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

import com.rf.psychological.base.repository.BaseRepository;
import com.rf.psychological.scale.dao.model.ScaleEntity;
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;

/**
 * @author zzf
 * @description:
 * @date 2021/5/14 10:54
 */
public interface ScaleRepository extends BaseRepository<ScaleEntity,String> {

    /**
     * 根据flag查询检测列表
     * @param flag
     * @return
     */
    @Query(value="select id,check_item,content,flag,question_no,question_type,score,score_direction,serial_no,weight,question_param from t_scale_info where flag = :flag order by question_no+0,serial_no+0 ",nativeQuery=true)
    List<ScaleEntity> getScaleByFlag(@Param("flag")String flag);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "delete from t_scale_info", nativeQuery = true)
    void deleteAll();

    /**
     * 根据id修改指定字段
     *
     * @return
     */
    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "UPDATE t_scale_info SET content = :answer, check_item = :checkItems WHERE id = :id ", nativeQuery = true)
    void updateScale(@Param("answer")String answer, @Param("checkItems")String checkItems, @Param("id")String id);

    @Transactional
    @Modifying
    @Query(value = "delete from t_scale_info where flag=:flag  ", nativeQuery = true)
    void deleteScaleByFlag(@Param("flag")String flag);

    /**
     * 根据flag和机构编号查询列表
     */
    @Query(value="SELECT tsci.* FROM t_scale_info tsci " +
            "JOIN t_subject_info tsui ON tsci.flag = tsui.flag " +
            "join t_institution_auth tia ON tsui.id = tia.b_id " +
            "WHERE tia.institution_no = :institutionNo AND tsui.flag = :flag ",nativeQuery=true)
    List<ScaleEntity> getScaleByFlagAndInstitutionNo(@Param("institutionNo") String institutionNo, @Param("flag") String flag);
}
