package com.rf.psychological.institution.repository;

import com.rf.psychological.base.repository.BaseRepository;
import com.rf.psychological.institution.model.InstitutionEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface InstitutionRepository extends BaseRepository<InstitutionEntity, String> {

    /**
     * 查询所有机构名称
     *
     * @param pageNum
     * @param pageSize
     * @param searchKey
     * @return
     */
    @Query(value = "select id,institution_name,institution_no,login_name,password from t_institution_info  where if(:searchKey is not null and :searchKey!='',institution_no like CONCAT('%',:searchKey,'%')  ,1=1) or if(:searchKey is not null and :searchKey!='',institution_name like CONCAT('%',:searchKey,'%')  ,1=1)  limit :pageNum ,:pageSize", nativeQuery = true)
    List<InstitutionEntity> findAllInstitutionByName(@Param("pageNum") int pageNum, @Param("pageSize") int pageSize, @Param("searchKey") String searchKey);

    @Query(value = "select count(1) from t_institution_info  where if(:searchKey is not null and :searchKey!='',institution_no like CONCAT('%',:searchKey,'%') ,1=1) or if(:searchKey is not null and :searchKey!='',institution_name like CONCAT('%',:searchKey,'%') ,1=1)", nativeQuery = true)
    int allInstitutionNum(@Param("searchKey") String searchKey);

    /**
     * 根据机构编号查询机构信息
     * @param institutionNo
     * @return
     */
    //@Query(value = "select id,institution_name,institution_no,login_name,password from t_institution_info  where institution_no = :institutionNo", nativeQuery = true)
    //InstitutionEntity findByInstitutionNo(@Param("institutionNo") String institutionNo);
    InstitutionEntity findByInstitutionNo(String institutionNo);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "update t_institution_info set institution_no = :institutionNo where id = :institutionId ", nativeQuery = true)
    void updateById(@Param("institutionId") String institutionId, @Param("institutionNo") String institutionNo);

    List<InstitutionEntity> findAllByInstitutionName(String institutionName);
}
