<?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.asset.mapper.AmsReceiveOrderMapper">

    <resultMap type="AmsReceiveOrder" id="AmsReceiveOrderResult">
        <result property="orderId" column="order_id" />
        <result property="receiveNo" column="receive_no" />
        <result property="applicantId" column="applicant_id" />
        <result property="applicantName" column="applicant_name" />
        <result property="applyDeptId" column="apply_dept_id" />
        <result property="applyDeptName" column="apply_dept_name" />
        <result property="confirmUserId" column="confirm_user_id" />
        <result property="confirmUserName" column="confirm_user_name" />
        <result property="confirmTime" column="confirm_time" />
        <result property="rejectReason" column="reject_reason" />
        <result property="orderStatus" column="order_status" />
        <result property="createBy" column="create_by" />
        <result property="createTime" column="create_time" />
        <result property="updateBy" column="update_by" />
        <result property="updateTime" column="update_time" />
        <result property="remark" column="remark" />
        <result property="delFlag" column="del_flag" />
    </resultMap>

    <resultMap id="AmsReceiveOrderItemCollectionResult" type="AmsReceiveOrder" extends="AmsReceiveOrderResult">
        <collection property="amsReceiveOrderItemList" ofType="AmsReceiveOrderItem"
                    column="order_id" select="selectAmsReceiveOrderItemList" />
    </resultMap>

    <resultMap type="AmsReceiveOrderItem" id="AmsReceiveOrderItemResult">
        <result property="itemId" column="item_id" />
        <result property="orderId" column="order_id" />
        <result property="receiveNo" column="receive_no" />
        <result property="assetId" column="asset_id" />
        <result property="assetCode" column="asset_code" />
        <result property="assetName" column="asset_name" />
        <result property="categoryId" column="category_id" />
        <result property="categoryCode" column="category_code" />
        <result property="categoryName" column="category_name" />
        <result property="specModel" column="spec_model" />
        <result property="brand" column="brand" />
        <result property="assetStatus" column="asset_status" />
        <result property="beforeWarehouseId" column="before_warehouse_id" />
        <result property="beforeWarehouseCode" column="before_warehouse_code" />
        <result property="beforeWarehouseName" column="before_warehouse_name" />
        <result property="beforeLocationId" column="before_location_id" />
        <result property="beforeLocationCode" column="before_location_code" />
        <result property="beforeLocationName" column="before_location_name" />
        <result property="receiveUserId" column="receive_user_id" />
        <result property="receiveUserName" column="receive_user_name" />
        <result property="receiveDeptId" column="receive_dept_id" />
        <result property="receiveDeptName" column="receive_dept_name" />
        <result property="createBy" column="create_by" />
        <result property="createTime" column="create_time" />
        <result property="updateBy" column="update_by" />
        <result property="updateTime" column="update_time" />
        <result property="remark" column="remark" />
        <result property="delFlag" column="del_flag" />
    </resultMap>

    <resultMap type="AmsAsset" id="AvailableReceiveAssetResult">
        <result property="assetId" column="asset_id" />
        <result property="assetCode" column="asset_code" />
        <result property="assetName" column="asset_name" />
        <result property="categoryId" column="category_id" />
        <result property="categoryCode" column="category_code" />
        <result property="categoryName" column="category_name" />
        <result property="specModel" column="spec_model" />
        <result property="brand" column="brand" />
        <result property="assetStatus" column="asset_status" />
        <result property="warehouseId" column="warehouse_id" />
        <result property="warehouseCode" column="warehouse_code" />
        <result property="warehouseName" column="warehouse_name" />
        <result property="locationId" column="location_id" />
        <result property="locationCode" column="location_code" />
        <result property="locationName" column="location_name" />
        <result property="tagCode" column="tag_code" />
    </resultMap>

    <sql id="selectAmsReceiveOrderVo">
        select order_id, receive_no, applicant_id, applicant_name, apply_dept_id, apply_dept_name,
               confirm_user_id, confirm_user_name, confirm_time, reject_reason, order_status,
               create_by, create_time, update_by, update_time, remark, del_flag
        from ams_receive_order
    </sql>

    <select id="selectAmsReceiveOrderList" parameterType="AmsReceiveOrder" resultMap="AmsReceiveOrderResult">
        <include refid="selectAmsReceiveOrderVo"/>
        <where>
            del_flag = '0'
            <if test="receiveNo != null and receiveNo != ''">
                and receive_no like concat(#{receiveNo}, '%')
            </if>
            <if test="applicantName != null and applicantName != ''">
                and applicant_name like concat('%', #{applicantName}, '%')
            </if>
            <if test="applyDeptId != null">
                and apply_dept_id = #{applyDeptId}
            </if>
            <if test="params.beginConfirmTime != null and params.beginConfirmTime != ''">
                and confirm_time &gt;= #{params.beginConfirmTime}
            </if>
            <if test="params.endConfirmTime != null and params.endConfirmTime != ''">
                and confirm_time &lt; date_add(#{params.endConfirmTime}, interval 1 day)
            </if>
            <if test="orderStatus != null and orderStatus != ''">
                and order_status = #{orderStatus}
            </if>
            <if test="params.assetCode != null and params.assetCode != ''">
                and exists (
                    select 1 from ams_receive_order_item item
                    where item.order_id = ams_receive_order.order_id
                      and item.del_flag = '0'
                      and item.asset_code like concat(#{params.assetCode}, '%')
                )
            </if>
        </where>
        order by create_time desc, order_id desc
    </select>

    <select id="selectAmsReceiveOrderByOrderId" parameterType="Long"
            resultMap="AmsReceiveOrderItemCollectionResult">
        <include refid="selectAmsReceiveOrderVo"/>
        where order_id = #{orderId} and del_flag = '0'
    </select>

    <select id="selectAmsReceiveOrderByOrderIdForUpdate" parameterType="Long"
            resultMap="AmsReceiveOrderItemCollectionResult">
        <include refid="selectAmsReceiveOrderVo"/>
        where order_id = #{orderId} and del_flag = '0'
        for update
    </select>

    <select id="selectAvailableReceiveAssetList" resultMap="AvailableReceiveAssetResult">
        select asset.asset_id, asset.asset_code, asset.asset_name, asset.category_id,
               asset.category_code, asset.category_name, asset.spec_model, asset.brand,
               asset.asset_status, asset.warehouse_id, asset.warehouse_code, asset.warehouse_name,
               asset.location_id, asset.location_code, asset.location_name, asset.tag_code
        from ams_asset asset
        where asset.del_flag = '0'
          and asset.asset_status = #{stockStatus}
          and not exists (
              select 1
              from ams_receive_order_item item
              inner join ams_receive_order receive_order on receive_order.order_id = item.order_id
                  and receive_order.del_flag = '0'
                  and receive_order.order_status in (#{draftStatus}, #{pendingStatus})
              where item.asset_id = asset.asset_id
                and item.del_flag = '0'
                <if test="currentOrderId != null">
                    and receive_order.order_id != #{currentOrderId}
                </if>
          )
        <if test="asset.assetCode != null and asset.assetCode != ''">
            and asset.asset_code like concat('%', #{asset.assetCode}, '%')
        </if>
        <if test="asset.assetName != null and asset.assetName != ''">
            and asset.asset_name like concat('%', #{asset.assetName}, '%')
        </if>
        <if test="asset.categoryName != null and asset.categoryName != ''">
            and asset.category_name like concat('%', #{asset.categoryName}, '%')
        </if>
        order by asset.asset_id
    </select>

    <select id="countOtherActiveReceiveOrderByAssetId" resultType="int">
        select count(1)
        from ams_receive_order_item item
        inner join ams_receive_order receive_order on receive_order.order_id = item.order_id
            and receive_order.del_flag = '0'
            and receive_order.order_status in (#{draftStatus}, #{pendingStatus})
        where item.asset_id = #{assetId}
          and item.del_flag = '0'
          <if test="currentOrderId != null">
              and receive_order.order_id != #{currentOrderId}
          </if>
    </select>

    <select id="selectAmsReceiveOrderItemList" resultMap="AmsReceiveOrderItemResult">
        select item.item_id, item.order_id, item.receive_no, item.asset_id, item.asset_code,
               item.asset_name, item.category_id, item.category_code, item.category_name,
               item.spec_model, item.brand, asset.asset_status, item.before_warehouse_id,
               item.before_warehouse_code, item.before_warehouse_name, item.before_location_id,
               item.before_location_code, item.before_location_name, item.receive_user_id,
               item.receive_user_name, item.receive_dept_id, item.receive_dept_name,
               item.create_by, item.create_time, item.update_by, item.update_time,
               item.remark, item.del_flag
        from ams_receive_order_item item
        left join ams_asset asset on asset.asset_id = item.asset_id and asset.del_flag = '0'
        where item.order_id = #{order_id} and item.del_flag = '0'
        order by item.item_id
    </select>

    <insert id="insertAmsReceiveOrder" parameterType="AmsReceiveOrder"
            useGeneratedKeys="true" keyProperty="orderId">
        insert into ams_receive_order (
            receive_no, applicant_id, applicant_name, apply_dept_id, apply_dept_name,
            order_status, create_by, create_time, remark, del_flag
        ) values (
            #{receiveNo}, #{applicantId}, #{applicantName}, #{applyDeptId}, #{applyDeptName},
            #{orderStatus}, #{createBy}, #{createTime}, #{remark}, #{delFlag}
        )
    </insert>

    <!--
        保存编辑：更新领用单备注等非核心状态字段。
        限制：只有处于 'DRAFT' 草稿状态的领用单才允许修改，构成状态一致性的安全防线。
    -->
    <update id="updateAmsReceiveOrder" parameterType="AmsReceiveOrder">
        update ams_receive_order
        set remark = #{remark},
            update_by = #{updateBy},
            update_time = #{updateTime}
        where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <!--
        提交领用单：将领用单状态由草稿扭转为 PENDING_CONFIRM (待确认)，并清空以前的驳回原因。
        限制：仅允许 'DRAFT' 草稿状态的领用单提交。
    -->
    <update id="submitAmsReceiveOrder" parameterType="AmsReceiveOrder">
        update ams_receive_order
        set order_status = #{orderStatus},
            reject_reason = null,
            update_by = #{updateBy},
            update_time = #{updateTime}
        where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <!--
        确认领用：记录确认人用户ID、确认人姓名快照、确认时间，并将状态扭转为 COMPLETED。
        限制：只有处于 PENDING_CONFIRM (待确认) 状态的单据才能执行确认，防止状态并发冲突。
    -->
    <update id="confirmAmsReceiveOrder" parameterType="AmsReceiveOrder">
        update ams_receive_order
        set order_status = #{orderStatus},
            confirm_user_id = #{confirmUserId},
            confirm_user_name = #{confirmUserName},
            confirm_time = #{confirmTime},
            reject_reason = null,
            update_by = #{updateBy},
            update_time = #{updateTime}
        where order_id = #{orderId} and del_flag = '0' and order_status = 'PENDING_CONFIRM'
    </update>

    <!--
        驳回申请：记录驳回原因，并将状态扭转为 REJECTED。
        限制：只有处于 PENDING_CONFIRM (待确认) 状态的单据才能执行驳回。
    -->
    <update id="rejectAmsReceiveOrder" parameterType="AmsReceiveOrder">
         update ams_receive_order
         set order_status = #{orderStatus},
             reject_reason = #{rejectReason},
             update_by = #{updateBy},
             update_time = #{updateTime}
         where order_id = #{orderId} and del_flag = '0' and order_status = 'PENDING_CONFIRM'
     </update>

    <update id="deleteAmsReceiveOrderByOrderId" parameterType="Long">
        update ams_receive_order
        set del_flag = '1'
        where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <update id="deleteAmsReceiveOrderByOrderIds" parameterType="String">
        update ams_receive_order
        set del_flag = '1'
        where order_id in
        <foreach item="orderId" collection="array" open="(" separator="," close=")">
            #{orderId}
        </foreach>
        and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <update id="deleteAmsReceiveOrderItemByOrderIds" parameterType="String">
        update ams_receive_order_item
        set del_flag = '1'
        where order_id in
        <foreach item="orderId" collection="array" open="(" separator="," close=")">
            #{orderId}
        </foreach>
        and del_flag = '0'
    </update>

    <update id="deleteAmsReceiveOrderItemByOrderId" parameterType="Long">
        update ams_receive_order_item
        set del_flag = '1'
        where order_id = #{orderId} and del_flag = '0'
    </update>

    <insert id="batchAmsReceiveOrderItem">
        insert into ams_receive_order_item (
            order_id, receive_no, asset_id, asset_code, asset_name, category_id, category_code,
            category_name, spec_model, brand, before_warehouse_id, before_warehouse_code,
            before_warehouse_name, before_location_id, before_location_code, before_location_name,
            receive_user_id, receive_user_name, receive_dept_id, receive_dept_name,
            create_by, create_time, remark, del_flag
        ) values
        <foreach item="item" collection="list" separator=",">
            (
                #{item.orderId}, #{item.receiveNo}, #{item.assetId}, #{item.assetCode},
                #{item.assetName}, #{item.categoryId}, #{item.categoryCode}, #{item.categoryName},
                #{item.specModel}, #{item.brand}, #{item.beforeWarehouseId},
                #{item.beforeWarehouseCode}, #{item.beforeWarehouseName}, #{item.beforeLocationId},
                #{item.beforeLocationCode}, #{item.beforeLocationName}, #{item.receiveUserId},
                #{item.receiveUserName}, #{item.receiveDeptId}, #{item.receiveDeptName},
                #{item.createBy}, #{item.createTime}, #{item.remark}, #{item.delFlag}
            )
        </foreach>
    </insert>

</mapper>
