<?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.qmth.exam.reserve.dao.ExamSiteDao">

    <select id="countExamSiteCapacityById" resultType="java.lang.Integer">
        select sum(capacity)
        from t_exam_room
        where exam_site_id = #{examSiteId}
          and enable = 1
    </select>

    <select id="findAllExamSiteCapacityList" resultType="com.qmth.exam.reserve.bean.examsite.ExamSiteCapacityInfo">
        select es.id                                                                                         as examSiteId,
               (select sum(er.capacity) from t_exam_room er where er.exam_site_id = es.id and er.enable = 1) as capacity
        from t_exam_site es
    </select>

    <select id="findInfoById" resultType="com.qmth.exam.reserve.bean.examsite.ExamSiteCacheBean">
        select es.id          examSiteId,
               es.name        examSiteName,
               es.address     examSiteAddress,
               es.category_id categoryId,
               c.name         categoryName
        from t_exam_site es
                 inner join t_category c on c.id = es.category_id
        where es.id = #{examSiteId}
    </select>

    <select id="page" resultType="com.qmth.exam.reserve.bean.examsite.ExamSiteVO">
        SELECT
        s.id,
        s.NAME,
        s.CODE,
        g.NAME teachingName,
        g.id teachingId,
        s.address,
        s.capacity,
        s.enable
        FROM
        t_exam_site s,
        t_category g
        WHERE
        s.category_id = g.id
        <if test="req.teachingId != null">
            and s.category_id=#{req.teachingId}
        </if>
        <if test="req.name != null and req.name !=''">
            and s.name like concat('%',#{req.name}, '%')
        </if>
        <if test="req.enable != null">
            and s.enable=#{req.enable}
        </if>
        order by s.update_time desc
    </select>

    <select id="countExamSiteTimePeriodCapacity" resultType="java.lang.Integer">
        SELECT IFNULL(SUM(er.capacity), 0) AS capacity
        FROM t_exam_room er
                 LEFT JOIN t_time_period_exam_room tper ON er.id = tper.exam_room_id
            AND tper.time_period_id = #{timePeriodId}
        WHERE er.ENABLE = 1
          AND er.exam_site_id = #{examSiteId}
          AND (tper.id IS NULL OR tper.ENABLE = 1)
    </select>

    <update id="updateExamSiteCapacity">
        UPDATE t_exam_site
        SET capacity = (SELECT ifNULL(sum(capacity),0) FROM t_exam_room WHERE exam_site_id = #{examSiteId} AND ENABLE = 1)
        WHERE id = #{examSiteId};
    </update>

</mapper>
