<?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.dk.mdm.mapper.mst.GoodsSkuMapper">

    <!-- 通用设置 -->
    <!-- 通用查询列 -->
    <sql id="Base_Column_List">
        sku_id, sku_code, sku_name, sku_model, brand_id, category_id, unit_id, sub_unit_id, conversion_factor
        , series_id, sku_spec, price_purchase, price_standard, price_wholesale, price_limited, price_other,sku_images
        , remarks, flg_valid, cp_id, op_create_time, op_create_user_id, op_update_time, op_update_user_id
        , op_app_code, op_timestamp, op_db_user, warning_upper_limit, warning_lower_limit
    </sql>
    <!--  更新预警信息  -->
    <update id="saveWarningList">
        <foreach collection="list" item="item" index="index" separator=";">
            UPDATE dkic_b.t_mst_goods_sku
            SET warning_lower_limit = #{item.warningLowerLimit}, warning_upper_limit = #{item.warningUpperLimit}
            WHERE sku_id = #{item.skuId}::uuid
        </foreach>
    </update>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dk.mdm.model.pojo.mst.GoodsSku">
        <id column="sku_id" property="skuId"/>
                <result column="sku_code" property="skuCode"/>
                <result column="sku_name" property="skuName"/>
                <result column="sku_model" property="skuModel"/>
                <result column="brand_id" property="brandId" typeHandler="UuidTypeHandler"/>
                <result column="category_id" property="categoryId" typeHandler="UuidTypeHandler"/>
                <result column="unit_id" property="unitId" typeHandler="UuidTypeHandler"/>
                <result column="sub_unit_id" property="subUnitId" typeHandler="UuidTypeHandler"/>
                <result column="conversion_factor" property="conversionFactor"/>
                <result column="series_id" property="seriesId" typeHandler="UuidTypeHandler"/>
                <result column="sku_spec" property="skuSpec"/>
                <result column="price_purchase" property="pricePurchase"/>
                <result column="price_standard" property="priceStandard"/>
                <result column="price_wholesale" property="priceWholesale"/>
                <result column="price_limited" property="priceLimited"/>
                <result column="price_other" property="priceOther"/>
                <result column="sku_images" property="skuImages" typeHandler="JsonTypeHandler"/>
                <result column="warning_lower_limit" property="warningLowerLimit"/>
                <result column="warning_upper_limit" property="warningUpperLimit"/>
                <result column="remarks" property="remarks"/>
                <result column="flg_valid" property="flgValid"/>
                <result column="flg_sub_unit" property="flgSubUnit"/>
                <result column="flg_opening_inv" property="flgOpeningInv"/>
                <result column="flg_price" property="flgPrice"/>
                <result column="cp_id" property="cpId"/>
                <result column="op_create_time" property="opCreateTime" typeHandler="TimestampTypeHandler"/>
                <result column="op_create_user_id" property="opCreateUserId" typeHandler="UuidTypeHandler"/>
                <result column="op_update_time" property="opUpdateTime" typeHandler="TimestampTypeHandler"/>
                <result column="op_update_user_id" property="opUpdateUserId" typeHandler="UuidTypeHandler"/>
                <result column="op_app_code" property="opAppCode"/>
                <result column="op_timestamp" property="opTimestamp" typeHandler="TimestampTypeHandler"/>
                <result column="op_db_user" property="opDbUser"/>
        <result column="decimalPlaces" property="decimalPlaces"/>
    </resultMap>

    <sql id="Base_Column_List_JOIN">
        tmgs.price_other,tmgs.sku_id, tmgs.sku_code, tmgs.sku_name, tmgs.sku_model, tmgs.brand_id, tmgs.category_id, tmgs.unit_id, tmgs.sub_unit_id,
              tmgs.conversion_factor, tmgs.series_id, tmgs.sku_spec, tmgs.price_purchase, tmgs.price_standard,
           tmgs.pack_box,   tmgs.price_wholesale, tmgs.price_limited, tmgs.price_other,tmgs.sku_images, tmgs.remarks, tmgs.flg_valid, tmgs.flg_sub_unit,  tmgs.flg_opening_inv,  tmgs.flg_price,  tmgs.cp_id,
        tmgs.warning_lower_limit, tmgs.warning_upper_limit
    </sql>
    <resultMap id="BaseResultMapResponse" type="com.dk.mdm.model.response.mst.GoodsSkuResponse">
        <id column="sku_id" property="skuId"/>
        <result column="sku_code" property="skuCode"/>
        <result column="sku_name" property="skuName"/>
        <result column="sku_model" property="skuModel"/>
        <result column="brand_id" property="brandId" typeHandler="UuidTypeHandler"/>
        <result column="category_id" property="categoryId" typeHandler="UuidTypeHandler"/>
        <result column="unit_id" property="unitId" typeHandler="UuidTypeHandler"/>
        <result column="sub_unit_id" property="subUnitId" typeHandler="UuidTypeHandler"/>
        <result column="conversion_factor" property="conversionFactor"/>
        <result column="series_id" property="seriesId" typeHandler="UuidTypeHandler"/>
        <result column="sku_spec" property="skuSpec"/>
        <result column="price_purchase" property="pricePurchase"/>
        <result column="price_standard" property="priceStandard"/>
        <result column="price_wholesale" property="priceWholesale"/>
        <result column="price_other" property="priceOther"/>
        <result column="price_limited" property="priceLimited"/>
        <result column="price_other" property="priceOther"/>
        <result column="pack_box" property="packBox"/>
        <result column="sku_images" property="skuImages" typeHandler="JsonTypeHandler"/>
        <result column="remarks" property="remarks"/>
        <result column="flg_valid" property="flgValid"/>
        <result column="cp_id" property="cpId"/>
        <result column="inventoryCount" property="inventoryCount"/>
        <result column="subUnitName" property="subUnitName"/>
        <result column="unitName" property="unitName"/>
        <result column="wh_id" property="whId" typeHandler="UuidTypeHandler"/>
        <result column="wh_name" property="whName"/>
        <result column="non_std_code" property="nonStdCode"/>
        <result column="inv_qty" property="invQty"/>
        <result column="cost_price" property="costPrice"/>
        <result column="priceInto" property="priceInto"/>
        <result column="intoQty" property="intoQty"/>
        <result column="decimalPlaces" property="decimalPlaces"/>
        <result column="intoing_box" property="box" />
        <result column="intoing_piece" property="piece" />
        <result column="warning_lower_limit" property="warningLowerLimit"/>
        <result column="warning_upper_limit" property="warningUpperLimit"/>
    </resultMap>

    <!-- 通用条件列 -->
    <sql id="Condition">
        <where>
            <if test="skuCode != null and skuCode != ''">
                AND tmgs.sku_code = #{skuCode}
            </if>
            <if test="skuName != null and skuName != ''">
                AND tmgs.sku_name = #{skuName}
            </if>
            <if test="skuModel != null and skuModel != ''">
                AND tmgs.sku_model = #{skuModel}
            </if>
            <if test="brandId != null and brandId != ''">
                AND tmgs.brand_id = #{brandId}::uuid
            </if>
            <if test="skuId != null and skuId != ''">
                AND tmgs.sku_id = #{skuId}::uuid
            </if>
            <if test="categoryId != null and categoryId != ''">
                AND tmgs.category_id = #{categoryId}::uuid
            </if>
            <if test="unitId != null and unitId != ''">
                AND tmgs.unit_id = #{unitId}::uuid
            </if>
            <if test="subUnitId != null and subUnitId != ''">
                AND tmgs.sub_unit_id = #{subUnitId}::uuid
            </if>
            <if test="conversionFactor != null">
                AND tmgs.conversion_factor = #{conversionFactor}
            </if>
            <if test="seriesId != null and seriesId != ''">
                AND tmgs.series_id = #{seriesId}::uuid
            </if>
            <if test="skuSpec != null and skuSpec != ''">
                AND tmgs.sku_spec = #{skuSpec}
            </if>
            <if test="pricePurchase != null">
                AND tmgs.price_purchase = #{pricePurchase}
            </if>
            <if test="priceStandard != null">
                AND tmgs.price_standard = #{priceStandard}
            </if>
            <if test="priceWholesale != null">
                AND tmgs.price_wholesale = #{priceWholesale}
            </if>
            <if test="priceLimited != null">
                AND tmgs.price_limited = #{priceLimited}
            </if>
            <if test="skuImages != null and skuImages != ''">
                AND tmgs.sku_images = #{skuImages}
            </if>
            <if test="remarks != null and remarks != ''">
                AND tmgs.remarks = #{remarks}
            </if>
            <if test="flgValid != null">
                AND tmgs.flg_valid = #{flgValid}
            </if>
            <if test="flgValidList != null and flgValidList.size>0">
                AND tmgs.flg_valid  =any(#{flgValidList, typeHandler=BooleanListTypeHandler})
            </if>
            <if test="goodsBrandList != null and goodsBrandList.size>0">
                AND tmgs.brand_id  =any(#{goodsBrandList, typeHandler=UuidListTypeHandler})
            </if>
            <if test="cpId != null">
                AND tmgs.cp_id = #{cpId}
            </if>
            <if test="brandIds != null">
                AND   EXISTS (
                SELECT 1
                FROM unnest(string_to_array(#{brandIds}, ',')) AS brand_uuid
                WHERE brand_uuid::uuid = tmgs.brand_id
                )
            </if>
            <if test="searchText !=null">
                AND (tmgs.sku_name LIKE concat('%', my_ex.likequery(#{searchText}), '%')
                or tmgs.sku_model LIKE concat('%', my_ex.likequery(#{searchText}), '%'))
            </if>
        </where>
    </sql>

    <sql id="idsForeach">
        <!-- 根据主键skuId批量操作 -->
        WHERE sku_id in
        <foreach collection="ids" index="index" item="item" separator="," open="(" close=")">
            #{item}
        </foreach>
    </sql>

    <!-- 查询表t_mst_goods_sku，（条件查询+分页）列表 -->
    <select id="selectByCond" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_JOIN"/>
        ,tmgb.short_name AS "shortName"
        ,tmgb.brand_name AS "brandName",tmgsr.series_name AS "seriesName"
        ,tmgus.unit_name         as "subUnitName"
        ,tmgu.unit_name         as "unitName"
        ,tmgu.decimal_places    as "decimalPlaces"
        ,COALESCE((SELECT sum(tpi.usable_qty)  from dkic_b.t_psi_inventory tpi where tpi.sku_id = tmgs.sku_id and tpi.cp_id =  #{cpId} ),0) AS "usableQty"
        FROM dkic_b.t_mst_goods_sku  tmgs
        left join dkic_b.t_mst_unit as tmgu on tmgs.unit_id = tmgu.unit_id
        left join dkic_b.t_mst_unit as tmgus on tmgs.sub_unit_id = tmgus.unit_id
        LEFT JOIN dkic_b.t_mst_goods_brand tmgb ON tmgb.brand_id = tmgs.brand_id
        LEFT JOIN dkic_b.t_mst_goods_series tmgsr ON tmgsr.series_id = tmgs.series_id
        <include refid="Condition"/>
        order by  tmgs.op_create_time desc
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>

    <!-- 查询表t_mst_goods_sku，（条件查询）个数 -->
    <select id="countByCond" resultType="Long">
        SELECT
        count(1)
        FROM dkic_b.t_mst_goods_sku tmgs
        LEFT JOIN dkic_b.t_mst_goods_brand tmgb ON tmgb.brand_id = tmgs.brand_id
        LEFT JOIN dkic_b.t_mst_goods_series tmgsr ON tmgsr.series_id = tmgs.series_id
        <include refid="Condition"/>
    </select>

    <!-- 根据主键查询表t_mst_goods_sku的一行数据 -->
    <select id="selectById" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_JOIN"/>
        ,tmgb.brand_name AS "brandName"
           ,tmgc.cat_name AS "catName"
        ,tmu.unit_name AS "unitName"
        ,tmu.decimal_places    as "decimalPlaces"
        ,subtmu.unit_name AS "subUnitName"
        ,tmgsr.series_name AS "seriesName"
        ,(SELECT  count(1) FROM  dkic_b.t_psi_inventory tsic WHERE tsic.sku_id = tmgs.sku_id ) AS inventoryCount
        ,tpiid.wh_id,
        tpiid.wh_name,
        tpiid.non_std_code,
        tpiid.inv_qty as "intoQty",
        tpiid.cost_price  as "priceInto",
        tpiid.intoing_box,
        tpiid.intoing_piece
        FROM dkic_b.t_mst_goods_sku  tmgs
        LEFT JOIN (
        SELECT
        tpii.sku_id,
        tpii.intoing_box,
        tpii.intoing_piece,
        tmwitem.wh_id,
        tmwitem.wh_name,
        tpivt.non_std_code,
        tpivt.inv_qty,
        tpii.cost_price
        FROM
        dkic_b.t_psi_inbound_item tpii
        LEFT JOIN dkic_b.t_psi_inventory tpivt ON tpii.inv_id = tpivt.inv_id
        LEFT JOIN dkic_b.t_mst_warehouse tmwitem ON tpivt.wh_id = tmwitem.wh_id
        WHERE
        tpii.into_type = '入库类型-期初入库'
        ) tpiid ON tpiid.sku_id = tmgs.sku_id
        LEFT JOIN dkic_b.t_mst_goods_brand tmgb ON tmgb.brand_id = tmgs.brand_id
        LEFT JOIN dkic_b.t_mst_goods_category tmgc ON tmgc.cat_id = tmgs.category_id
        LEFT JOIN dkic_b.t_mst_unit tmu ON tmu.unit_id = tmgs.unit_id
        LEFT JOIN dkic_b.t_mst_unit subtmu ON subtmu.unit_id = tmgs.sub_unit_id
        LEFT JOIN dkic_b.t_mst_goods_series tmgsr ON tmgsr.series_id = tmgs.series_id
        WHERE tmgs.sku_id = #{id}::uuid
    </select>

    <!-- 根据主键锁定表t_mst_goods_sku的一行数据 -->
    <select id="selectByIdForUpdate" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_mst_goods_sku
        WHERE sku_id = #{skuId}
        for update
    </select>

    <!-- 根据主键锁定表t_mst_goods_sku的多行数据 -->
    <select id="selectByIdsForUpdate" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        FROM dkic_b.t_mst_goods_sku
        <include refid="idsForeach"/>
        for update
    </select>

    <insert id="insertBatch">
        insert into dkic_b.t_mst_goods_sku
        (
        <trim suffixOverrides=",">
            sku_code,
            sku_name,
            sku_model,
            brand_id,
            category_id,
            unit_id,
            sub_unit_id,
            conversion_factor,
            series_id,
            sku_spec,
            price_purchase,
            price_standard,
            price_wholesale,
            price_limited,
            sku_images,
            remarks,
            cp_id,
            op_app_code,
            warning_lower_limit,
            warning_upper_limit
        </trim>
        )
        values
        <foreach collection="list" index="index" item="item" separator=",">
            (
            <trim suffixOverrides=",">
                #{item.skuCode},
                #{item.skuName},
                #{item.skuModel},
                #{item.brandId}::uuid,
                #{item.categoryId}::uuid,
                #{item.unitId}::uuid,
                #{item.subUnitId}::uuid,
                #{item.conversionFactor},
                #{item.seriesId}::uuid,
                #{item.skuSpec},
                #{item.pricePurchase},
                #{item.priceStandard},
                #{item.priceWholesale},
                #{item.priceLimited},
                #{item.skuImages},
                #{item.remarks},
                #{item.cpId},
                #{item.opAppCode},
                #{item.warningLowerLimit},
                #{item.warningUpperLimit}
            </trim>
            )
        </foreach>
    </insert>
</mapper>
