package com.uas.platform.b2b.dao;

import com.uas.platform.b2b.model.PurchaseOrder;
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 java.util.List;

@Repository
public interface PurchaseOrderDao extends JpaSpecificationExecutor<PurchaseOrder>, JpaRepository<PurchaseOrder, Long> {

	/**
	 * @param enUU
	 *            买方企业ID
	 * @param code
	 *            订单号
	 * @return
	 */
	public List<PurchaseOrder> findByEnUUAndCode(long enUU, String code);

	/**
	 * 获得每种单据状态的未读数量
	 *
	 * @param ids 未读单据id
	 * @return 返回各个状态的数量，Object数据第一个值为数量，第二个值为砖头
	 */
	@Query("select count(p), p.status from PurchaseOrderAll p where p.id in :ids and (p.end = 0 or p.end is null) and (p.status = 201 or p.status = 200) group by p.status")
	public List<Object[]> getUnreadCountEveryStatus(@Param("ids") List<Long> ids);

	/**
	 * 通过企业UU和来源id查询单据是否存在
	 *
	 * @param uu
	 * @param id
	 * @return
	 */
	List<PurchaseOrder> findByEnUUAndAndErpId(Long uu, Long id);

	/**
	 * 通过id更新采购单状态
	 *
	 * @param status 状态
	 * @param id id
	 */
	@Modifying
	@Transactional
	@Query("update PurchaseOrder set status = :status where id = :id")
	void updatePurchaseStatus(@Param("status") Short status, @Param("id") Long id);
}
