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

    <resultMap type="AmsBorrowOrder" id="AmsBorrowOrderResult">
        <result property="orderId"    column="order_id"    />
        <result property="borrowNo"    column="borrow_no"    />
        <result property="borrowUserId"    column="borrow_user_id"    />
        <result property="borrowUserName"    column="borrow_user_name"    />
        <result property="borrowDeptId"    column="borrow_dept_id"    />
        <result property="borrowDeptName"    column="borrow_dept_name"    />
        <result property="expectedReturnDate"    column="expected_return_date"    />
        <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="AmsBorrowOrderAmsBorrowOrderItemResult" type="AmsBorrowOrder" extends="AmsBorrowOrderResult">
        <collection property="amsBorrowOrderItemList" ofType="AmsBorrowOrderItem" column="order_id" select="selectAmsBorrowOrderItemList" />
    </resultMap>

    <resultMap type="AmsBorrowOrderItem" id="AmsBorrowOrderItemResult">
        <result property="itemId"    column="item_id"    />
        <result property="orderId"    column="order_id"    />
        <result property="borrowNo"    column="borrow_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="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="returnWarehouseId"    column="return_warehouse_id"    />
        <result property="returnWarehouseCode"    column="return_warehouse_code"    />
        <result property="returnWarehouseName"    column="return_warehouse_name"    />
        <result property="returnLocationId"    column="return_location_id"    />
        <result property="returnLocationCode"    column="return_location_code"    />
        <result property="returnLocationName"    column="return_location_name"    />
        <result property="actualReturnDate"    column="actual_return_date"    />
        <result property="returnStatus"    column="return_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 type="AmsAsset" id="AvailableBorrowAssetResult">
        <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="selectAmsBorrowOrderVo">
        select order_id, borrow_no, borrow_user_id, borrow_user_name, borrow_dept_id, borrow_dept_name, expected_return_date, 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_borrow_order
    </sql>

    <select id="selectAmsBorrowOrderList" parameterType="AmsBorrowOrder" resultMap="AmsBorrowOrderResult">
        <include refid="selectAmsBorrowOrderVo"/>
        <where>
            del_flag = '0'
            <if test="borrowNo != null  and borrowNo != ''"> and borrow_no like concat(#{borrowNo}, '%')</if>
            <if test="borrowUserId != null "> and borrow_user_id = #{borrowUserId}</if>
            <if test="borrowUserName != null  and borrowUserName != ''"> and borrow_user_name like concat('%', #{borrowUserName}, '%')</if>
            <if test="borrowDeptId != null "> and borrow_dept_id = #{borrowDeptId}</if>
            <if test="borrowDeptName != null  and borrowDeptName != ''"> and borrow_dept_name like concat('%', #{borrowDeptName}, '%')</if>
            <if test="expectedReturnDate != null "> and expected_return_date = #{expectedReturnDate}</if>
            <if test="confirmUserId != null "> and confirm_user_id = #{confirmUserId}</if>
            <if test="confirmUserName != null  and confirmUserName != ''"> and confirm_user_name like concat('%', #{confirmUserName}, '%')</if>
            <if test="confirmTime != null "> and confirm_time = #{confirmTime}</if>
            <if test="rejectReason != null  and rejectReason != ''"> and reject_reason = #{rejectReason}</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_borrow_order_item item
                    where item.order_id = ams_borrow_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="selectAmsBorrowOrderByOrderId" parameterType="Long" resultMap="AmsBorrowOrderAmsBorrowOrderItemResult">
        <include refid="selectAmsBorrowOrderVo"/>
        where order_id = #{orderId} and del_flag = '0'
    </select>

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

    <select id="selectAmsBorrowOrderItemList" resultMap="AmsBorrowOrderItemResult">
        select item_id, order_id, borrow_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, return_warehouse_id, return_warehouse_code, return_warehouse_name, return_location_id, return_location_code, return_location_name, actual_return_date, return_status, create_by, create_time, update_by, update_time, remark, del_flag
        from ams_borrow_order_item
        where order_id = #{order_id} and del_flag = '0'
        order by item_id
    </select>

    <select id="selectAmsBorrowOrderItemByOrderIdAndItemIdForUpdate" resultMap="AmsBorrowOrderItemResult">
        select item_id, order_id, borrow_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, return_warehouse_id, return_warehouse_code, return_warehouse_name, return_location_id, return_location_code, return_location_name, actual_return_date, return_status, create_by, create_time, update_by, update_time, remark, del_flag
        from ams_borrow_order_item
        where order_id = #{orderId}
          and item_id = #{itemId}
          and del_flag = '0'
        for update
    </select>

    <select id="selectAvailableBorrowAssetList" resultMap="AvailableBorrowAssetResult">
        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_borrow_order_item item
              inner join ams_borrow_order borrow_order on borrow_order.order_id = item.order_id
                  and borrow_order.del_flag = '0'
                  and borrow_order.order_status in (#{draftStatus}, #{pendingStatus})
              where item.asset_id = asset.asset_id
                and item.del_flag = '0'
                <if test="currentOrderId != null">
                    and borrow_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="countOtherActiveBorrowOrderByAssetId" resultType="int">
        select count(1)
        from ams_borrow_order_item item
        inner join ams_borrow_order borrow_order on borrow_order.order_id = item.order_id
            and borrow_order.del_flag = '0'
            and borrow_order.order_status in (#{draftStatus}, #{pendingStatus})
        where item.asset_id = #{assetId}
          and item.del_flag = '0'
          <if test="currentOrderId != null">
              and borrow_order.order_id != #{currentOrderId}
          </if>
    </select>

    <insert id="insertAmsBorrowOrder" parameterType="AmsBorrowOrder" useGeneratedKeys="true" keyProperty="orderId">
        insert into ams_borrow_order
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="borrowNo != null and borrowNo != ''">borrow_no,</if>
            <if test="borrowUserId != null">borrow_user_id,</if>
            <if test="borrowUserName != null">borrow_user_name,</if>
            <if test="borrowDeptId != null">borrow_dept_id,</if>
            <if test="borrowDeptName != null">borrow_dept_name,</if>
            <if test="expectedReturnDate != null">expected_return_date,</if>
            <if test="confirmUserId != null">confirm_user_id,</if>
            <if test="confirmUserName != null">confirm_user_name,</if>
            <if test="confirmTime != null">confirm_time,</if>
            <if test="rejectReason != null">reject_reason,</if>
            <if test="orderStatus != null and orderStatus != ''">order_status,</if>
            <if test="createBy != null">create_by,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateBy != null">update_by,</if>
            <if test="updateTime != null">update_time,</if>
            <if test="remark != null">remark,</if>
            <if test="delFlag != null and delFlag != ''">del_flag,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="borrowNo != null and borrowNo != ''">#{borrowNo},</if>
            <if test="borrowUserId != null">#{borrowUserId},</if>
            <if test="borrowUserName != null">#{borrowUserName},</if>
            <if test="borrowDeptId != null">#{borrowDeptId},</if>
            <if test="borrowDeptName != null">#{borrowDeptName},</if>
            <if test="expectedReturnDate != null">#{expectedReturnDate},</if>
            <if test="confirmUserId != null">#{confirmUserId},</if>
            <if test="confirmUserName != null">#{confirmUserName},</if>
            <if test="confirmTime != null">#{confirmTime},</if>
            <if test="rejectReason != null">#{rejectReason},</if>
            <if test="orderStatus != null and orderStatus != ''">#{orderStatus},</if>
            <if test="createBy != null">#{createBy},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateBy != null">#{updateBy},</if>
            <if test="updateTime != null">#{updateTime},</if>
            <if test="remark != null">#{remark},</if>
            <if test="delFlag != null and delFlag != ''">#{delFlag},</if>
         </trim>
    </insert>

    <update id="updateAmsBorrowOrder" parameterType="AmsBorrowOrder">
        update ams_borrow_order
        <trim prefix="SET" suffixOverrides=",">
            <if test="borrowNo != null and borrowNo != ''">borrow_no = #{borrowNo},</if>
            <if test="borrowUserId != null">borrow_user_id = #{borrowUserId},</if>
            <if test="borrowUserName != null">borrow_user_name = #{borrowUserName},</if>
            <if test="borrowDeptId != null">borrow_dept_id = #{borrowDeptId},</if>
            <if test="borrowDeptName != null">borrow_dept_name = #{borrowDeptName},</if>
            <if test="expectedReturnDate != null">expected_return_date = #{expectedReturnDate},</if>
            <if test="confirmUserId != null">confirm_user_id = #{confirmUserId},</if>
            <if test="confirmUserName != null">confirm_user_name = #{confirmUserName},</if>
            <if test="confirmTime != null">confirm_time = #{confirmTime},</if>
            <if test="rejectReason != null">reject_reason = #{rejectReason},</if>
            <if test="orderStatus != null and orderStatus != ''">order_status = #{orderStatus},</if>
            <if test="createBy != null">create_by = #{createBy},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="updateBy != null">update_by = #{updateBy},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="remark != null">remark = #{remark},</if>
            <if test="delFlag != null and delFlag != ''">del_flag = #{delFlag},</if>
        </trim>
        where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <!-- 逻辑删除，仅限草稿单 -->
    <update id="deleteAmsBorrowOrderByOrderId" parameterType="Long">
        update ams_borrow_order set del_flag = '1' where order_id = #{orderId} and del_flag = '0' and order_status = 'DRAFT'
    </update>

    <update id="deleteAmsBorrowOrderByOrderIds" parameterType="String">
        update ams_borrow_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="deleteAmsBorrowOrderItemByOrderIds" parameterType="String">
        update ams_borrow_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="deleteAmsBorrowOrderItemByOrderId" parameterType="Long">
        update ams_borrow_order_item set del_flag = '1' where order_id = #{orderId} and del_flag = '0'
    </update>

    <insert id="batchAmsBorrowOrderItem">
        insert into ams_borrow_order_item(
            order_id, borrow_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, return_warehouse_id,
            return_warehouse_code, return_warehouse_name, return_location_id, return_location_code,
            return_location_name, actual_return_date, return_status, create_by, create_time,
            remark, del_flag
        ) values
        <foreach item="item" index="index" collection="list" separator=",">
            (
                #{item.orderId}, #{item.borrowNo}, #{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.returnWarehouseId}, #{item.returnWarehouseCode}, #{item.returnWarehouseName},
                #{item.returnLocationId}, #{item.returnLocationCode}, #{item.returnLocationName},
                #{item.actualReturnDate}, #{item.returnStatus}, #{item.createBy}, #{item.createTime},
                #{item.remark}, #{item.delFlag}
            )
        </foreach>
    </insert>

    <!-- 提交：仅限草稿状态 -->
    <update id="submitAmsBorrowOrder" parameterType="AmsBorrowOrder">
        update ams_borrow_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>

    <!-- 确认借出：仅期待确认状态 -->
    <update id="confirmAmsBorrowOrder" parameterType="AmsBorrowOrder">
        update ams_borrow_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>

    <!-- 驳回借用：仅期待确认状态 -->
    <update id="rejectAmsBorrowOrder" parameterType="AmsBorrowOrder">
        update ams_borrow_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="updateAmsBorrowOrderItemReturnStatus">
        update ams_borrow_order_item
        <trim prefix="SET" suffixOverrides=",">
            <if test="item.returnWarehouseId != null">return_warehouse_id = #{item.returnWarehouseId},</if>
            <if test="item.returnWarehouseCode != null">return_warehouse_code = #{item.returnWarehouseCode},</if>
            <if test="item.returnWarehouseName != null">return_warehouse_name = #{item.returnWarehouseName},</if>
            <if test="item.returnLocationId != null">return_location_id = #{item.returnLocationId},</if>
            <if test="item.returnLocationCode != null">return_location_code = #{item.returnLocationCode},</if>
            <if test="item.returnLocationName != null">return_location_name = #{item.returnLocationName},</if>
            <if test="item.actualReturnDate != null">actual_return_date = #{item.actualReturnDate},</if>
            <if test="item.returnStatus != null and item.returnStatus != ''">return_status = #{item.returnStatus},</if>
            <if test="item.updateBy != null">update_by = #{item.updateBy},</if>
            <if test="item.updateTime != null">update_time = #{item.updateTime},</if>
        </trim>
        where order_id = #{item.orderId}
          and item_id = #{item.itemId}
          and del_flag = '0'
          and return_status = #{expectedStatus}
    </update>

    <!-- 自定义修改主单状态 -->
    <update id="updateAmsBorrowOrderStatus">
        update ams_borrow_order
        set order_status = #{orderStatus},
            update_by = #{updateBy},
            update_time = #{updateTime}
        where order_id = #{orderId} and del_flag = '0'
    </update>

</mapper>
