<?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.zhyc.module.base.mapper.DaSheepfoldMapper">

    <resultMap type="com.zhyc.module.base.domain.DaSheepfold" id="DaSheepfoldResult">
        <result property="id" column="id"/>
        <result property="ranchId" column="ranch_id"/>
        <result property="sheepfoldName" column="sheepfold_name"/>
        <result property="sheepfoldTypeId" column="sheepfold_type_id"/>
        <result property="sheepfoldNo" column="sheepfold_no"/>
        <result property="rowNo" column="row_no"/>
        <result property="columns" column="columns"/>
        <result property="comment" column="comment"/>
        <!-- 新增羊只数量映射 -->
        <result property="sheepCount" column="sheep_count"/>
    </resultMap>

    <!-- 汇总结果映射（主表格用） -->
    <resultMap id="DaSheepfoldSummaryResult" type="com.zhyc.module.base.domain.DaSheepfold">
        <result property="ranchId" column="ranch_id"/>
        <result property="sheepfoldTypeId" column="sheepfold_type_id"/>
        <result property="sheepfoldNo" column="sheepfold_no"/>
        <result property="sheepfoldName" column="sheepfoldName"/>
        <result property="comment" column="comment"/>
        <result property="totalSheepCount" column="totalSheepCount"/> <!-- 羊舍总羊数 -->
    </resultMap>

    <!-- 基础栏位表查询字段 -->
    <sql id="selectDaSheepfoldVo">
        SELECT
            ds.id,
            ds.ranch_id,
            ds.sheepfold_name,
            ds.sheepfold_type_id,
            ds.sheepfold_no,
            ds.row_no,
            ds.columns,
            ds.comment
        FROM da_sheepfold ds
    </sql>

    <!-- 1. 主表格：羊舍级别汇总查询（统计每个羊舍的总羊数） -->
    <select id="selectDaSheepfoldSummaryList" parameterType="DaSheepfold" resultMap="DaSheepfoldSummaryResult">
        SELECT
        ds.ranch_id,
        ds.sheepfold_type_id,
        ds.sheepfold_no,
        -- 提取羊舍名称（截取栏位名称的羊舍部分，保证唯一）
        CONCAT(ds.sheepfold_no, '号', (SELECT dict_label FROM sys_dict_data WHERE dict_value = ds.sheepfold_type_id AND dict_type = 'bas_sheepfold_type')) as sheepfoldName,
        MAX(ds.comment) as comment,
        -- 汇总该羊舍下所有栏位的羊数总和
        SUM(IFNULL(sheep_group.sheep_count, 0)) as totalSheepCount
        FROM da_sheepfold ds
        -- 左关联羊只表，统计每个栏位的羊数
        LEFT JOIN (
        SELECT sheepfold_id, COUNT(id) as sheep_count
        FROM bas_sheep -- 羊只表
        GROUP BY sheepfold_id -- 按栏位ID分组统计羊数
        ) sheep_group ON ds.id = sheep_group.sheepfold_id -- 关联字段修正为sheepfold_id
        <where>
            <if test="ranchId != null ">and ds.ranch_id = #{ranchId}</if>
            <if test="sheepfoldTypeId != null ">and ds.sheepfold_type_id = #{sheepfoldTypeId}</if>
            ${params.dataScope}
        </where>
        -- 按羊舍维度分组（牧场+羊舍类型+羊舍编号 唯一标识一个羊舍）
        GROUP BY ds.ranch_id, ds.sheepfold_type_id, ds.sheepfold_no
        ORDER BY ds.sheepfold_no
    </select>

    <!-- 2. 子表格：栏位级别明细查询（统计单个栏位的羊数） -->
    <select id="selectDaSheepfoldList" parameterType="DaSheepfold" resultMap="DaSheepfoldResult">
        SELECT
        ds.id,
        ds.ranch_id,
        ds.sheepfold_name,
        ds.sheepfold_type_id,
        ds.sheepfold_no,
        ds.row_no,
        ds.columns,
        ds.comment,
        -- 统计当前栏位的羊数（关联羊只表）
        IFNULL(sheep_group.sheep_count, 0) as sheep_count
        FROM da_sheepfold ds
        -- 左关联羊只表，避免无羊的栏位被过滤
        LEFT JOIN (
        SELECT sheepfold_id, COUNT(id) as sheep_count
        FROM bas_sheep -- 羊只表
        GROUP BY sheepfold_id
        ) sheep_group ON ds.id = sheep_group.sheepfold_id -- 关联字段修正为sheepfold_id
        <where>
            <if test="ranchId != null ">and ds.ranch_id = #{ranchId}</if>
            <if test="sheepfoldTypeId != null ">and ds.sheepfold_type_id = #{sheepfoldTypeId}</if>
            <if test="sheepfoldNo != null and sheepfoldNo != '' ">and ds.sheepfold_no = #{sheepfoldNo}</if>
            ${params.dataScope}
        </where>
        GROUP BY ds.id,ds.ranch_id,ds.sheepfold_name,ds.sheepfold_type_id,ds.sheepfold_no,ds.row_no,ds.columns,ds.comment
        ORDER BY SUBSTRING_INDEX(ds.row_no, '-', 1), CAST(ds.columns AS UNSIGNED)
    </select>

    <select id="selectDaSheepfoldById" parameterType="Long" resultMap="DaSheepfoldResult">
        <include refid="selectDaSheepfoldVo"/>
        where id = #{id}
    </select>

    <insert id="insertDaSheepfold" parameterType="DaSheepfold" useGeneratedKeys="true" keyProperty="id">
        insert into da_sheepfold
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="ranchId != null">ranch_id,</if>
            <if test="sheepfoldName != null">sheepfold_name,</if>
            <if test="sheepfoldTypeId != null">sheepfold_type_id,</if>
            <if test="sheepfoldNo != null">sheepfold_no,</if>
            <if test="rowNo != null">row_no,</if>
            <if test="columns != null">columns,</if>
            <if test="comment != null">comment,</if>
            <if test="userId != null">user_id,</if>
            <if test="deptId != null">dept_id,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="ranchId != null">#{ranchId},</if>
            <if test="sheepfoldName != null">#{sheepfoldName},</if>
            <if test="sheepfoldTypeId != null">#{sheepfoldTypeId},</if>
            <if test="sheepfoldNo != null">#{sheepfoldNo},</if>
            <if test="rowNo != null">#{rowNo},</if>
            <if test="columns != null">#{columns},</if>
            <if test="comment != null">#{comment},</if>
            <if test="userId != null">#{userId},</if>
            <if test="deptId != null">#{deptId},</if>
        </trim>
    </insert>

    <update id="updateDaSheepfold" parameterType="DaSheepfold">
        update da_sheepfold
        <trim prefix="SET" suffixOverrides=",">
            <if test="ranchId != null">ranch_id = #{ranchId},</if>
            <if test="sheepfoldName != null">sheepfold_name = #{sheepfoldName},</if>
            <if test="sheepfoldTypeId != null">sheepfold_type_id = #{sheepfoldTypeId},</if>
            <if test="sheepfoldNo != null">sheepfold_no = #{sheepfoldNo},</if>
            <if test="rowNo != null">row_no = #{rowNo},</if>
            <if test="columns != null">columns = #{columns},</if>
            <if test="comment != null">comment = #{comment},</if>
        </trim>
        where id = #{id}
    </update>

    <delete id="deleteDaSheepfoldById" parameterType="Long">
        delete
        from da_sheepfold
        where id = #{id}
    </delete>

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

    <select id="selectCount" parameterType="DaSheepfold" resultType="int">
        SELECT COUNT(*)
        FROM da_sheepfold
        WHERE ranch_id = #{ranchId}
          AND sheepfold_type_id = #{sheepfoldTypeId}
          AND sheepfold_no = #{sheepfoldNo}
    </select>

    <!-- 新增：按组合条件删除羊舍记录 -->
    <delete id="deleteSheepfoldByCondition">
        DELETE FROM da_sheepfold
        WHERE ranch_id = #{ranchId}
          AND sheepfold_no = #{sheepfoldNo}
          AND sheepfold_type_id = #{sheepfoldTypeId}
    </delete>
</mapper>