<?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.srs.dormitory.mapper.DmsBuildingDeptMapper">
	
	<!-- 通用查询映射结果 -->
	<resultMap id="BaseResultMap" type="com.srs.dormitory.domain.DmsBuildingDept">
		<id column="id" property="id"/>
		<result column="building_id" property="buildingId"/>
		<result column="dept_id" property="deptId"/>
	</resultMap>
	<select id="selectGenderCount" resultType="com.srs.dormitory.domain.Vo.GenderVo">
		SELECT stu.gender,
		       COUNT(*) AS total_count
		FROM srs_student stu
			     JOIN srs_class class ON stu.class_id = class.class_id
			     JOIN srs_grade grade ON class.grade_id = grade.grade_id
			     JOIN srs_majors major ON class.major_id = major.major_id
			     JOIN sys_dept dept ON major.college_id = dept.dept_id
		WHERE dept.dept_id = #{id}
		  AND class.grade_id = #{gradeId}
		GROUP BY stu.gender
	</select>
	<select id="selectDeptId" resultType="com.srs.dormitory.domain.Vo.GendersVo">
		SELECT dept_id,
		       dept_name
		FROM sys_dept
	</select>
	<select id="selectEmptyDormitory" resultType="com.srs.dormitory.domain.Vo.EmptyDormitoryVo">
		SELECT b.id                                      AS building_id,
		       b.`name`,
		       gender,
		       IFNULL(
				       (SELECT SUM(bed_count)
				        FROM dms_dormitory_building b
					             JOIN dms_dormitory_building_info binfo ON b.id = binfo.building_id
				        WHERE b.id = #{id}),
				       0
			       ) - IFNULL(SUM(occupancy), 0)         AS remaining_beds,
		       COUNT(CASE WHEN occupancy = 0 THEN 1 END) AS empty_dormitory
		FROM dms_dormitory_building b
			     left JOIN dms_dormitory_building_info binfo ON b.id = binfo.building_id
			     left JOIN dms_dormitory_unit unit ON b.id = unit.building_id
			     left JOIN dms_dormitory dor ON dor.unit_id = unit.id
		WHERE b.id = #{id}
		GROUP BY b.`name`,
		         gender,
		         b.id
	</select>
	<select id="selectBuilding" resultType="java.util.Map">
		SELECT
			b.id AS buildingId,
			b.name AS buildingName
		FROM
			sys_dept d
				JOIN
			dms_building_dept bd ON d.dept_id = bd.dept_id
				JOIN
			dms_dormitory_building b ON bd.building_id = b.id WHERE d.dept_id = #{id}
	</select>


</mapper>
