package com.uas.platform.b2b.dao;

import com.uas.platform.b2b.model.Vendor;
import com.uas.platform.core.data.repository.GenericRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.persistence.QueryHint;
import java.util.List;

@Repository
public interface VendorDao extends JpaSpecificationExecutor<Vendor>, GenericRepository<Vendor, Long> {

	/**
	 * @param myEnUU
	 *            我的企业ID
	 * @param vendUU
	 *            供应商企业ID
	 * @return
	 */
	@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value = "true") })
	@Query("from Vendor v where v.myEnUU = :myEnUU and v.vendorEnterprise.uu = :vendUU")
	public List<Vendor> findByMyEnUUAndVendUU(@Param("myEnUU") long myEnUU, @Param("vendUU") long vendUU);

	/**
	 * 按营业执照号查询供应商或客户是否存在
	 * 
	 * @param myEnBusinessCode
	 * @param VendBusinessCode
	 * @return
	 */
	@QueryHints({ @QueryHint(name = "org.hibernate.cacheable", value = "true") })
	@Query("from Vendor v where v.myEnterprise.enBussinessCode = :myEnBusinessCode and v.vendorEnterprise.enBussinessCode = :VendBusinessCode")
	public List<Vendor> findByMyEnBusinessCodeAndVendBusinessCode(@Param("myEnBusinessCode") String myEnBusinessCode,
			@Param("VendBusinessCode") String VendBusinessCode);

	public List<Vendor> findByMyEnUU(Long myEnUU);

	@Query("from Vendor v where v.vendEnUU = :vendUU and v.custswitch = 1")
	public List<Vendor> findByVendEnUU(@Param("vendUU") Long vendUU);

	/**
	 * 按类型查找客户
	 * 
	 * @param myEnUU
	 * @param isErp
	 * @param isSaas
	 * @return
	 */
	@Query("from Vendor v where v.vendEnUU = :vendEnUU and (v.myEnterprise.enIsErp = :enIsErp or v.myEnterprise.enSaasStatus = :enSaasStatus)")
	public List<Vendor> findCustByVendUUAndCustPlatform(@Param("vendEnUU") long vendEnUU, @Param("enIsErp") short isErp,
			@Param("enSaasStatus") short isSaas);

	/**
	 * 按类型查找指定客户
	 * 
	 * @param myEnUU
	 * @param isErp
	 * @param isSaas
	 * @return
	 */
	@Query("from Vendor v where v.myEnUU = :custEnUU and v.vendEnUU = :vendEnUU and (v.myEnterprise.enIsErp = :enIsErp or v.myEnterprise.enSaasStatus = :enSaasStatus)")
	public List<Vendor> findByCustAndVendAndCustPlatform(@Param("custEnUU") long custEnUU, @Param("vendEnUU") long vendEnUU,
			@Param("enIsErp") short isErp, @Param("enSaasStatus") short isSaas);

	/**
	 * 获得每种单据状态的未读数量
	 *
	 * @Param ids 未读单据id
	 * @return
	 */
	@Query("select count(p), p.status from Vendor p where p.id in :ids group by p.status")
	List<Object[]> getUnreadCountEveryStatus(@Param("ids") List<Long> ids);

	/**
	 * 寻找未同步到ERP的供应商信息
	 *
	 * @param myEnuu
	 * @param status
	 * @return
	 */
    List<Vendor> findByMyEnUUAndErpstatus(Long myEnuu, Integer status);

}
