<?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.ivt.InventoryMapper">

    <!-- 通用设置 -->
    <!-- 通用查询列 -->
    <sql id="Base_Column_List">
        inv_id, wh_id, sku_id, non_std_code, sys.f_remove_zero(inv_qty) as inv_qty, sys.f_remove_zero(outing_qty) as outing_qty,
        sys.f_remove_zero(usable_qty) as usable_qty, cost_price, cost_amt, 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, sys.f_remove_zero(freeze_qty) as freeze_qty
    </sql>
    <!-- 通用查询列Response -->
    <sql id="Base_Column_List_Response">
        tpi.inv_id, tpi.wh_id, tpi.sku_id, tpi.non_std_code, sys.f_remove_zero(tpi.inv_qty) as inv_qty,
        sys.f_remove_zero(tpi.outing_qty) as outing_qty,
        sys.f_remove_zero(tpi.usable_qty) as usable_qty, tpi.cost_price, tpi.cost_amt, tpi.remarks, tpi.flg_valid,
        tpi.cp_id,sys.f_remove_zero(tpi.freeze_qty) as freeze_qty
    </sql>

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dk.mdm.model.pojo.ivt.Inventory">
        <id column="inv_id" property="invId"/>
                <result column="wh_id" property="whId" typeHandler="UuidTypeHandler"/>
                <result column="sku_id" property="skuId" typeHandler="UuidTypeHandler"/>
                <result column="non_std_code" property="nonStdCode"/>
                <result column="inv_qty" property="invQty"/>
                <result column="outing_qty" property="outingQty"/>
                <result column="usable_qty" property="usableQty"/>
                <result column="cost_price" property="costPrice"/>
                <result column="cost_amt" property="costAmt"/>
                <result column="remarks" property="remarks"/>
                <result column="flg_valid" property="flgValid"/>
                <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="freeze_qty" property="freezeQty"/>
        <result column="decimalPlaces" property="decimalPlaces"/>
    </resultMap>
    <!-- 通用查询映射结果Response -->
    <resultMap id="BaseResultMapResponse" type="com.dk.mdm.model.response.ivt.InventoryResponse">
        <id column="inv_id" property="invId"/>
                <result column="wh_id" property="whId" typeHandler="UuidTypeHandler"/>
                <result column="sku_id" property="skuId" typeHandler="UuidTypeHandler"/>
                <result column="non_std_code" property="nonStdCode"/>
                <result column="inv_qty" property="invQty"/>
                <result column="outing_qty" property="outingQty"/>
                <result column="usable_qty" property="usableQty"/>
                <result column="cost_price" property="costPrice"/>
                <result column="cost_amt" property="costAmt"/>
                <result column="remarks" property="remarks"/>
                <result column="flg_valid" property="flgValid"/>
                <result column="cp_id" property="cpId"/>
                <result column="sku_code" property="skuCode"/>
                <result column="sku_name" property="skuName"/>
                  <result column="sku_spec" property="skuSpec"/>
                <result column="sku_model" property="skuModel"/>
                <result column="brand_name" property="brandName"/>
                <result column="short_name" property="shortName"/>
                <result column="wh_name" property="whName"/>
                <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="unit_id" property="unitId" typeHandler="UuidTypeHandler"/>
        <result column="sub_unit_id" property="subUnitId" typeHandler="UuidTypeHandler"/>
        <result column="pack_box" property="packBox"/>
        <result column="subUnitName" property="subUnitName"/>
        <result column="unitName" property="unitName"/>
        <result column="flg_sub_unit" property="flgSubUnit"/>
        <result column="seriesName" property="seriesName"/>
        <result column="catName" property="catName"/>
        <result column="price_other" property="priceOther"/>
        <result column="sku_images" property="skuImages" typeHandler="JsonTypeHandler"/>
        <result column="decimalPlaces" property="decimalPlaces"/>
    </resultMap>

    <!-- 通用条件列 -->
    <sql id="Condition">
        <where>
            <if test="whId != null and whId != ''">
                AND tpi.wh_id = #{whId}::UUID
            </if>
            <if test="whIds != null and whIds.size()>0">
                AND tpi.wh_id =
                any(#{whIds, typeHandler=UuidListTypeHandler})
            </if>
            <if test="skuId != null and skuId != ''">
                AND tpi.sku_id = #{skuId}
            </if>
            <if test="nonStdCode != null and nonStdCode != ''">
                AND tpi.non_std_code = #{nonStdCode}
            </if>
            <if test="invQty != null">
                AND tpi.inv_qty = #{invQty}
            </if>
            <if test="outingQty != null">
                AND tpi.outing_qty = #{outingQty}
            </if>
            <if test="usableQty != null">
                AND tpi.usable_qty = #{usableQty}
            </if>
            <if test="costPrice != null">
                AND tpi.cost_price = #{costPrice}
            </if>
            <if test="costAmt != null">
                AND tpi.cost_amt = #{costAmt}
            </if>
            <if test="flgValid != null">
                AND tpi.flg_valid = #{flgValid}
            </if>
            <if test="flgZero == true">
                AND tpi.inv_qty != 0
            </if>
            <if test="cpId != null">
                AND tpi.cp_id = #{cpId}
            </if>
            <if test="freezeQty != null">
                AND tpi.freeze_qty = #{freezeQty}
            </if>
            <if test="categoryId != null and categoryId != ''">
                AND tmgs.category_id = #{categoryId}::UUID
            </if>
            <if test="brandId != null and brandId != ''">
                AND tmgs.brand_id = #{brandId}::UUID
            </if>
            <if  test="searchText != null">
                AND (tmgs.sku_model  like concat('%', my_ex.likequery(#{searchText}) , '%')
                OR  tmgs.sku_name like concat('%', my_ex.likequery(#{searchText}) , '%')
                OR  tpi.non_std_code like concat('%', my_ex.likequery(#{searchText}) , '%')
                )
            </if>
            <if test="invQtyFlag != null and invQtyFlag = true">
                and tpi.inv_qty != 0

            </if>
        </where>
    </sql>

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

    <!-- 查询表dkic_b.t_psi_inventory，（条件查询+分页）列表 -->
    <select id="selectByCond" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_Response"/>
        ,tmgs.sku_code
        ,tmgs.sku_model
        ,tmgs.sku_name
        ,tmgs.sku_spec
        ,tmgs.price_purchase
        ,tmgs.price_standard
        ,tmgs.price_wholesale
        ,tmgs.price_other
        ,tmgs.price_limited
        ,tmgs.sku_images
        ,tmgs.unit_id
        ,tmgs.sub_unit_id
        ,tmgs.pack_box
        ,tmu.unit_name    AS "unitName"
        ,subtmu.unit_name AS "subUnitName"
        ,tmgs.flg_sub_unit
        ,tmgb.brand_name
        ,tmgb.short_name
        ,tmw.wh_name
        ,tmgc.cat_name as "catName"
        ,tmgseries.series_name as "seriesName"
        ,tmu.decimal_places    as "decimalPlaces"
        FROM dkic_b.t_psi_inventory tpi
        <include refid="Join_Table"/>
        <include refid="Condition"/>
        <if test="desc != null and desc != ''">
            order by tpi.usable_qty desc
        </if>
        <if test="desc == null or desc == ''">
            order by tpi.usable_qty
        </if>
        <if test="pageSize != null and currentPage != null and pageSize != 0 and currentPage != 0">
            limit #{end} offset #{start}
        </if>
    </select>

    <!-- 查询表dkic_b.t_psi_inventory，（条件查询）个数 -->
    <select id="countByCond" resultType="Long">
        SELECT
        count(1)
        FROM dkic_b.t_psi_inventory tpi
        <include refid="Join_Table"/>
        <include refid="Condition"/>
    </select>

    <sql id="Join_Table">
        left join dkic_b.t_mst_goods_sku tmgs on tmgs.sku_id = tpi.sku_id
        left join dkic_b.t_mst_warehouse tmw on tmw.wh_id = tpi.wh_id
        LEFT JOIN dkic_b.t_mst_goods_brand tmgb ON tmgb.brand_id = tmgs.brand_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_category as tmgc on tmgs.category_id = tmgc.cat_id
        left join dkic_b.t_mst_goods_series as tmgseries on tmgs.series_id = tmgseries.series_id

    </sql>


    <!-- 根据主键查询表dkic_b.t_psi_inventory的一行数据 -->
    <select id="selectById" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_Response"/>
        ,tmu.decimal_places    as "decimalPlaces"
        FROM dkic_b.t_psi_inventory tpi
        left join dkic_b.t_mst_goods_sku tmgs on tmgs.sku_id = tpi.sku_id
        LEFT JOIN dkic_b.t_mst_unit tmu ON tmu.unit_id = tmgs.unit_id
        WHERE tpi.inv_id = #{id}::uuid
    </select>

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

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

    <insert id="insertBatch">
        insert into dkic_b.t_psi_inventory
        (
        <trim suffixOverrides=",">
            wh_id,
            sku_id,
            non_std_code,
            inv_qty,
            outing_qty,
            usable_qty,
            cost_price,
            cost_amt,
            remarks,
            cp_id,
            op_app_code,
            freeze_qty,
        </trim>
        )
        values
        <foreach collection="list" index="index" item="item" separator=",">
            (
            <trim suffixOverrides=",">
                #{item.whId}::uuid,
                #{item.skuId}::uuid,
                #{item.nonStdCode},
                #{item.invQty},
                #{item.outingQty},
                #{item.usableQty},
                #{item.costPrice},
                #{item.costAmt},
                #{item.remarks},
                #{item.cpId},
                #{item.opAppCode},
                #{item.freezeQty},
            </trim>
            )
        </foreach>
    </insert>

    <!-- 查询表dkic_b.t_psi_inventory，（条件查询+分页）列表 -->
    <select id="selectByOther" resultMap="BaseResultMapResponse">
        SELECT
        <include refid="Base_Column_List_Response"/>
        ,tmu.decimal_places    as "decimalPlaces"
        FROM dkic_b.t_psi_inventory tpi
        left join dkic_b.t_mst_goods_sku tmgs on tmgs.sku_id = tpi.sku_id
        LEFT JOIN dkic_b.t_mst_unit tmu ON tmu.unit_id = tmgs.unit_id
        <where>
            <if test="whId != null and whId != ''">
                AND tpi.wh_id = #{whId}::uuid
            </if>
            <if test="skuId != null and skuId != ''">
                AND tpi.sku_id = #{skuId}::uuid
            </if>
            <if test="nonStdCode != null and nonStdCode != ''">
                AND tpi.non_std_code = #{nonStdCode}
            </if>
            <if test="nonStdCode == null and nonStdCode == ''">
                AND tpi.non_std_code = '-'
            </if>
        </where>
    </select>

    <!--修改库存数量金额-->
    <update id="updateAmountAndQuantity" parameterType="com.dk.mdm.model.vo.ivt.InventoryVO">
        update dkic_b.t_psi_inventory
        <set>
            <if test="invQty != null">
                inv_qty = inv_qty + #{invQty,jdbcType=NUMERIC},
                usable_qty = (inv_qty + #{invQty,jdbcType=NUMERIC}) - outing_qty - freeze_qty,
                <if test="zeroFlag">
                    cost_amt = 0,
                    cost_price = 0 ,
                </if>
                <if test="!zeroFlag">
                    cost_amt = cost_amt + #{costAmt,jdbcType=NUMERIC},
                    cost_price = (cost_amt + #{costAmt,jdbcType=NUMERIC}) / (inv_qty + #{invQty,jdbcType=NUMERIC}) ,
                </if>
            </if>
        </set>
        where inv_id =#{invId,typeHandler=UuidTypeHandler}
        and inv_qty + #{invQty,jdbcType=NUMERIC}>=0
        and cost_amt + #{costAmt,jdbcType=NUMERIC}>=0
    </update>

    <!--修改库存数量金额(删除用)-->
    <update id="updateAmtAndQty" parameterType="com.dk.mdm.model.pojo.ivt.Inventory">
        update dkic_b.t_psi_inventory
        <set>
            <if test="invQty != null">
                inv_qty = #{invQty,jdbcType=NUMERIC},
            </if>
            <if test="usableQty != null">
                usable_qty = #{usableQty,jdbcType=NUMERIC},
            </if>
            <if test="costPrice != null">
                cost_price = #{costPrice,jdbcType=NUMERIC},
            </if>
            <if test="costAmt != null">
                cost_amt = #{costAmt,jdbcType=NUMERIC},
            </if>
        </set>
        where inv_id =#{invId,typeHandler=UuidTypeHandler}
        and #{invQty,jdbcType=NUMERIC}>=0
        and #{costAmt,jdbcType=NUMERIC}>=0
    </update>


    <!--删除数据-->
    <delete id="deleteData" parameterType="com.dk.mdm.model.pojo.ivt.InOutRecord">
        DELETE
        FROM dkic_b.t_psi_inventory
        where inv_id = #{invId,typeHandler=UuidTypeHandler}
    </delete>

    <!--修改存货单价/存货资产-->
    <update id="updateCost" parameterType="com.dk.mdm.model.pojo.ivt.Inventory">
        update dkic_b.t_psi_inventory
        <set>
            <if test="costPrice != null">
                cost_price = #{costPrice,jdbcType=NUMERIC},
            </if>
            <if test="costAmt != null">
                cost_amt = #{costAmt,jdbcType=NUMERIC},
            </if>
        </set>
        where inv_id =#{invId,typeHandler=UuidTypeHandler}
    </update>


</mapper>
