package com.qmth.qrzk.dao.repositories;

import java.util.List;

import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import com.qmth.qrzk.supplypaper.model.SupplyProvInfo;

/**
 * 供卷省份
 * @author zhengmin
 *
 */
public interface SupplyProvInfoRepo extends JpaRepository<SupplyProvInfo, Long> {

	/**
	 * 根据批次和省份代码查找
	 * @param batchId
	 * @param provCode
	 * @param sort
	 * @return
	 */
	List<SupplyProvInfo> findByBatchIdAndProvCode(int batchId,int provCode,Sort sort);
	
	int countByProvCodeAndBatchId(int provCode,int batchId);
	
	/**
	 * 查询所有供卷省份
	 * @param batchId
	 * @return
	 */
	@Query("SELECT DISTINCT c.provCode,c.provName FROM SupplyProvInfo AS c WHERE c.batchId = ?1 order by c.provCode")
	List<Object[]> findDistinctProvs(int batchId);
	
	@Query(value="SELECT COUNT(*) FROM qr_supply_prov_info t1 where t1.batch_id = ?1 and t1.prov_code = 54 and " +
			"NOT EXISTS (SELECT t2.course_code FROM qr_supply_prov_info t2 where t2.course_code = t1.course_code and " +
			"t2.batch_id = ?1 and t2.prov_code = 51)",nativeQuery=true)
	int countXIZANGAlone(int batchId);
	
	/**
	 * 删除没有关联供卷课程的省份
	 */
	@Modifying
	@Query("delete from SupplyProvInfo where supplyCourse is null")
	void deleteSupplyCourseIsNull();
	
	/**
	 * 根据批次查找
	 * @param batchId
	 * @param sort
	 * @return
	 */
	List<SupplyProvInfo> findByBatchId(int batchId, Sort sort);
	
	/**
	 * 根据批次和课程查找
	 * @param batchId
	 * @param courseCode
	 * @param sort
	 * @return
	 */
	List<SupplyProvInfo> findByBatchIdAndCourseCode(int batchId, String courseCode, Sort sort);
	
	/**
	 * 根据批次、课程、省份查找
	 * @param batchId
	 * @param courseCode
	 * @param provCode
	 * @return
	 */
	List<SupplyProvInfo> findByBatchIdAndCourseCodeAndProvCode(int batchId, String courseCode,int provCode);
}
