<?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.AmsTransferOrderMapper">

    <resultMap type="AmsTransferOrder" id="AmsTransferOrderResult">
        <result property="orderId" column="order_id" />
        <result property="transferNo" column="transfer_no" />
        <result property="applicantId" column="applicant_id" />
        <result property="applicantName" column="applicant_name" />
        <result property="transferReason" column="transfer_reason" />
        <result property="confirmUserId" column="confirm_user_id" />
        <result property="confirmUserName" column="confirm_user_name" />
        <result property="confirmTime" column="confirm_time" />
        <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="AmsTransferOrderItemCollectionResult" type="AmsTransferOrder" extends="AmsTransferOrderResult">
        <collection property="amsTransferOrderItemList" ofType="AmsTransferOrderItem"
                    column="order_id" select="selectAmsTransferOrderItemList" />
    </resultMap>

    <resultMap type="AmsTransferOrderItem" id="AmsTransferOrderItemResult">
        <result property="itemId" column="item_id" />
        <result property="orderId" column="order_id" />
        <result property="transferNo" column="transfer_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="oldDeptId" column="old_dept_id" />
        <result property="oldDeptName" column="old_dept_name" />
        <result property="newDeptId" column="new_dept_id" />
        <result property="newDeptName" column="new_dept_name" />
        <result property="oldUserId" column="old_user_id" />
        <result property="oldUserName" column="old_user_name" />
        <result property="newUserId" column="new_user_id" />
        <result property="newUserName" column="new_user_name" />
        <result property="oldWarehouseId" column="old_warehouse_id" />
        <result property="oldWarehouseCode" column="old_warehouse_code" />
        <result property="oldWarehouseName" column="old_warehouse_name" />
        <result property="newWarehouseId" column="new_warehouse_id" />
        <result property="newWarehouseCode" column="new_warehouse_code" />
        <result property="newWarehouseName" column="new_warehouse_name" />
        <result property="oldLocationId" column="old_location_id" />
        <result property="oldLocationCode" column="old_location_code" />
        <result property="oldLocationName" column="old_location_name" />
        <result property="newLocationId" column="new_location_id" />
        <result property="newLocationCode" column="new_location_code" />
        <result property="newLocationName" column="new_location_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="AvailableTransferAssetResult">
        <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="useDeptId" column="use_dept_id" />
        <result property="useDeptName" column="use_dept_name" />
        <result property="useUserId" column="use_user_id" />
        <result property="useUserName" column="use_user_name" />
        <result property="tagCode" column="tag_code" />
    </resultMap>

    <sql id="selectAmsTransferOrderVo">
        select order_id, transfer_no, applicant_id, applicant_name, transfer_reason,
               confirm_user_id, confirm_user_name, confirm_time, order_status,
               create_by, create_time, update_by, update_time, remark, del_flag
        from ams_transfer_order
    </sql>

    <select id="selectAmsTransferOrderList" parameterType="AmsTransferOrder" resultMap="AmsTransferOrderResult">
        <include refid="selectAmsTransferOrderVo"/>
        <where>
            del_flag = '0'
            <if test="transferNo != null and transferNo != ''">
                and transfer_no like concat(#{transferNo}, '%')
            </if>
            <if test="applicantName != null and applicantName != ''">
                and applicant_name like concat('%', #{applicantName}, '%')
            </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_transfer_order_item item
                    where item.order_id = ams_transfer_order.order_id
                      and item.del_flag = '0'
                      and item.asset_code like concat(#{params.assetCode}, '%')
                )
            </if>
            <if test="params.oldWarehouseId != null and params.oldWarehouseId != ''">
                and exists (
                    select 1 from ams_transfer_order_item item
                    where item.order_id = ams_transfer_order.order_id
                      and item.del_flag = '0'
                      and item.old_warehouse_id = #{params.oldWarehouseId}
                )
            </if>
            <if test="params.newWarehouseId != null and params.newWarehouseId != ''">
                and exists (
                    select 1 from ams_transfer_order_item item
                    where item.order_id = ams_transfer_order.order_id
                      and item.del_flag = '0'
                      and item.new_warehouse_id = #{params.newWarehouseId}
                )
            </if>
        </where>
        order by create_time desc, order_id desc
    </select>

    <select id="selectAmsTransferOrderByOrderId" parameterType="Long"
            resultMap="AmsTransferOrderItemCollectionResult">
        <include refid="selectAmsTransferOrderVo"/>
        where order_id = #{orderId} and del_flag = '0'
    </select>

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

    <!-- 查询可调拨资产候选列表：仅筛选在库状态，通过 NOT EXISTS 排除已被其他有效调拨单占用的资产 -->
    <select id="selectAvailableTransferAssetList" resultMap="AvailableTransferAssetResult">
        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.use_dept_id,
               asset.use_dept_name, asset.use_user_id, asset.use_user_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_transfer_order_item item
              inner join ams_transfer_order transfer_order on transfer_order.order_id = item.order_id
                  and transfer_order.del_flag = '0'
                  and transfer_order.order_status in (#{draftStatus}, #{pendingStatus})
              where item.asset_id = asset.asset_id
                and item.del_flag = '0'
                <if test="currentOrderId != null">
                    and transfer_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>
        <if test="asset.assetStatus != null and asset.assetStatus != ''">
            and asset.asset_status = #{asset.assetStatus}
        </if>
        order by asset.asset_id
    </select>

    <!-- 保存草稿时防重复占用校验：统计同一资产在其他有效调拨单（草稿+待确认）中的引用次数 -->
    <select id="countOtherActiveTransferOrderByAssetId" resultType="int">
        select count(1)
        from ams_transfer_order_item item
        inner join ams_transfer_order transfer_order on transfer_order.order_id = item.order_id
            and transfer_order.del_flag = '0'
            and transfer_order.order_status in (#{draftStatus}, #{pendingStatus})
        where item.asset_id = #{assetId}
          and item.del_flag = '0'
          <if test="currentOrderId != null">
              and transfer_order.order_id != #{currentOrderId}
          </if>
    </select>

    <!-- 查询调拨单明细，LEFT JOIN ams_asset 实时取资产当前状态而非冒余存储 -->
    <select id="selectAmsTransferOrderItemList" resultMap="AmsTransferOrderItemResult">
        select item.item_id, item.order_id, item.transfer_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.old_dept_id,
               item.old_dept_name, item.new_dept_id, item.new_dept_name, item.old_user_id,
               item.old_user_name, item.new_user_id, item.new_user_name, item.old_warehouse_id,
               item.old_warehouse_code, item.old_warehouse_name, item.new_warehouse_id,
               item.new_warehouse_code, item.new_warehouse_name, item.old_location_id,
               item.old_location_code, item.old_location_name, item.new_location_id,
               item.new_location_code, item.new_location_name, item.create_by, item.create_time,
               item.update_by, item.update_time, item.remark, item.del_flag
        from ams_transfer_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="insertAmsTransferOrder" parameterType="AmsTransferOrder"
            useGeneratedKeys="true" keyProperty="orderId">
        insert into ams_transfer_order (
            transfer_no, applicant_id, applicant_name, transfer_reason, order_status,
            create_by, create_time, remark, del_flag
        ) values (
            #{transferNo}, #{applicantId}, #{applicantName}, #{transferReason}, #{orderStatus},
            #{createBy}, #{createTime}, #{remark}, #{delFlag}
        )
    </insert>

    <update id="updateAmsTransferOrder" parameterType="AmsTransferOrder">
        update ams_transfer_order
        set transfer_reason = #{transferReason},
            update_by = #{updateBy},
            update_time = #{updateTime},
            remark = #{remark}
        where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <!-- 提交调拨单：DRAFT → PENDING_CONFIRM，通过 WHERE order_status='DRAFT' 保证幂等性 -->
    <update id="submitAmsTransferOrder" parameterType="AmsTransferOrder">
        update ams_transfer_order
        set order_status = #{orderStatus},
            update_by = #{updateBy},
            update_time = #{updateTime}
        where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <!-- 确认调拨单：PENDING_CONFIRM → TRANSFERRED，写入确认人信息 -->
    <update id="confirmAmsTransferOrder" parameterType="AmsTransferOrder">
        update ams_transfer_order
        set order_status = #{orderStatus},
            confirm_user_id = #{confirmUserId},
            confirm_user_name = #{confirmUserName},
            confirm_time = #{confirmTime},
            update_by = #{updateBy},
            update_time = #{updateTime}
        where order_id = #{orderId} and del_flag = '0' and order_status = 'PENDING_CONFIRM'
    </update>

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

    <update id="deleteAmsTransferOrderByOrderIds" parameterType="String">
        update ams_transfer_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="deleteAmsTransferOrderItemByOrderIds" parameterType="String">
        update ams_transfer_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="deleteAmsTransferOrderItemByOrderId" parameterType="Long">
        update ams_transfer_order_item
        set del_flag = '1'
        where order_id = #{orderId} and del_flag = '0'
    </update>

    <insert id="batchAmsTransferOrderItem">
        insert into ams_transfer_order_item (
            order_id, transfer_no, asset_id, asset_code, asset_name, category_id, category_code,
            category_name, spec_model, brand, old_dept_id, old_dept_name, new_dept_id,
            new_dept_name, old_user_id, old_user_name, new_user_id, new_user_name,
            old_warehouse_id, old_warehouse_code, old_warehouse_name, new_warehouse_id,
            new_warehouse_code, new_warehouse_name, old_location_id, old_location_code,
            old_location_name, new_location_id, new_location_code, new_location_name,
            create_by, create_time, remark, del_flag
        ) values
        <foreach item="item" collection="list" separator=",">
            (
                #{item.orderId}, #{item.transferNo}, #{item.assetId}, #{item.assetCode},
                #{item.assetName}, #{item.categoryId}, #{item.categoryCode}, #{item.categoryName},
                #{item.specModel}, #{item.brand}, #{item.oldDeptId}, #{item.oldDeptName},
                #{item.newDeptId}, #{item.newDeptName}, #{item.oldUserId}, #{item.oldUserName},
                #{item.newUserId}, #{item.newUserName}, #{item.oldWarehouseId},
                #{item.oldWarehouseCode}, #{item.oldWarehouseName}, #{item.newWarehouseId},
                #{item.newWarehouseCode}, #{item.newWarehouseName}, #{item.oldLocationId},
                #{item.oldLocationCode}, #{item.oldLocationName}, #{item.newLocationId},
                #{item.newLocationCode}, #{item.newLocationName}, #{item.createBy},
                #{item.createTime}, #{item.remark}, #{item.delFlag}
            )
        </foreach>
    </insert>

</mapper>
