<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ruoyi.dz.mapper.DzClassesMapper">

    <resultMap type="DzClasses" id="DzClassesResult">
        <result property="classId"    column="class_id"    />
        <result property="deptId"    column="dept_id"    />
        <result property="schoolId"    column="school_id"    />
        <result property="year"    column="year"    />
        <result property="name"    column="name"    />
        <result property="online"    column="online"    />
        <result property="status"    column="status"    />
        <result property="stats"    column="stats"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
        <result property="isDefault"    column="is_default"    />
        <association property="school"     javaType="DzSchool"         resultMap="DzSchoolResult" />
    </resultMap>

    <resultMap type="DzSchool" id="DzSchoolResult">
        <result property="id"    column="id"    />
        <result property="name"    column="school_name"    />
        <result property="deptId"    column="dept_id"    />
        <result property="location"    column="location"    />
        <result property="pro"    column="pro"    />
        <result property="city"    column="city"    />
        <result property="area"    column="area"    />
    </resultMap>

    <select id="selectClassesDirectedBuildStats" resultType="com.alibaba.fastjson2.JSONObject">
        SELECT c.`class_id` classId, c.`name` className, lt.`batch_id` batchId, lt.`name` batchName, count(*) `total`, SUM(if(ls.`major_plan_id` IS NULL, 1, 0)) unexact,
               SUM(IF(ls.`major_plan_id` IS not NULL and ts.`student_id` IS NULL, 1, 0)) unsend,
               SUM(IF(ls.`major_plan_id` IS not NULL and ts.`student_id` IS NOT NULL and ts.`status` != 4 , 1, 0)) unfinish,
               sum(if(ls.`major_plan_id` IS NOT NULL and ts.`student_id` is not null AND ts.`status` = 4 , 1, 0)) send
        FROM `dz_teacher_class` tc
        join `learn_student` ls on tc.`class_id` = ls.`class_id`
        join `dz_classes` c on ls.`class_id` = c.`class_id`
        JOIN `sys_user` u ON ls.`student_id` = u.`user_id`
        join `learn_test` lt on lt.`year` = #{year} <if test="batchId != null"> and lt.`batch_id` =  #{batchId} </if>
        LEFT JOIN `learn_test_student` ts ON ts.`student_id` = ls.`student_id` AND ts.`batch_id` = lt.`batch_id` AND ts.`class_id` = tc.`class_id`
            <if test="buildType != null"> AND ts.`build_type` = #{buildType} </if>
            <if test="subjectId != null"> and ts.`subject_id` = #{subjectId} </if>
        <where>tc.`teacher_id` = #{teacherId}
            <if test="classId != null"> AND ls.`class_id` = #{classId}</if>
            <if test="universityId != null"> AND ls.`university_id` = #{universityId}</if>
            <if test="majorGroup != null"> AND ls.`major_group` = #{majorGroup}</if>
            <if test="majorPlanId != null"> AND ls.`major_plan_id` = #{majorPlanId}</if>
            <if test="examType != null and examType != ''"> AND u.`exam_type` = #{examType}</if>
        </where>
        group by c.`class_id`, c.`name`, lt.`batch_id`, lt.`name`
        order by c.`class_id`, c.`name`, lt.`batch_id`, lt.`name`
    </select>

    <select id="selectClassesBuildStats" resultType="com.alibaba.fastjson2.JSONObject">
        SELECT c.`class_id` classId, c.`name` className, lt.`batch_id` batchId, lt.`name` batchName, count(*) `total`,
               SUM(IF(ts.`student_id` IS NULL, 1, 0)) unsend,
               SUM(IF(ts.`student_id` IS NOT NULL and ts.`status` != 4 , 1, 0)) unfinish,
               sum(if(ts.`student_id` is not null AND ts.`status` = 4 , 1, 0)) send
         FROM `dz_teacher_class` tc
         join `learn_student` ls on tc.`class_id` = ls.`class_id`
         JOIN sys_user u ON ls.`student_id` = u.`user_id`
         join `dz_classes` c on ls.`class_id` = c.`class_id`
         join `learn_test` lt on lt.`year` = #{year} <if test="batchId != null"> and lt.`batch_id` =  #{batchId} </if>
         LEFT JOIN `learn_test_student` ts ON ts.`student_id` = ls.`student_id` AND ts.`class_id` = tc.`class_id`
            <if test="batchId != null"> and ts.`batch_id` =  #{batchId} </if>
            <if test="buildType != null"> AND ts.`build_type` = #{buildType} </if>
            <if test="subjectId != null"> and ts.`subject_id` = #{subjectId} </if>
        <where>tc.`teacher_id` = #{teacherId}
            <if test="classId != null"> AND ls.`class_id` = #{classId}</if>
            <if test="universityId != null"> AND ls.`university_id` = #{universityId}</if>
            <if test="majorGroup != null"> AND ls.`major_group` = #{majorGroup}</if>
            <if test="majorPlanId != null"> AND ls.`major_plan_id` = #{majorPlanId}</if>
            <if test="examType != null  and examType != ''"> AND u.`exam_type` = #{examType}</if>
        </where>
        group by c.`class_id`, c.`name`, lt.`batch_id`, lt.`name`
        order by c.`class_id`, c.`name`, lt.`batch_id`, lt.`name`
    </select>

    <select id="getPaperStudentRecords" resultType="com.alibaba.fastjson2.JSONObject">
      SELECT ts.examinee_id examineeId, ls.`student_id` studentId, u.`nick_name` studentName, dc.`name` className, u.`phonenumber` mobile, ts.`batch_id` batchId, ts.`subject_id` subjectId, ts.`paper_id` paperId, lp.`paperName`, lp.`fenshu` total, le.`score`, le.`score_rate` rate,
              lt.`name` batchName, ds.`subject_name` subjectName,
              CASE WHEN ls.`major_plan_id` IS NULL AND #{buildType} IN ('ExactHand', 'ExactIntelligent') THEN '10' WHEN ts.`student_id` IS NULL THEN '20' WHEN ts.`status` != 4 THEN '30' ELSE '40' END state
        FROM `learn_student` ls
        JOIN `sys_user` u ON ls.`student_id` = u.`user_id`
        JOIN `dz_classes` dc ON dc.`class_id` = ls.`class_id`
        JOIN `learn_test` lt ON lt.`year` = #{year} <if test="batchId != null"> and lt.`batch_id` =  #{batchId} </if>
        LEFT JOIN `learn_test_student` ts ON ts.`student_id` = ls.`student_id` and ts.`batch_id` = lt.`batch_id`
        <if test="buildType != null"> AND ts.`build_type` = #{buildType} </if>
        <if test="subjectId != null"> and ts.`subject_id` = #{subjectId} </if>
        LEFT JOIN `dz_subject` ds ON ds.`subject_id` = ts.`subject_id`
        LEFT JOIN `learn_examinee` le ON le.examinee_id = ts.examinee_id
        LEFT JOIN `learn_paper` lp ON ts.`paper_id` = lp.`id`
        <where> ls.`class_id` = #{classId}
            <if test="universityId != null"> AND ls.`university_id` = #{universityId}</if>
            <if test="majorGroup != null"> AND ls.`major_group` = #{majorGroup}</if>
            <if test="majorPlanId != null"> AND ls.`major_plan_id` = #{majorPlanId}</if>
            <if test="examType != null  and examType != ''"> AND u.`exam_type` = #{examType}</if>
        </where>
    </select>

    <select id="selectClassesBuildStatsDetail" resultType="com.alibaba.fastjson2.JSONObject">
        SELECT 
            u.`nick_name` AS studentName,
            CONCAT(u.`nick_name`, '-', IFNULL(u.`phonenumber`, '')) AS namePhone,
            IFNULL(card.`card_no`, '') AS cardNo,
            IFNULL(d.`dept_name`, '') AS institution,
            IFNULL(u.`location`, IFNULL(reg_school.`pro`, '')) AS province,
            IFNULL(agent.`name`, '') AS agent,
            IFNULL(u.`end_year`, '') AS year,
            IFNULL(reg_school.`name`, '') AS registerSchool,
            IFNULL(reg_class.`name`, '') AS registerClass,
            IFNULL(train_school.`name`, '') AS trainSchool,
            IFNULL(train_class.`name`, '') AS trainClass,
            IFNULL(u.`exam_type`, '') AS examType,
            u.directed_study AS direct
        FROM `dz_teacher_class` tc
        JOIN `learn_student` ls ON tc.`class_id` = ls.`class_id`
        JOIN `dz_classes` c ON ls.`class_id` = c.`class_id`
        JOIN `sys_user` u ON ls.`student_id` = u.`user_id`
        JOIN `learn_test` lt ON lt.`year` = #{year} <if test="batchId != null"> AND lt.`batch_id` = #{batchId} </if>
        LEFT JOIN `sys_dept` d ON u.`dept_id` = d.`dept_id`
        LEFT JOIN `dz_cards` card ON u.`card_id` = card.`card_id`
        LEFT JOIN `dz_school` reg_school ON card.`school_id` = reg_school.`id`
        LEFT JOIN `dz_classes` reg_class ON card.`class_id` = reg_class.`class_id`
        LEFT JOIN `dz_school` train_school ON ls.`school_id` = train_school.`id`
        LEFT JOIN `dz_classes` train_class ON ls.`class_id` = train_class.`class_id`
        LEFT JOIN `dz_agent` agent ON (card.`agent_id` = agent.`agent_id` OR card.`leaf_agent_id` = agent.`agent_id` OR (u.`invite_code` IS NOT NULL AND u.`invite_code` != '' AND CAST(u.`invite_code` AS UNSIGNED) = agent.`agent_id`))
        LEFT JOIN `learn_test_student` ts ON ts.`student_id` = ls.`student_id` AND ts.`batch_id` = lt.`batch_id` AND ts.`class_id` = tc.`class_id`
            <if test="buildType != null"> AND ts.`build_type` = #{buildType} </if>
            <if test="subjectId != null"> AND ts.`subject_id` = #{subjectId} </if>
        <where>
            tc.`teacher_id` = #{teacherId}
            <if test="classId != null"> AND ls.`class_id` = #{classId}</if>
            <if test="batchId != null"> AND lt.`batch_id` = #{batchId}</if>
            <if test="universityId != null"> AND ls.`university_id` = #{universityId}</if>
            <if test="majorPlanId != null"> AND ls.`major_plan_id` = #{majorPlanId}</if>
            <if test="examType != null and examType != ''"> AND u.`exam_type` = #{examType}</if>
            <!-- 根据统计类型过滤 -->
            <choose>
                <!-- send: 组卷已完成 -->
                <when test="statType == 'send'">
                    AND ls.`major_plan_id` IS NOT NULL 
                    AND ts.`student_id` IS NOT NULL 
                    AND ts.`status` = 4
                </when>
                <!-- total: 班级人数 -->
                <when test="statType == 'total'">
                    <!-- 不添加额外条件，返回所有学生 -->
                </when>
                <!-- unexact: 未定向未组卷 -->
                <when test="statType == 'unexact'">
                    AND ls.`major_plan_id` IS NULL
                </when>
                <!-- unfinish: 组卷未完成 -->
                <when test="statType == 'unfinish'">
                    AND ls.`major_plan_id` IS NOT NULL 
                    AND ts.`student_id` IS NOT NULL 
                    AND ts.`status` != 4
                </when>
                <!-- unsend: 定向未组卷 -->
                <when test="statType == 'unsend'">
                    AND ls.`major_plan_id` IS NOT NULL 
                    AND ts.`student_id` IS NULL
                </when>
            </choose>
        </where>
        ORDER BY u.`user_id` DESC
    </select>


    <sql id="selectDzClassesVo">
        select t1.class_id, t1.dept_id, t1.school_id, t1.year, t1.name, t1.online, t1.status, t1.stats, t1.create_time, t1.update_time,t1.is_default,
        t2.id, t2.name school_name, t2.dept_id, t2.pro, t2.city, t2.area
        from dz_classes t1
        left join dz_school t2 on t1.school_id=t2.id
    </sql>

    <select id="selectDzClassesList" parameterType="DzClasses" resultMap="DzClassesResult">
        <include refid="selectDzClassesVo"/>
        <where>
            <if test="schoolId != null "> and t1.school_id = #{schoolId}</if>
            <if test="deptId != null and deptId > 0 "> and t1.dept_id = #{deptId}</if>
            <if test="deptId == 0 "> and t1.dept_id is null </if>
            <if test="year != null "> and t1.year = #{year}</if>
            <if test="name != null  and name != ''"> and t1.name like concat('%', #{name}, '%')</if>
            <if test="online != null "> and t1.online = #{online}</if>
            <if test="status != null "> and t1.status = #{status}</if>
            <if test="isDefault != null "> and t1.is_default = #{isDefault}</if>
            <if test="stats != null  and stats != ''"> and t1.stats = #{stats}</if>
        </where>
    </select>

    <select id="selectClassesForTeacher" parameterType="Long" resultMap="DzClassesResult">
        SELECT c.* FROM `dz_teacher_class` tc
        JOIN `dz_classes` c ON tc.`class_id` = c.`class_id`
        WHERE tc.`teacher_id` = #{teacherId} AND NOW() &lt; tc.`out_date`
    </select>

    <select id="selectClassesByIds" resultMap="DzClassesResult">
        <include refid="selectDzClassesVo"/>
        where t1.class_id in <foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
    </select>

    <select id="selectDzClassesListBySchoolId" resultMap="DzClassesResult">
        select * from dz_classes t1
        where t1.school_id = #{schoolId}
    </select>

    <select id="selectDzClassesListByCampusId" resultMap="DzClassesResult">
        select * from dz_classes t1
        where t1.school_id = #{campusId}
    </select>

    <select id="selectDzClassesBySchoolIds" resultMap="DzClassesResult">
        <include refid="selectDzClassesVo"/>
        where t1.school_id in 
        <foreach collection="schoolIds" item="schoolId" open="(" separator="," close=")">
            #{schoolId}
        </foreach>
    </select>

    <select id="selectDzClassesByClassId" parameterType="Long" resultMap="DzClassesResult">
        <include refid="selectDzClassesVo"/>
        where t1.class_id = #{classId}
    </select>

    <insert id="insertDzClasses" parameterType="DzClasses" useGeneratedKeys="true" keyProperty="classId">
        insert into dz_classes
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="deptId != null">dept_id,</if>
            <if test="schoolId != null">school_id,</if>
            <if test="year != null">year,</if>
            <if test="name != null and name != ''">name,</if>
            <if test="online != null">online,</if>
            <if test="status != null">status,</if>
            <if test="stats != null">stats,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateTime != null">update_time,</if>
            <if test="isDefault != null">is_default,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="deptId != null">#{deptId},</if>
            <if test="schoolId != null">#{schoolId},</if>
            <if test="year != null">#{year},</if>
            <if test="name != null and name != ''">#{name},</if>
            <if test="online != null">#{online},</if>
            <if test="status != null">#{status},</if>
            <if test="stats != null">#{stats},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateTime != null">#{updateTime},</if>
            <if test="isDefault != null">#{isDefault},</if>
        </trim>
    </insert>

    <update id="updateDzClasses" parameterType="DzClasses">
        update dz_classes
        <trim prefix="SET" suffixOverrides=",">
            <if test="deptId != null">dept_id = #{deptId},</if>
            <if test="schoolId != null">school_id = #{schoolId},</if>
            <if test="year != null">year = #{year},</if>
            <if test="name != null and name != ''">name = #{name},</if>
            <if test="online != null">online = #{online},</if>
            <if test="status != null">status = #{status},</if>
            <if test="stats != null">stats = #{stats},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="isDefault != null">is_default = #{isDefault},</if>
        </trim>
        where class_id = #{classId}
    </update>

    <delete id="deleteDzClassesByClassId" parameterType="Long">
        delete from dz_classes where class_id = #{classId}
    </delete>

    <delete id="deleteDzClassesByClassIds" parameterType="String">
        delete from dz_classes where class_id in
        <foreach item="classId" collection="array" open="(" separator="," close=")">
            #{classId}
        </foreach>
    </delete>

    <!-- 校验班级名称在同一学校下是否唯一 -->
    <select id="checkClassName" resultType="int">
        select count(1) from dz_classes where school_id = #{schoolId} and name = #{name}
        <if test="classId != null">
            and class_id != #{classId}
        </if>
    </select>
</mapper>
