<?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.pangu.school.mapper.SchoolGradeMapper">

    <resultMap id="SchoolGradeResult" type="com.pangu.school.domain.entity.SchoolGrade">
        <id property="id" column="id"/>
        <result property="schoolId" column="school_id"/>
        <result property="gradeId" column="grade_id"/>
        <result property="orderNum" column="order_num"/>
        <result property="status" column="status"/>
        <result property="createBy" column="create_by"/>
        <result property="createTime" column="create_time"/>
    </resultMap>

    <!-- 扩展结果映射，包含年级名称 -->
    <resultMap id="SchoolGradeExtResult" type="com.pangu.school.domain.entity.SchoolGrade" extends="SchoolGradeResult">
        <association property="grade" javaType="com.pangu.base.domain.Grade">
            <result property="gradeName" column="grade_name"/>
        </association>
    </resultMap>

    <sql id="selectSchoolGradeVo">
        SELECT sg.id, sg.school_id, sg.grade_id, sg.order_num, sg.status,
               sg.create_by, sg.create_time,
               g.grade_name
        FROM pg_school_grade sg
        LEFT JOIN pg_grade g ON sg.grade_id = g.grade_id AND g.del_flag = '0'
        WHERE sg.del_flag = '0'
    </sql>

    <select id="selectBySchoolIds" resultMap="SchoolGradeResult">
        SELECT sg.id, sg.school_id, sg.grade_id, sg.order_num, sg.status,
               sg.create_by, sg.create_time,
               g.grade_name
        FROM pg_school_grade sg
        LEFT JOIN pg_grade g ON sg.grade_id = g.grade_id AND g.del_flag = '0'
        WHERE sg.del_flag = '0'
        AND sg.school_id IN
        <foreach collection="schoolIds" item="schoolId" open="(" separator="," close=")">
            #{schoolId}
        </foreach>
        ORDER BY sg.order_num
    </select>

    <select id="exists" resultType="boolean">
        SELECT COUNT(*) > 0
        FROM pg_school_grade
        WHERE del_flag = '0'
        AND school_id = #{schoolId}
        AND grade_id = #{gradeId}
    </select>

    <select id="countBySchoolId" parameterType="Long" resultType="int">
        SELECT COUNT(*)
        FROM pg_school_grade
        WHERE del_flag = '0'
        AND school_id = #{schoolId}
    </select>

    <select id="countByGradeId" parameterType="Long" resultType="int">
        SELECT COUNT(*)
        FROM pg_school_grade
        WHERE del_flag = '0'
        AND grade_id = #{gradeId}
    </select>

    <insert id="batchInsert">
        INSERT INTO pg_school_grade (school_id, grade_id, order_num, status, create_by, create_time, del_flag)
        VALUES
        <foreach collection="list" item="item" separator=",">
            (#{item.schoolId}, #{item.gradeId}, #{item.orderNum}, #{item.status}, #{item.createBy}, #{item.createTime}, '0')
        </foreach>
    </insert>

</mapper>
