<?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.bonus.material.ma.mapper.PartTypeMapper">
    <resultMap type="com.bonus.material.ma.domain.PartType" id="PartTypeResult">
        <result property="id"    column="pa_id"    />
        <result property="paName"    column="pa_name"    />
        <result property="parentId"    column="parent_id"    />
        <result property="status"    column="status"    />
        <result property="storageNum"    column="storage_num"    />
        <result property="unitId"    column="unit_id"    />
        <result property="unitName"    column="unit_name"    />
        <result property="buyPrice"    column="buy_price"    />
        <result property="level"    column="level"    />
        <result property="warnNum"    column="warn_num"    />
        <result property="delFlag"    column="del_flag"    />
        <result property="createBy"    column="create_by"    />
        <result property="updateBy"    column="update_by"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
        <result property="remark"    column="remark"    />
        <result property="companyId"    column="company_id"    />
    </resultMap>

    <sql id="selectPartTypeVo">
        select pa_id, pa_name, parent_id, status, storage_num, unit_id, unit_name, buy_price, level, warn_num, del_flag, create_by, update_by, create_time, update_time, remark, company_id from ma_part_type
    </sql>
    
    <select id="selectPartTypeByPaId" parameterType="Long" resultMap="PartTypeResult">
        <include refid="selectPartTypeVo"/>
        where pa_id = #{id}
    </select>

    <select id="getPartTree" resultType="com.bonus.common.biz.domain.TreeNode">
        SELECT pa_id AS id,
               pa_name AS label,
               parent_id AS parentId,
               level
        FROM ma_part_type
        WHERE del_flag = '0' and level != '3'
        ORDER BY create_time
    </select>

    <select id="selectPartTypeList" resultType="com.bonus.common.biz.domain.TreeNode">
        select pa_id as id, pa_name as label, parent_id as parentId, storage_num as storageNum, unit_name as unitName, buy_price as buyPrice, level as level, remark as remark from ma_part_type
        where del_flag = '0'
        <if test="keyWord != null and keyWord != ''">
            and (
                pa_name like concat('%', #{keyWord}, '%')
                or storage_num like concat('%', #{keyWord}, '%')
                or unit_name = #{keyWord},
                or buy_price like concat('%', #{keyWord}, '%')
            )
        </if>
    </select>

    <select id="getTypeList" resultType="com.bonus.material.ma.domain.PartType">
        select pa_id as id, pa_name as paName, parent_id as parentId, storage_num as storageNum, unit_name as unitName, buy_price as buyPrice, level as level, remark as remark from ma_part_type
        where del_flag = '0'
        <if test="keyWord != null and keyWord != ''">
            and (
            pa_name like concat('%', #{keyWord}, '%')
            or storage_num like concat('%', #{keyWord}, '%')
            or unit_name = #{keyWord},
            or buy_price like concat('%', #{keyWord}, '%')
            )
        </if>
    </select>

    <select id="selectByName" resultType="com.bonus.material.ma.domain.PartType">
        select pa_id as id, pa_name as paName, parent_id as parentId, storage_num as storageNum, unit_name as unitName, buy_price as buyPrice, level as level, remark as remark from ma_part_type
        where del_flag = '0'
          <if test="paName != null and paName != ''">
               AND pa_name = #{paName}
          </if>
          <if test="parentId != null">
               AND parent_id = #{parentId}
          </if>
    </select>

    <select id="selectById" resultType="java.lang.Integer">
        select count(*) from ma_part_type where del_flag = '0' and parent_id = #{id}
    </select>

    <select id="selectPart" resultType="java.lang.Integer">
        select count(*) from repair_apply_record where part_id = #{id}
    </select>

    <insert id="insertPartType" parameterType="com.bonus.material.ma.domain.PartType">
        insert into ma_part_type
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="paName != null and paName != ''">pa_name,</if>
            <if test="parentId != null">parent_id,</if>
            <if test="status != null">status,</if>
            <if test="storageNum != null">storage_num,</if>
            <if test="unitId != null">unit_id,</if>
            <if test="unitName != null">unit_name,</if>
            <if test="buyPrice != null">buy_price,</if>
            <if test="level != null">level,</if>
            <if test="warnNum != null">warn_num,</if>
            del_flag,
            <if test="createBy != null">create_by,</if>
            <if test="updateBy != null">update_by,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateTime != null">update_time,</if>
            <if test="remark != null">remark,</if>
            <if test="companyId != null">company_id,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="paName != null and paName != ''">#{paName},</if>
            <if test="parentId != null">#{parentId},</if>
            <if test="status != null">#{status},</if>
            <if test="storageNum != null">#{storageNum},</if>
            <if test="unitId != null">#{unitId},</if>
            <if test="unitName != null">#{unitName},</if>
            <if test="buyPrice != null">#{buyPrice},</if>
            <if test="level != null">#{level},</if>
            <if test="warnNum != null">#{warnNum},</if>
            0,
            <if test="createBy != null">#{createBy},</if>
            <if test="updateBy != null">#{updateBy},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateTime != null">#{updateTime},</if>
            <if test="remark != null">#{remark},</if>
            <if test="companyId != null">#{companyId},</if>
         </trim>
    </insert>

    <update id="updatePartType" parameterType="com.bonus.material.ma.domain.PartType">
        update ma_part_type
        <trim prefix="SET" suffixOverrides=",">
            <if test="paName != null and paName != ''">pa_name = #{paName},</if>
            <if test="parentId != null">parent_id = #{parentId},</if>
            <if test="status != null">status = #{status},</if>
            <if test="storageNum != null">storage_num = #{storageNum},</if>
            <if test="unitId != null">unit_id = #{unitId},</if>
            <if test="unitName != null">unit_name = #{unitName},</if>
            <if test="buyPrice != null">buy_price = #{buyPrice},</if>
            <if test="level != null">level = #{level},</if>
            <if test="warnNum != null">warn_num = #{warnNum},</if>
            <if test="updateBy != null">update_by = #{updateBy},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="remark != null">remark = #{remark},</if>
            <if test="companyId != null">company_id = #{companyId},</if>
        </trim>
        where pa_id = #{id}
    </update>

    <delete id="deletePartTypeByPaId" parameterType="Long">
        update ma_part_type set del_flag = '2' where pa_id = #{id}
    </delete>

    <select id="selectParentId" resultType="java.lang.Integer">
        SELECT DISTINCT
        mt2.pa_id
        FROM
        ma_part_type mt
        LEFT JOIN ma_part_type mt2 ON mt.parent_id = mt2.pa_id
        LEFT JOIN ma_part_type mt3 ON mt2.parent_id = mt3.pa_id
        <where>
            <if test="level == 0">
                and mt.level = 4
            </if>
            <if test="level == 1">
                and mt3.pa_id = #{id}
            </if>
            <if test="level == 2">
                and mt2.pa_id = #{id}
            </if>
            and mt2.pa_id is not null
            and mt2.del_flag = '0'
        </where>
    </select>

    <select id="getListByTypeName" resultType="com.bonus.material.ma.domain.PartType">
        SELECT DISTINCT
        m.pa_id AS id,
        m.pa_name AS paName,
        m1.pa_name AS partName,
        m2.pa_name As partType,
        m.parent_id as parentId,
        m.unit_name as unitName,
        m.storage_num as storageNum,
        m.buy_price as buyPrice,
        m.LEVEL as level,
        m.remark as remark
        FROM
        ma_part_type m
        LEFT JOIN ma_part_type m1 ON m.parent_id = m1.pa_id
        and m1.del_flag = '0'
        LEFT JOIN ma_part_type m2 ON m1.parent_id = m2.pa_id
        and m2.del_flag = '0'
        WHERE m.parent_id = #{paId} and m.del_flag = '0'
        <if test="type.keyWord != null and type.keyWord !=''">
            AND (m.pa_name like concat('%',#{type.keyWord},'%')
            or m1.pa_name like concat('%',#{type.keyWord},'%')
            or m2.pa_name like concat('%',#{type.keyWord},'%')
            )
        </if>
    </select>

    <select id="select" resultType="com.bonus.material.ma.domain.PartType">
        SELECT
            part_id AS id,
            part_num AS storageNum
        FROM
            pa_person_storage
        WHERE
            part_num > 0 and creator = #{createBy}
    </select>

    <select id="getTypeStorageNumList" resultType="com.bonus.material.part.domain.PartLeaseDetails">
        SELECT
            m3.pa_name as partType,
            m2.pa_name as partName,
            m1.pa_name as partModel,
            m1.storage_num as storageNum,
            m1.buy_price as buyPrice,
            su.nick_name as createBy,
            m1.create_time as createTime
        FROM
            ma_part_type m1
                LEFT JOIN ma_part_type m2 ON m1.parent_id = m2.pa_id
                AND m2.del_flag = '0'
                LEFT JOIN ma_part_type m3 ON m2.parent_id = m3.pa_id
                AND m3.del_flag = '0'
                LEFT JOIN sys_user su on m1.create_by = su.user_id
        WHERE
            m1.del_flag = '0'
          AND m1.`level` = 3
        <if test="keyWord != null and keyWord !=''">
            AND
              (
              m1.pa_name like concat('%',#{keyWord},'%')
              or m2.pa_name like concat('%',#{keyWord},'%')
              or m3.pa_name like concat('%',#{keyWord},'%')
              or su.nick_name like concat('%',#{keyWord},'%')
              )
        </if>
    </select>
    <select id="getPersonStorageNumList" resultType="com.bonus.material.part.domain.PartLeaseDetails">
        SELECT
            m3.pa_name as partType,
            m2.pa_name as partName,
            m1.pa_name as partModel,
            p1.part_num as storageNum,
            p1.part_price as buyPrice,
            su.nick_name as createBy,
            p1.create_time as createTime
        FROM
            pa_person_storage p1
                LEFT JOIN ma_part_type m1 ON p1.part_id = m1.pa_id
                AND m1.del_flag = '0'
                LEFT JOIN ma_part_type m2 ON m1.parent_id = m2.pa_id
                AND m2.del_flag = '0'
                LEFT JOIN ma_part_type m3 ON m2.parent_id = m3.pa_id
                AND m3.del_flag = '0'
                LEFT JOIN sys_user su on p1.creator = su.user_id
        WHERE
            p1.is_active = '1'
        <if test="keyWord != null and keyWord !=''">
            AND
              (
              m1.pa_name like concat('%',#{keyWord},'%')
              or m2.pa_name like concat('%',#{keyWord},'%')
              or m3.pa_name like concat('%',#{keyWord},'%')
              or su.nick_name like concat('%',#{keyWord},'%')
              )
        </if>
    </select>

    <select id="getUserName" resultType="com.bonus.material.ma.domain.PartType">
        SELECT
            mp.user_id AS userId,
            mp.type_id AS typeId,
            su.nick_name AS keepUserName
        FROM
            ma_part_type_keeper mp
                LEFT JOIN sys_user su ON mp.user_id = su.user_id
        <where>
            <if test="userId != null "> and mp.user_id = #{userId}</if>
            <if test="typeId != null "> and mp.type_id = #{typeId}</if>
        </where>
    </select>
    <select id="selectPartTypeListNew" resultType="com.bonus.common.biz.domain.TreeNode">
        SELECT
            mpt.pa_id as id,
            mpt.pa_name as label,
            mpt.parent_id as parentId,
            mpt.unit_name as unitName,
            mpt.buy_price as buyPrice,
            mpt.`level`,
            mpt.remark,
            pps.part_num as storageNum
        FROM
            ma_part_type_keeper mpk
                LEFT JOIN (
                SELECT
                    part_id,
                    SUM(part_num) as part_num
                FROM
                    pa_person_storage
                GROUP BY part_id
            ) pps ON pps.part_id = mpk.type_id
                LEFT JOIN ma_part_type mpt ON mpt.pa_id = mpk.type_id AND mpt.del_flag = '0'
        WHERE
            mpk.user_id = #{userId}
          -- 添加条件：如果level为3，则要求part_num > 0
          AND (mpt.`level` != 3 OR (mpt.`level` = 3 AND (pps.part_num IS NOT NULL AND pps.part_num > 0)))

        GROUP BY pa_id

        UNION ALL

-- 一级父级
        SELECT
            p1.pa_id,
            p1.pa_name,
            p1.parent_id,
            p1.unit_name,
            p1.buy_price,
            p1.`level`,
            p1.remark,
            NULL AS part_num
        FROM
            ma_part_type_keeper mpk
                JOIN ma_part_type c ON c.pa_id = mpk.type_id AND c.del_flag = '0'
                JOIN ma_part_type p1 ON p1.pa_id = c.parent_id AND p1.del_flag = '0'
        WHERE
            mpk.user_id = #{userId}
          -- 确保原始部件满足level=3时的part_num条件
          AND (c.`level` != 3 OR EXISTS (
        SELECT 1 FROM (
            SELECT part_id, SUM(part_num) as part_num
            FROM pa_person_storage
            GROUP BY part_id
        ) pps
        WHERE pps.part_id = c.pa_id
        AND pps.part_num > 0
    ))

        GROUP BY pa_id

        UNION ALL

-- 二级父级（祖父级）
        SELECT
            p2.pa_id,
            p2.pa_name,
            p2.parent_id,
            p2.unit_name,
            p2.buy_price,
            p2.`level`,
            p2.remark,
            NULL AS part_num
        FROM
            ma_part_type_keeper mpk
                JOIN ma_part_type c ON c.pa_id = mpk.type_id AND c.del_flag = '0'
                JOIN ma_part_type p1 ON p1.pa_id = c.parent_id AND p1.del_flag = '0'
                JOIN ma_part_type p2 ON p2.pa_id = p1.parent_id AND p2.del_flag = '0'
        WHERE
            mpk.user_id = #{userId}
          -- 确保原始部件满足level=3时的part_num条件
          AND (c.`level` != 3 OR EXISTS (
        SELECT 1 FROM (
            SELECT part_id, SUM(part_num) as part_num
            FROM pa_person_storage
            GROUP BY part_id
        ) pps
        WHERE pps.part_id = c.pa_id
        AND pps.part_num > 0
    ))
        GROUP BY pa_id
    </select>
</mapper>