<?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.produce.breed.mapper.ScBreedPlanGenerateMapper">

    <resultMap type="ScBreedPlanGenerate" id="ScBreedPlanGenerateResult">
        <result property="id"    column="id"    />
        <result property="planName"    column="plan_name"    />
        <result property="planType"    column="plan_type"    />
        <result property="planDate"    column="plan_date"    />
        <result property="totalEweCount"    column="total_ewe_count"    />
        <result property="totalRamCount"    column="total_ram_count"    />
        <result property="breedRatio"    column="breed_ratio"    />
        <result property="status"    column="status"    />
        <result property="approver"    column="approver"    />
        <result property="approveTime"    column="approve_time"    />
        <result property="approveRemark"    column="approve_remark"    />
        <result property="createBy"    column="create_by"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateBy"    column="update_by"    />
        <result property="updateTime"    column="update_time"    />
    </resultMap>

    <sql id="selectScBreedPlanGenerateVo">
        select id, plan_name, plan_type, plan_date, total_ewe_count, total_ram_count,
               breed_ratio, status, approver, approve_time, approve_remark,
               create_by, create_time, update_by, update_time
        from sc_breed_plan_generate
    </sql>

    <select id="selectScBreedPlanGenerateList" parameterType="ScBreedPlanGenerate" resultMap="ScBreedPlanGenerateResult">
        <include refid="selectScBreedPlanGenerateVo"/>
        <where>
            <if test="planName != null and planName != ''"> and plan_name like concat('%', #{planName}, '%')</if>
            <if test="planType != null"> and plan_type = #{planType}</if>
            <if test="planDate != null"> and DATE(plan_date) = DATE(#{planDate})</if>
            <if test="status != null"> and status = #{status}</if>
            <if test="params.beginTime != null and params.beginTime != ''">
                and DATE(plan_date) &gt;= DATE(#{params.beginTime})
            </if>
            <if test="params.endTime != null and params.endTime != ''">
                and DATE(plan_date) &lt;= DATE(#{params.endTime})
            </if>
        </where>
        order by create_time desc
    </select>

    <select id="selectScBreedPlanGenerateById" parameterType="Long" resultMap="ScBreedPlanGenerateResult">
        <include refid="selectScBreedPlanGenerateVo"/>
        where id = #{id}
    </select>

    <!-- 筛选符合条件的母羊 -->
    <select id="selectEligibleEwe" resultType="Map">
        select
            bs.id,
            bs.manage_tags as bs_manage_tags,
            bv.variety as variety,
            bs.family,
            bst.name as sheep_type,
            bs.gender,
            TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) as month_age,
            bs.current_weight,
            bs.post_lambing_day,
            bbs.breed as breed,
            bs.parity,
            dsf.sheepfold_name,
            bs.comment,
            CASE WHEN bs.is_core = 1 THEN '是' ELSE '否' END as is_core,
            CASE WHEN bs.is_breeding = 1 THEN '是' ELSE '否' END as is_breeding,
            CONCAT('胎次:', IFNULL(bs.parity, 0), ' 配种次数:', IFNULL(bs.mating_counts, 0)) as reproduction_info
        from bas_sheep bs
                 left join bas_sheep_variety bv on bs.variety_id = bv.id
                 left join bas_sheep_type bst on bs.type_id = bst.id
                 left join bas_breed_status bbs on bs.breed_status_id = bbs.id
                 left join da_sheepfold dsf on bs.sheepfold_id = dsf.id
        where bs.gender = 1
          and bs.is_delete = 0
        <if test="manageTags != null and manageTags != ''">
            and bs.manage_tags like concat('%', #{manageTags}, '%')
        </if>
          and (bs.status_id = 1 or bs.status_id is null)
          and (
            (bst.name in ('青年羊', '超龄羊') and (
                (bv.variety = '湖羊' and TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) &gt;= 7.5 and bs.current_weight &gt;= 33) or
                (bv.variety = '东佛里生' and TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) &gt;= 9 and bs.current_weight &gt;= 50) or
                (bv.variety not in ('湖羊', '东佛里生') and TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) &gt;= 9 and bs.current_weight &gt;= 50)
                ))
                or
            (bst.name in ('泌乳羊', '种母羊') and bs.post_lambing_day &gt; 45 and bs.current_weight &gt; 0)
            )
        order by bv.variety, TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) desc
    </select>

    <!-- 筛选符合条件的公羊 -->
    <select id="selectEligibleRam" resultType="Map">
        select
            bs.id,
            bs.manage_tags as bs_manage_tags,
            bv.variety as variety,
            bs.family,
            bst.name as sheep_type,
            bs.gender,
            bs.birthday,
            TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) as month_age,
            bs.current_weight,
            bbs.breed as breed
        from bas_sheep bs
                 left join bas_sheep_variety bv on bs.variety_id = bv.id
                 left join bas_sheep_type bst on bs.type_id = bst.id
                 left join bas_breed_status bbs on bs.breed_status_id = bbs.id
        where bs.gender = 2
          and bs.is_delete = 0
        <if test="manageTags != null and manageTags != ''">
            and bs.manage_tags like concat('%', #{manageTags}, '%')
        </if>
          and bs.status_id = 1
          and (
            (bst.name in ('青年羊', '超龄羊') and (
                (bv.variety = '湖羊' and TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) &gt;= 7.5 and bs.current_weight &gt;= 33) or
                (bv.variety = '东佛里生' and TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) &gt;= 9 and bs.current_weight &gt;= 50) or
                (bv.variety not in ('湖羊', '东佛里生') and TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) &gt;= 9 and bs.current_weight &gt;= 50)
                ))
                or
            bst.name not in ('青年羊', '超龄羊')
            )
        order by bv.variety, TIMESTAMPDIFF(MONTH, bs.birthday, NOW()) desc
    </select>

    <insert id="insertScBreedPlanGenerate" parameterType="ScBreedPlanGenerate" useGeneratedKeys="true" keyProperty="id">
        insert into sc_breed_plan_generate
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="planName != null">plan_name,</if>
            <if test="planType != null">plan_type,</if>
            <if test="planDate != null">plan_date,</if>
            <if test="totalEweCount != null">total_ewe_count,</if>
            <if test="totalRamCount != null">total_ram_count,</if>
            <if test="breedRatio != null">breed_ratio,</if>
            <if test="status != null">status,</if>
            <if test="approver != null">approver,</if>
            <if test="approveTime != null">approve_time,</if>
            <if test="approveRemark != null">approve_remark,</if>
            <if test="createBy != null">create_by,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateBy != null">update_by,</if>
            <if test="updateTime != null">update_time,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="planName != null">#{planName},</if>
            <if test="planType != null">#{planType},</if>
            <if test="planDate != null">#{planDate},</if>
            <if test="totalEweCount != null">#{totalEweCount},</if>
            <if test="totalRamCount != null">#{totalRamCount},</if>
            <if test="breedRatio != null">#{breedRatio},</if>
            <if test="status != null">#{status},</if>
            <if test="approver != null">#{approver},</if>
            <if test="approveTime != null">#{approveTime},</if>
            <if test="approveRemark != null">#{approveRemark},</if>
            <if test="createBy != null">#{createBy},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateBy != null">#{updateBy},</if>
            <if test="updateTime != null">#{updateTime},</if>
        </trim>
    </insert>

    <!-- 插入临时配种计划 -->
    <insert id="insertTempBreedPlan">
        insert into sc_breed_plan_temp (plan_generate_id, ram_id, ewe_id, breed_type, create_time)
        values (#{planGenerateId}, #{breedPlan.ramId}, #{breedPlan.eweId}, #{breedPlan.breedType}, now())
    </insert>

    <update id="updateScBreedPlanGenerate" parameterType="ScBreedPlanGenerate">
        update sc_breed_plan_generate
        <trim prefix="SET" suffixOverrides=",">
            <if test="planName != null">plan_name = #{planName},</if>
            <if test="planType != null">plan_type = #{planType},</if>
            <if test="planDate != null">plan_date = #{planDate},</if>
            <if test="totalEweCount != null">total_ewe_count = #{totalEweCount},</if>
            <if test="totalRamCount != null">total_ram_count = #{totalRamCount},</if>
            <if test="breedRatio != null">breed_ratio = #{breedRatio},</if>
            <if test="status != null">status = #{status},</if>
            <if test="approver != null">approver = #{approver},</if>
            <if test="approveTime != null">approve_time = #{approveTime},</if>
            <if test="approveRemark != null">approve_remark = #{approveRemark},</if>
            <if test="updateBy != null">update_by = #{updateBy},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
        </trim>
        where id = #{id}
    </update>

    <!-- 将临时配种计划转为正式配种计划 -->
    <insert id="transferTempToFormal">
        insert into sc_breed_plan (ram_id, ewe_id, breed_type)
        select ram_id, ewe_id, breed_type
        from sc_breed_plan_temp
        where plan_generate_id = #{planGenerateId}
    </insert>

    <!-- 获取配种计划详情 - 显示完整字段信息 -->
    <select id="selectBreedPlanDetails" parameterType="Long" resultType="Map">
        select
            temp.id,
            temp.ram_id,
            temp.ewe_id,
            temp.breed_type,
            -- 母羊完整信息
            ewe.manage_tags as ewe_manage_tags,
            ewe_variety.variety as ewe_variety,
            ewe.family as ewe_family,
            ewe_type.name as ewe_sheep_type,
            ewe_breed.breed as ewe_breed_status,
            ewe.parity as ewe_parity,
            TIMESTAMPDIFF(MONTH, ewe.birthday, NOW()) as ewe_month_age,
            ewe.current_weight as ewe_current_weight,
            CASE WHEN ewe.is_core = 1 THEN 1 ELSE 0 END as ewe_is_core,
            CASE WHEN ewe.is_breeding = 1 THEN 1 ELSE 0 END as ewe_is_breeding,
            ewe_sheepfold.sheepfold_name as ewe_sheepfold_name,
            ewe.comment as ewe_comment,
            CONCAT('胎次:', IFNULL(ewe.parity, 0), ' 配种次数:', IFNULL(ewe.mating_counts, 0)) as ewe_reproduction_info,
            -- 公羊完整信息 - 直接关联查询耳号
            ram.manage_tags as ram_manage_tags,
            ram_variety.variety as ram_variety,
            ram.family as ram_family,
            ram_type.name as ram_sheep_type,
            ram.birthday as ram_birthday,
            TIMESTAMPDIFF(MONTH, ram.birthday, NOW()) as ram_month_age,
            ram.current_weight as ram_current_weight
        from sc_breed_plan_temp temp
                 left join bas_sheep ewe on ewe.id = CAST(temp.ewe_id AS UNSIGNED)
                 left join bas_sheep_variety ewe_variety on ewe.variety_id = ewe_variety.id
                 left join bas_sheep_type ewe_type on ewe.type_id = ewe_type.id
                 left join bas_breed_status ewe_breed on ewe.breed_status_id = ewe_breed.id
                 left join da_sheepfold ewe_sheepfold on ewe.sheepfold_id = ewe_sheepfold.id
                 left join bas_sheep ram on ram.id = CAST(temp.ram_id AS UNSIGNED)
                 left join bas_sheep_variety ram_variety on ram.variety_id = ram_variety.id
                 left join bas_sheep_type ram_type on ram.type_id = ram_type.id
        where temp.plan_generate_id = #{planGenerateId}
        order by temp.ewe_id, temp.ram_id
    </select>

    <!-- 获取审批详情 - 包含完整的母羊和公羊信息 -->
    <select id="selectApproveBreedPlanDetails" parameterType="Long" resultType="Map">
        select
            temp.id,
            temp.ram_id,
            temp.ewe_id,
            temp.breed_type,
            -- 母羊信息
            ewe.manage_tags as ewe_manage_tags,
            ewe_variety.variety as ewe_variety,
            ewe.family as ewe_family,
            ewe_type.name as ewe_sheep_type,
            ewe_breed.breed as ewe_breed_status,
            ewe.parity as ewe_parity,
            TIMESTAMPDIFF(MONTH, ewe.birthday, NOW()) as ewe_month_age,
            ewe.current_weight as ewe_current_weight,
            CASE WHEN ewe.is_core = 1 THEN 1 ELSE 0 END as ewe_is_core,
            CASE WHEN ewe.is_breeding = 1 THEN 1 ELSE 0 END as ewe_is_breeding,
            ewe_sheepfold.sheepfold_name as ewe_sheepfold_name,
            ewe.comment as ewe_comment,
            CONCAT('胎次:', IFNULL(ewe.parity, 0), ' 配种次数:', IFNULL(ewe.mating_counts, 0)) as ewe_reproduction_info,
            -- 公羊信息 - 直接关联查询耳号
            ram.manage_tags as ram_manage_tags,
            ram_variety.variety as ram_variety,
            ram.family as ram_family,
            ram_type.name as ram_sheep_type,
            ram.birthday as ram_birthday,
            TIMESTAMPDIFF(MONTH, ram.birthday, NOW()) as ram_month_age,
            ram.current_weight as ram_current_weight
        from sc_breed_plan_temp temp
                 left join bas_sheep ewe on ewe.id = CAST(temp.ewe_id AS UNSIGNED)
                 left join bas_sheep_variety ewe_variety on ewe.variety_id = ewe_variety.id
                 left join bas_sheep_type ewe_type on ewe.type_id = ewe_type.id
                 left join bas_breed_status ewe_breed on ewe.breed_status_id = ewe_breed.id
                 left join da_sheepfold ewe_sheepfold on ewe.sheepfold_id = ewe_sheepfold.id
                 left join bas_sheep ram on ram.id = CAST(temp.ram_id AS UNSIGNED)
                 left join bas_sheep_variety ram_variety on ram.variety_id = ram_variety.id
                 left join bas_sheep_type ram_type on ram.type_id = ram_type.id
        where temp.plan_generate_id = #{planGenerateId}
        order by temp.ewe_id, temp.ram_id
    </select>

    <!-- 更新临时配种计划 -->
    <update id="updateTempBreedPlan">
        update sc_breed_plan_temp
        <set>
            <if test="ramId != null">
                ram_id = #{ramId},
            </if>
            <if test="ramId == null">
                ram_id = null,
            </if>
            <if test="breedType != null">
                breed_type = #{breedType},
            </if>
            <if test="breedType == null">
                breed_type = null,
            </if>
        </set>
        where id = #{id}
    </update>

    <delete id="deleteScBreedPlanGenerateById" parameterType="Long">
        delete from sc_breed_plan_generate where id = #{id}
    </delete>

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

    <!-- 删除临时配种计划 -->
    <delete id="deleteTempBreedPlanByPlanId" parameterType="Long">
        delete from sc_breed_plan_temp where plan_generate_id = #{planGenerateId}
    </delete>
    <!-- 模糊查询耳号列表 -->
    <select id="searchEarNumbers" resultType="java.lang.String">
        SELECT DISTINCT sf.bs_manage_tags
        FROM sheep_file sf
        WHERE sf.bs_manage_tags LIKE CONCAT(#{query}, '%')
          AND sf.is_delete = 0
        ORDER BY sf.bs_manage_tags
            LIMIT 50
    </select>
</mapper>