<?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.ruoyi.web.modules.stock.mapper.BizStockLogMapper">

    <resultMap id="StockLogListRowResult" type="com.ruoyi.web.modules.stock.vo.StockLogListRowVO">
        <id property="logId" column="log_id"/>
        <result property="goodsId" column="goods_id"/>
        <result property="goodsName" column="goods_name"/>
        <result property="specText" column="spec_text"/>
        <result property="stockBefore" column="stock_before"/>
        <result property="stockAfter" column="stock_after"/>
        <result property="changeQty" column="change_qty"/>
        <result property="direction" column="direction"/>
        <result property="changeReason" column="change_reason"/>
        <result property="createTime" column="create_time"/>
    </resultMap>

    <sql id="listSelect">
        select log_id, goods_id, goods_name, spec_text, stock_before, stock_after,
               change_qty, direction, change_reason, create_time
        from biz_stock_log
    </sql>

    <sql id="listWhere">
        where shop_id = #{shopId}
        <if test="query != null and query.direction != null and query.direction != ''">
            and direction = #{query.direction}
        </if>
        <if test="query != null and query.keyword != null and query.keyword != ''">
            and (
                goods_name like concat('%', #{query.keyword}, '%')
                or (spec_text is not null and spec_text &lt;&gt; '—'
                    and spec_text like concat('%', #{query.keyword}, '%'))
            )
        </if>
    </sql>

    <insert id="insert" useGeneratedKeys="true" keyProperty="logId">
        insert into biz_stock_log (shop_id, goods_id, sku_id, goods_name, spec_text, direction, change_reason,
                                   change_qty, stock_before, stock_after, ref_type, ref_id, ref_no,
                                   operator_id, operator_name, create_time)
        values (#{shopId}, #{goodsId}, #{skuId}, #{goodsName}, #{specText}, #{direction}, #{changeReason},
                #{changeQty}, #{stockBefore}, #{stockAfter}, #{refType}, #{refId}, #{refNo},
                #{operatorId}, #{operatorName}, #{createTime})
    </insert>

    <select id="selectList" resultMap="StockLogListRowResult">
        <include refid="listSelect"/>
        <include refid="listWhere"/>
        order by create_time desc, log_id desc
    </select>

    <select id="selectByGoodsId" resultMap="StockLogListRowResult">
        <include refid="listSelect"/>
        where shop_id = #{shopId}
          and goods_id = #{goodsId}
        order by create_time desc, log_id desc
    </select>
</mapper>
