package com.rf.psychological.scale.dao.repository;

import com.rf.psychological.base.repository.BaseRepository;
import com.rf.psychological.scale.dao.dto.ResultDto;
import com.rf.psychological.scale.dao.model.WarnEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;

public interface WarnRepository extends BaseRepository<WarnEntity,String> {

    @Transactional
    @Modifying
    @Query(value = "delete from t_warn_info where dimension_id = :dimensionId and institution_no = :institutionNo",nativeQuery = true)
    void deleteByFlagAndInstitutionNo(@Param("dimensionId") String dimensionId, @Param("institutionNo") String institutionNo);

    @Transactional
    @Query(value = "SELECT  user_id ,result_id ,create_time ,flag from t_warn_info where flag = :flag  and institution_no = :institutionNo and " +
            "if(:searckKey is not null and :searckKey != '', user_id in(SELECT id FROM t_user_info where pet_name like CONCAT('%', :searckKey, '%')), 1 = 1) " +
            "GROUP BY  result_id,flag,create_time,user_id ORDER BY result_id,flag,create_time,user_id DESC limit :beginNum,:pageSize",nativeQuery = true)
    List<Map<String,Object>> findResultList(@Param("beginNum") int beginNum, @Param("pageSize") int pageSize,@Param("flag") String flag,
                                            @Param("institutionNo") String institutionNo, @Param("searckKey") String searckKey);

    List<WarnEntity> findByResultId(String resultId);
    @Query(value = "SELECT COUNT(1) FROM ( SELECT COUNT(1)   from t_warn_info where flag = :flag and institution_no = :institutionNo and " +
            "if(:searckKey is not null and :searckKey != '', user_id in(SELECT id FROM t_user_info where pet_name like CONCAT('%', :searckKey, '%')), 1 = 1) " +
            "GROUP BY  result_id,flag,create_time,user_id) t",nativeQuery = true)
    int findResultListCount(@Param("flag") String flag, @Param("institutionNo") String institutionNo, @Param("searckKey") String searckKey );

    @Query(value = "SELECT COUNT(*) FROM (SELECT flag FROM t_warn_info WHERE institution_no = :institutionNo GROUP BY flag) t ",nativeQuery = true)
    int findByInstitutionNo(@Param("institutionNo") String institutionNo);
}
