package com.uas.platform.b2b.dao;

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

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 org.springframework.transaction.annotation.Transactional;

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

@Repository
@Transactional
public interface PurchaseOrderItemDao extends JpaSpecificationExecutor<PurchaseOrderItem>, JpaRepository<PurchaseOrderItem, Long> {

	/**
	 * 按订单明细状态查找订单明细
	 * 
	 * @param statusCode
	 * @return
	 */
	@Query("select count(d) from PurchaseOrderItem d where d.order.id = :orderId and d.status = :status")
	public int getCountByStatus(@Param("orderId") long orderId, @Param("status") short status);
	
	/**
	 * 按订单明细状态查找全部回复的订单明细
	 * 
	 * @param statusCode
	 * @return
	 */
	@Query("select count(d) from PurchaseOrderItem d where d.order.id = :orderId and d.replyQty = d.qty")
	public int getCountByReply(@Param("orderId") long orderId);
	
	/**
	 * 按订单明细结案情况查找订单明细
	 * 
	 * @param statusCode
	 * @return
	 */
	@Query("select count(d) from PurchaseOrderItem d where d.order.id = :orderId and d.end = :end")
	public int getCountByEnd(@Param("orderId") long orderId, @Param("end") short end);

	/**
	 * 按订单单号和序号查找订单明细
	 * 
	 * @param enUU
	 * @param orderCode
	 * @param number
	 * @return
	 */
	@Query("from PurchaseOrderItem d where d.order.enUU = :enUU and d.order.code = :orderCode and d.number = :number")
	public List<PurchaseOrderItem> findByEnUUAndOrderCodeAndNumber(@Param("enUU") long enUU, @Param("orderCode") String orderCode,
			@Param("number") Short number);

	/**
	 * 按供应商ID和结案、反结案传输状态查找订单明细
	 * 
	 * @param vendUU
	 * @param endStatus
	 * @return
	 */
	@Query("from PurchaseOrderItem d where d.order.vendUU = :vendUU and d.endStatus = :endStatus")
	public List<PurchaseOrderItem> findByVendUUAndEndStatus(@Param("vendUU") long vendUU, @Param("endStatus") short endStatus);

	/**
	 * 按回复记录更新采购明细的回复状态
	 * 
	 * @param qty
	 * @param delivery
	 * @param remark
	 * @param id
	 */
	@Modifying(clearAutomatically = true)
	@Query("update PurchaseOrderItem p set p.replyQty=(select sum(r.qty) from PurchaseOrderReply r where r.orderItem=p),p.replyDelivery= :delivery,p.replyRemark= :remark where p.id= :id")
	public void updateByReply(@Param("delivery") Date delivery, @Param("remark") String remark, @Param("id") long id);
}
