<?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.SheepFileMapper">
    
    <resultMap type="SheepFile" id="SheepFileResult">
        <result property="id"    column="id"    />
        <result property="bsManageTags"    column="bs_manage_tags"    />
        <result property="ranchId"    column="ranch_id"    />
        <result property="drRanch"    column="dr_ranch"    />
        <result property="sheepfoldId"    column="sheepfold_id"    />
        <result property="sheepfoldName"    column="sheepfold_name"    />
        <result property="electronicTags"    column="electronic_tags"    />
        <result property="varietyId"    column="variety_id"    />
        <result property="variety"    column="variety"    />
        <result property="family"    column="family"    />
        <result property="name"    column="name"    />
        <result property="gender"    column="gender"    />
        <result property="birthday"    column="birthday"    />
        <result property="dayAge"    column="day_age"    />
        <result property="monthAge"    column="month_age"    />
        <result property="parity"    column="parity"    />
        <result property="birthWeight"    column="birth_weight"    />
        <result property="weaningDate"    column="weaning_date"    />
        <result property="statusId"    column="status_id"    />
        <result property="weaningWeight"    column="weaning_weight"    />
        <result property="currentWeight"    column="current_weight"    />
        <result property="weaningDayAge"    column="weaning_day_age"    />
        <result property="weaningDailyGain"    column="weaning_daily_gain"    />
        <result property="breedStatusId"    column="breed_status_id"    />
        <result property="breed"    column="breed"    />
        <result property="bsFatherId"    column="bs_father_id"    />
        <result property="fatherManageTags"    column="father_manage_tags"    />
        <result property="bsMotherId"    column="bs_mother_id"    />
        <result property="motherManageTags"    column="mother_manage_tags"    />
        <result property="receptorId"    column="receptor_id"    />
        <result property="receptorManageTags"    column="receptor_manage_tags"    />
        <result property="fatherFatherId"    column="father_father_id"    />
        <result property="grandfatherManageTags"    column="grandfather_manage_tags"    />
        <result property="fatherMotherId"    column="father_mother_id"    />
        <result property="grandmotherManageTags"    column="grandmother_manage_tags"    />
        <result property="fatherId"    column="father_id"    />
        <result property="maternalGrandfatherManageTags"    column="maternal_grandfather_manage_tags"    />
        <result property="motherId"    column="mother_id"    />
        <result property="maternalGrandmotherManageTags"    column="maternal_grandmother_manage_tags"    />
        <result property="matingDate"    column="mating_date"    />
        <result property="matingTypeId"    column="mating_type_id"    />
        <result property="pregDate"    column="preg_date"    />
        <result property="lambingDate"    column="lambing_date"    />
        <result property="lambingDay"    column="lambing_day"    />
        <result property="matingDay"    column="mating_day"    />
        <result property="gestationDay"    column="gestation_day"    />
        <result property="expectedDate"    column="expected_date"    />
        <result property="postLambingDay"    column="post_lambing_day"    />
        <result property="lactationDay"    column="lactation_day"    />
        <result property="anestrousDay"    column="anestrous_day"    />
        <result property="matingCounts"    column="mating_counts"    />
        <result property="matingTotal"    column="mating_total"    />
        <result property="miscarriageCounts"    column="miscarriage_counts"    />
        <result property="comment"    column="comment"    />
        <result property="controlled"    column="controlled"    />
        <result property="body"    column="body"    />
        <result property="breast"    column="breast"    />
        <result property="source"    column="source"    />
        <result property="sourceDate"    column="source_date"    />
        <result property="sourceRanchId"    column="source_ranch_id"    />
        <result property="sourceRanch"    column="source_ranch"    />
        <result property="updateBy"    column="update_by"    />
        <result property="updateTime"    column="update_time"    />
        <result property="createBy"    column="create_by"    />
        <result property="createTime"    column="create_time"    />
        <result property="isDelete"    column="is_delete"    />
    </resultMap>

    <sql id="selectSheepFileVo">
        select id, bs_manage_tags, ranch_id, dr_ranch, sheepfold_id, sheepfold_name, electronic_tags, variety_id, variety, family, name, gender, birthday, day_age, month_age, parity, birth_weight, weaning_date, status_id, weaning_weight, current_weight,weaning_day_age,weaning_daily_gain,breed_status_id, breed, bs_father_id, father_manage_tags, bs_mother_id, mother_manage_tags, receptor_id, receptor_manage_tags, father_father_id, grandfather_manage_tags, father_mother_id, grandmother_manage_tags, father_id, maternal_grandfather_manage_tags, mother_id, maternal_grandmother_manage_tags, mating_date, mating_type_id, preg_date, lambing_date, lambing_day, mating_day, gestation_day, expected_date, post_lambing_day, lactation_day, anestrous_day, mating_counts, mating_total, miscarriage_counts, comment, controlled, body, breast, source, source_date, source_ranch_id, source_ranch, update_by, update_time, create_by, create_time, is_delete from sheep_file
    </sql>

    <select id="selectSheepFileList" parameterType="SheepFile" resultMap="SheepFileResult">
        <include refid="selectSheepFileVo"/>
        <where>  
            <if test="id != null "> and id = #{id}</if>
            <if test="bsManageTags != null  and bsManageTags != ''"> and bs_manage_tags = #{bsManageTags}</if>
            <if test="drRanch != null  and drRanch != ''"> and dr_ranch = #{drRanch}</if>
            <if test="electronicTags != null  and electronicTags != ''"> and electronic_tags = #{electronicTags}</if>
            <if test="variety != null  and variety != ''"> and variety = #{variety}</if>
            <if test="name != null  and name != ''"> and name = #{name}</if>
            <if test="gender != null "> and gender = #{gender}</if>
            <if test="statusId != null "> and status_id = #{statusId}</if>
            <if test="breed != null  and breed != ''"> and breed = #{breed}</if>
        </where>
    </select>
    
    <select id="selectSheepFileById" parameterType="Long" resultMap="SheepFileResult">
        <include refid="selectSheepFileVo"/>
        where id = #{id}
    </select>
    <select id="selectSheepByManageTags"  parameterType="String" resultMap="SheepFileResult">
        <include refid="selectSheepFileVo"/>
        where bs_manage_tags = #{tags}
    </select>



    <!-- 在群羊只总数 -->
    <select id="countInGroup" resultType="java.lang.Long">
        SELECT COUNT(*) FROM sheep_file WHERE status_id = 1
    </select>

    <!-- 羊只类别分布 -->
    <select id="countBySheepType" resultType="java.util.Map">
        SELECT name AS name, COUNT(*) AS value
        FROM sheep_file
        WHERE status_id = 1
        GROUP BY name
    </select>

    <!-- 繁育状态分布 -->
    <select id="countByBreedStatus" resultType="java.util.Map">
        SELECT breed AS name, COUNT(*) AS value
        FROM sheep_file
        WHERE status_id = 1
        GROUP BY breed
    </select>

    <!-- 品种分布 -->
    <select id="countByVariety" resultType="java.util.Map">
        SELECT variety AS name, COUNT(*) AS value
        FROM sheep_file
        WHERE status_id = 1
        GROUP BY variety
    </select>

    <!-- 泌乳羊胎次分布 -->
    <select id="countParityOfLactation" resultType="java.util.Map">
        SELECT parity AS name, COUNT(*) AS value
        FROM sheep_file
        WHERE status_id = 1 AND name = '泌乳羊'
        GROUP BY parity
        ORDER BY parity
    </select>

    <!--
        获取字段唯一值的SQL映射
        说明：这个查询使用 ${fieldName} 直接拼接字段名，因为MyBatis的#{}不支持列名作为参数
        安全性：通过Service层的白名单验证来确保fieldName的安全性
    -->
    <select id="selectFieldValues" parameterType="String" resultType="String">
        SELECT
        DISTINCT ${fieldName} as field_value
        FROM
        sheep_file
        WHERE
        <!-- 过滤空值和NULL值，确保返回的数据质量 -->
        ${fieldName} IS NOT NULL
        AND ${fieldName} != ''
        AND ${fieldName} != 'null'
        ORDER BY
        <!-- 按字母顺序排序，方便前端显示 -->
        ${fieldName} ASC
    </select>

    <select id="selectSheepFileListByCondition" parameterType="map" resultMap="SheepFileResult">
        <include refid="selectSheepFileVo"/>
        FROM sheep_file
        <where>
            <!-- 逻辑删除过滤 -->
            AND is_delete = 0

            <!-- 原有的 SheepFile 条件（保持兼容性） -->
            <if test="sheepFile != null">
                <if test="sheepFile.bsManageTags != null and sheepFile.bsManageTags != ''">
                    AND bs_manage_tags LIKE CONCAT('%', #{sheepFile.bsManageTags}, '%')
                </if>
                <if test="sheepFile.electronicTags != null and sheepFile.electronicTags != ''">
                    AND electronic_tags LIKE CONCAT('%', #{sheepFile.electronicTags}, '%')
                </if>
                <if test="sheepFile.drRanch != null and sheepFile.drRanch != ''">
                    AND dr_ranch LIKE CONCAT('%', #{sheepFile.drRanch}, '%')
                </if>
                <if test="sheepFile.variety != null and sheepFile.variety != ''">
                    AND variety LIKE CONCAT('%', #{sheepFile.variety}, '%')
                </if>
                <if test="sheepFile.name != null and sheepFile.name != ''">
                    AND name LIKE CONCAT('%', #{sheepFile.name}, '%')
                </if>
                <if test="sheepFile.gender != null">
                    AND gender = #{sheepFile.gender}
                </if>
                <if test="sheepFile.statusId != null">
                    AND status_id = #{sheepFile.statusId}
                </if>
                <if test="sheepFile.breed != null and sheepFile.breed != ''">
                    AND breed LIKE CONCAT('%', #{sheepFile.breed}, '%')
                </if>
            </if>

            <!-- 动态条件处理 - 使用多个if标签代替复杂的choose -->
            <if test="params != null and !params.isEmpty()">
                <!-- 空值条件 -->
                <foreach collection="params.entrySet()" item="value" index="key">
                    <if test="value != null and value.toString() == 'IS_NULL'">
                        AND ${key} IS NULL
                    </if>
                    <if test="value != null and value.toString() == 'NOT_NULL'">
                        AND ${key} IS NOT NULL
                    </if>
                </foreach>

                <!-- 范围条件 -->
                <foreach collection="params.entrySet()" item="value" index="key">
                    <!-- 显式将 value 转换为字符串 -->
                    <if test="value != null and value.toString() != null">
                        <choose>
                            <when test="value.toString().startsWith('GT:')">
                                AND ${key} &gt; #{value.toString().substring(3)}
                            </when>
                            <when test="value.toString().startsWith('LT:')">
                                AND ${key} &lt; #{value.toString().substring(3)}
                            </when>
                            <when test="value.toString().startsWith('GE:')">
                                AND ${key} &gt;= #{value.toString().substring(3)}
                            </when>
                            <when test="value.toString().startsWith('LE:')">
                                AND ${key} &lt;= #{value.toString().substring(3)}
                            </when>
                        </choose>
                    </if>
                </foreach>

                <!-- 列表条件 -->
                <foreach collection="params.entrySet()" item="value" index="key">
                    <if test="value != null and value.toString() != null and value.toString().contains(',')">
                        AND ${key} IN
                        <foreach collection="value.toString().split(',')" item="item" open="(" separator="," close=")">
                            #{item}
                        </foreach>
                    </if>
                </foreach>

                <!-- 模糊查询条件（针对文本字段） -->
                <foreach collection="params.entrySet()" item="value" index="key">
                    <if test="value != null and value.toString() != null">
                        <choose>
                            <when test="key == 'bs_manage_tags' or key == 'electronic_tags' or
                              key == 'dr_ranch' or key == 'sheepfold_name' or
                              key == 'variety' or key == 'family' or
                              key == 'name' or key == 'breed' or
                              key == 'father_manage_tags' or key == 'mother_manage_tags' or
                              key == 'receptor_manage_tags'">
                                AND ${key} LIKE CONCAT('%', #{value}, '%')
                            </when>
                            <otherwise>
                                <!-- 普通等于条件 -->
                                AND ${key} = #{value}
                            </otherwise>
                        </choose>
                    </if>
                </foreach>
            </if>
        </where>
        ORDER BY id DESC
    </select>

<!--    &lt;!&ndash; 查询所有公羊（gender=2） &ndash;&gt;-->
<!--    <select id="selectRamList" resultMap="SheepFileResult">-->
<!--        <include refid="selectSheepFileVo"/>-->
<!--        where gender = 2 and (is_delete = 0 or is_delete is null)-->
<!--        order by create_time desc-->
<!--    </select>-->

    <!-- 查询所有公羊 -->
    <select id="selectRamList" resultMap="SheepFileResult">
        SELECT * FROM sheep_file
        WHERE gender = 2 AND is_delete = 0
    </select>

    <!-- 根据管理耳号查询 -->
    <select id="selectSheepFileByManageTags" resultMap="SheepFileResult">
        SELECT * FROM sheep_file
        WHERE bs_manage_tags = #{manageTags} AND is_delete = 0
            LIMIT 1
    </select>
</mapper>