package com.uas.platform.b2b.dao;

import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.uas.platform.b2b.model.MakeOrder;

@Repository
public interface MakeOrderDao extends JpaSpecificationExecutor<MakeOrder>, JpaRepository<MakeOrder, Long> {

	/**
	 * 按所属企业及编号查找委外加工单
	 * 
	 * @param enUU
	 * @param code
	 * @return
	 */
	public List<MakeOrder> findByEnUUAndCode(Long enUU, String code);
	
	/**
	 * 卖家根据卖家UU号和下载状态获取需要下载的客户委外加工单
	 * @return
	 */
	public List<MakeOrder> findByVendUUAndSendStatus(Long vendUU, Short sendStatus);

	/**
	 * 按回复记录更新采购明细的回复状态
	 * 
	 * @param qty
	 * @param delivery
	 * @param remark
	 * @param id
	 */
	@Transactional
	@Modifying(clearAutomatically = true)
	@Query("update MakeOrder m set m.replyQty=(select sum(r.qty) from MakeOrderReply r where r.orderId=:id),m.replyDelivery= :delivery,m.replyRemark= :remark where m.id= :id")
	public void updateByReply(@Param("delivery") Date delivery, @Param("remark") String remark, @Param("id") long id);
	
	/**
	 * 根据供应商UU号和结案传输状态获取委外加工单
	 * @param end
	 * @param endSendStatus
	 * @return
	 */
	public List<MakeOrder> findByVendUUAndEndSendStatus(Long vendUU, Short endSendStatus);
	
	/**
	 * 获得每种单据状态的数量
	 *
	 * @Param ids 单据id
	 * @return
	 */
	@Query("select count(p), p.status from MakeOrder p where p.id in :ids group by p.status")
	List<Object[]> getUnreadCountEveryStatus(@Param("ids") List<Long> ids);

}
