<?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.lframework.xingyun.sc.mappers.TakeStockPlanDetailMapper">

    <resultMap id="GetTakeStockPlanDetailProductDto" type="com.lframework.xingyun.sc.dto.stock.take.plan.GetTakeStockPlanDetailProductDto">
        <id column="id" property="id"/>
        <result column="product_id" property="productId"/>
        <result column="stock_num" property="stockNum"/>
    </resultMap>

    <resultMap id="TakeStockPlanDetail" type="com.lframework.xingyun.sc.entity.TakeStockPlanDetail">
        <id column="id" property="id"/>
        <result column="product_id" property="productId"/>
        <result column="stock_num" property="stockNum"/>
        <result column="take_num" property="takeNum"/>
        <result column="total_out_num" property="totalOutNum"/>
        <result column="total_in_num" property="totalInNum"/>
        <result column="description" property="description"/>
        <result column="order_no" property="orderNo"/>
    </resultMap>

    <sql id="GetTakeStockPlanDetailProductDto_sql">
        SELECT
            tb.id,
            tb.product_id,
            tb.stock_num
        FROM tbl_take_stock_plan_detail AS tb
    </sql>

    <sql id="TakeStockPlanDetailDto_sql">
        SELECT
            tb.id,
            tb.product_id,
            tb.stock_num,
            tb.take_num,
            tb.total_out_num,
            tb.total_in_num,
            tb.description,
            tb.order_no
        FROM tbl_take_stock_plan_detail AS tb
    </sql>
    <insert id="addTotalInNum">
        UPDATE tbl_take_stock_plan_detail SET total_in_num = total_in_num + #{num}
        WHERE plan_id IN (SELECT id from tbl_take_stock_plan WHERE sc_id = #{scId} AND take_status = 0) AND product_id = #{productId}
    </insert>
    <insert id="addTotalOutNum">
        UPDATE tbl_take_stock_plan_detail SET total_out_num = total_out_num + #{num}
        WHERE plan_id IN (SELECT id from tbl_take_stock_plan WHERE sc_id = #{scId} AND take_status = 0) AND product_id = #{productId}
    </insert>
    <update id="updateOriTakeNum">
        UPDATE tbl_take_stock_plan_detail set ori_take_num = IFNULL(ori_take_num, 0) + #{num}
        WHERE plan_id = #{planId} AND product_id = #{productId}
    </update>
    <select id="getByPlanIdAndProductId" resultMap="GetTakeStockPlanDetailProductDto">
        <include refid="GetTakeStockPlanDetailProductDto_sql"/>
        WHERE tb.plan_id = #{planId}
        AND tb.product_id = #{productId}
    </select>
    <select id="getDetailsByPlanId" resultMap="TakeStockPlanDetail">
        <include refid="TakeStockPlanDetailDto_sql"/>
        WHERE tb.plan_id = #{planId}
        ORDER BY tb.order_no
    </select>
</mapper>