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

import com.rf.psychological.base.repository.BaseRepository;
import com.rf.psychological.plan.dao.model.TestPlanEntity;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author lpf
 * @description:
 * @date 2022/1/6 12:42
 */
public interface TestPlanRepository extends BaseRepository<TestPlanEntity, String> {


    /**
     * 根据id查看预约记录
     * @param id
     * @param searchKey
     * @param beginTime
     * @param endTime
     * @param status
     * @return
     */
    @Query(value = "select id, create_time, create_user, create_user_id, name, test_begin_time, test_end_time, update_time, institution_no,status\n" +
            "from t_test_plan\n" +
            "where id=?1 and if(?2 is not null and ?2 !='',t_test_plan.name like CONCAT('%',?2,'%') ,1=1)\n" +
            "and  if(?3 is not null and ?3!='',test_begin_time>=?3 ,1=1)  and if(?4 is not null and ?4!='', test_end_time<=?4 ,1=1) " +
            "and  if(?5 is not null and ?5!='',status = ?5 ,1=1)  order by create_time desc",
            countQuery = "select count(*)\n" +
                    "from t_test_plan\n" +
                    "where id=?1 and if(?2 is not null and ?2 !='',t_test_plan.name like CONCAT('%',?2,'%') ,1=1)\n" +
                    "and  if(?3 is not null and ?3!='',test_begin_time>?3 ,1=1)  and if(?4 is not null and ?4!='', test_end_time<?4 ,1=1)  " +
                    "and  if(?5 is not null and ?5!='',status = ?5 ,1=1)",
            nativeQuery = true)
    TestPlanEntity findAllById(String id, String searchKey, Date beginTime, Date endTime, String status);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "update t_test_plan set status=?2 where id=?1", nativeQuery = true)
    void updateStatus(String id, int status);

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = "update t_test_plan set name=?2 , test_begin_time=?3,test_end_time=?4  where id=?1", nativeQuery = true)
    void updateInfo(String id, String name, Date beginTestTime, Date endTestTime);

    /**
     * 到达开始时间未开始的测试计划
     * 到达结束时间未结束的测试计划
     */
    @Query(value = "select id, create_time, create_user, create_user_id, name, test_begin_time, test_end_time, update_time, institution_no,status from t_test_plan " +
            "where (test_begin_time <= now() and status = 2)or (test_end_time <= now() and status = 3)",nativeQuery = true)
    List<TestPlanEntity> findPlan();

    List<TestPlanEntity> findAllByInstitutionNo(String institutionNo);
}
