package org.dromara.main.mapper;

import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.dromara.common.mybatis.core.mapper.BaseMapperPlus;
import org.dromara.main.domain.MainExamApply;
import org.dromara.main.domain.vo.MainExamApplyRecordVo;

import java.util.List;

public interface MainExamApplyMapper extends BaseMapperPlus<MainExamApply, MainExamApply> {

    @Select("SELECT * FROM main_exam_apply WHERE evaluation_id = #{evaluationId} AND tenant_id = #{tenantId} AND student_id = #{studentId} LIMIT 1")
    MainExamApply selectAnyByUniqueKey(@Param("evaluationId") Long evaluationId,
                                       @Param("tenantId") String tenantId,
                                       @Param("studentId") Long studentId);

    @Update("UPDATE main_exam_apply SET del_flag = '0', apply_source = '3', apply_status = '0', schedule_start_time = NOW(), deadline_time = NULL, max_attempt_count = 1, finished_time = NULL, final_result = NULL, update_time = NOW() WHERE id = #{id}")
    int restoreDeletedApply(@Param("id") Long id);

    @InterceptorIgnore(tenantLine = "true")
    @Select("""
        SELECT
            a.id,
            a.evaluation_id AS evaluationId,
            e.evaluation_name AS evaluationName,
            p.post_name AS positionName,
            a.student_id AS studentId,
            a.apply_status AS applyStatus,
            a.final_result AS finalResult,
            CASE
                WHEN a.final_result = '1' THEN '通过'
                WHEN a.final_result = '2' THEN '未通过'
                WHEN a.apply_status = '2' THEN '待评分'
                WHEN a.apply_status = '1' THEN '测评中'
                ELSE '待测评'
            END AS statusText,
            CASE
                WHEN a.final_result = '1' THEN 'pass'
                WHEN a.final_result = '2' THEN 'fail'
                ELSE 'pending'
            END AS statusType,
            a.schedule_start_time AS scheduleStartTime,
            a.deadline_time AS deadlineTime,
            a.finished_time AS finishedTime,
            a.create_time AS createTime
        FROM main_exam_apply a
        LEFT JOIN main_exam_evaluation e ON a.evaluation_id = e.id
        LEFT JOIN main_position p ON e.position_id = p.id
        WHERE IFNULL(a.del_flag, '0') = '0'
          AND a.student_id = #{studentId}
        ORDER BY COALESCE(a.finished_time, a.update_time, a.create_time) DESC, a.id DESC
        """)
    List<MainExamApplyRecordVo> selectRecordListByStudentId(@Param("studentId") Long studentId);
}
