<?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.bonus.material.settlement.mapper.SltAgreementInfoMapper">
    <resultMap type="com.bonus.material.settlement.domain.SltAgreementInfo" id="SltAgreementInfoResult">
        <result property="id"    column="id"    />
        <result property="agreementId"    column="agreement_id"    />
        <result property="typeId"    column="type_id"    />
        <result property="maId"    column="ma_id"    />
        <result property="num"    column="num"    />
        <result property="startTime"    column="start_time"    />
        <result property="endTime"    column="end_time"    />
        <result property="status"    column="status"    />
        <result property="leaseId"    column="lease_id"    />
        <result property="backId"    column="back_id"    />
        <result property="leasePrice"    column="lease_price"    />
        <result property="buyPrice"    column="buy_price"    />
        <result property="isSlt"    column="is_slt"    />
        <result property="sltTime"    column="slt_time"    />
        <result property="companyId"    column="company_id"    />
        <result property="leaseType"    column="lease_type"    />
        <result property="trimDay"    column="trim_day"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
    </resultMap>

    <!-- 区间费用计算查询 -->
    <resultMap type="com.bonus.material.settlement.domain.vo.PeriodCostResultVo" id="PeriodCostResultMap">
        <result property="agreementId" column="agreement_id"/>
        <result property="agreementCode" column="agreement_code"/>
        <result property="unitId" column="unit_id"/>
        <result property="unitName" column="unit_name"/>
        <result property="projectId" column="project_id"/>
        <result property="projectName" column="project_name"/>
        <result property="typeId" column="type_id"/>
        <result property="typeName" column="type_name"/>
        <result property="modelName" column="model_name"/>
        <result property="maId" column="ma_id"/>
        <result property="maCode" column="ma_code"/>
        <result property="num" column="num"/>
        <result property="leasePrice" column="lease_price"/>
        <result property="isSettled" column="is_settled"/>
        <result property="settlementTime" column="settlement_time"/>
        <result property="startTime" column="start_time"/>
        <result property="endTime" column="end_time"/>
        <result property="status" column="status"/>
        <result property="mtUnitName" column="mt_unit_name"/>
        <result property="remark" column="remark"/>
        <result property="comsumable" column="comsumable"/>
        <result property="buyPrice" column="buy_price"/>
        <result property="leaseDays" column="lease_day"/>
        <result property="markTime" column="mark_time"/>
        <result property="leaseCost" column="lease_cost"/>
    </resultMap>

    <sql id="selectSltAgreementInfoVo">
        select id, agreement_id, type_id, ma_id, num, start_time, end_time, status, lease_id, back_id, lease_price, buy_price, is_slt, slt_time, company_id, lease_type, trim_day, create_time, update_time from slt_agreement_info
    </sql>

    <select id="selectSltAgreementInfoList" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo" resultMap="SltAgreementInfoResult">
        <include refid="selectSltAgreementInfoVo"/>
        <where>
            <if test="agreementId != null "> and agreement_id = #{agreementId}</if>
            <if test="typeId != null "> and type_id = #{typeId}</if>
            <if test="maId != null "> and ma_id = #{maId}</if>
            <if test="num != null "> and num = #{num}</if>
            <if test="startTime != null "> and start_time = #{startTime}</if>
            <if test="endTime != null "> and end_time = #{endTime}</if>
            <if test="status != null  and status != ''"> and status = #{status}</if>
            <if test="leaseId != null "> and lease_id = #{leaseId}</if>
            <if test="backId != null "> and back_id = #{backId}</if>
            <if test="leasePrice != null "> and lease_price = #{leasePrice}</if>
            <if test="buyPrice != null "> and buy_price = #{buyPrice}</if>
            <if test="isSlt != null  and isSlt != ''"> and is_slt = #{isSlt}</if>
            <if test="sltTime != null "> and slt_time = #{sltTime}</if>
            <if test="companyId != null "> and company_id = #{companyId}</if>
            <if test="leaseType != null  and leaseType != ''"> and lease_type = #{leaseType}</if>
            <if test="trimDay != null "> and trim_day = #{trimDay}</if>
        </where>
    </select>

    <select id="selectSltAgreementInfoById" parameterType="Long" resultMap="SltAgreementInfoResult">
        <include refid="selectSltAgreementInfoVo"/>
        where id = #{id}
    </select>

    <insert id="insertSltAgreementInfo" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo" useGeneratedKeys="true" keyProperty="id">
        insert into slt_agreement_info
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="agreementId != null">agreement_id,</if>
            <if test="typeId != null">type_id,</if>
            <if test="maId != null">ma_id,</if>
            <if test="num != null">num,</if>
            <if test="startTime != null">start_time,</if>
            <if test="endTime != null">end_time,</if>
            <if test="status != null">status,</if>
            <if test="leaseId != null">lease_id,</if>
            <if test="backId != null">back_id,</if>
            <if test="leasePrice != null">lease_price,</if>
            <if test="buyPrice != null">buy_price,</if>
            <if test="isSlt != null">is_slt,</if>
            <if test="sltTime != null">slt_time,</if>
            <if test="companyId != null">company_id,</if>
            <if test="leaseType != null">lease_type,</if>
            <if test="trimDay != null">trim_day,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateTime != null">update_time,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="agreementId != null">#{agreementId},</if>
            <if test="typeId != null">#{typeId},</if>
            <if test="maId != null">#{maId},</if>
            <if test="num != null">#{num},</if>
            <if test="startTime != null">#{startTime},</if>
            <if test="endTime != null">#{endTime},</if>
            <if test="status != null">#{status},</if>
            <if test="leaseId != null">#{leaseId},</if>
            <if test="backId != null">#{backId},</if>
            <if test="leasePrice != null">#{leasePrice},</if>
            <if test="buyPrice != null">#{buyPrice},</if>
            <if test="isSlt != null">#{isSlt},</if>
            <if test="sltTime != null">#{sltTime},</if>
            <if test="companyId != null">#{companyId},</if>
            <if test="leaseType != null">#{leaseType},</if>
            <if test="trimDay != null">#{trimDay},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateTime != null">#{updateTime},</if>
         </trim>
    </insert>

    <update id="updateSltAgreementInfo" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo">
        update slt_agreement_info
        <trim prefix="SET" suffixOverrides=",">
            <if test="agreementId != null">agreement_id = #{agreementId},</if>
            <if test="typeId != null">type_id = #{typeId},</if>
            <if test="maId != null">ma_id = #{maId},</if>
            <if test="num != null">num = #{num},</if>
            <if test="startTime != null">start_time = #{startTime},</if>
            <if test="endTime != null">end_time = #{endTime},</if>
            <if test="status != null">status = #{status},</if>
            <if test="leaseId != null">lease_id = #{leaseId},</if>
            <if test="backId != null">back_id = #{backId},</if>
            <if test="leasePrice != null">lease_price = #{leasePrice},</if>
            <if test="buyPrice != null">buy_price = #{buyPrice},</if>
            <if test="isSlt != null">is_slt = #{isSlt},</if>
            <if test="sltTime != null">slt_time = #{sltTime},</if>
            <if test="companyId != null">company_id = #{companyId},</if>
            <if test="leaseType != null">lease_type = #{leaseType},</if>
            <if test="trimDay != null">trim_day = #{trimDay},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
        </trim>
        where id = #{id}
    </update>

    <delete id="deleteSltAgreementInfoById" parameterType="Long">
        delete from slt_agreement_info where id = #{id}
    </delete>

    <delete id="deleteSltAgreementInfoByIds" parameterType="String">
        delete from slt_agreement_info where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <delete id="deleteSltInfo">
        DELETE FROM slt_agreement_info
        WHERE
        lease_id = #{record.parentId}
        and type_id = #{record.typeId}
        <if test="record.maId != null">
            AND ma_id = #{record.maId}
        </if>
        <if test="record.publishTask != null and record.publishTask != ''">
            AND publish_task = #{record.publishTask}
        </if>
    </delete>

    <select id="getSltAgreementInfo" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            id AS id,
            agreement_id AS agreementId,
            type_id AS typeId,
            ma_id AS maId,
            num AS num,
            start_time AS startTime,
            end_time AS endTime,
            status AS status,
            lease_id AS leaseId,
            back_id AS backId,
            lease_price AS leasePrice,
            buy_price AS buyPrice,
            company_id AS companyId
        FROM
            slt_agreement_info
        WHERE
            lease_id = #{parentId}
          AND
            type_id = #{typeId}
          AND
            ma_id IS NULL
          AND
            status = '0'
          <if test="publishTask != null and publishTask != ''">
             AND publish_task = #{publishTask}
          </if>
          <if test="leaseUnitIsTeam">
              AND agreement_id = #{projectUnitAgreementId}
          </if>
          <if test="!leaseUnitIsTeam">
              AND agreement_id = #{agreementId}
          </if>
          AND
            DATE(start_time) = CURDATE();
    </select>

    <select id="getSltAgreementInfo4Project" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT bai.agreement_id as agreementId, bai.agreement_code as agreementCode, bai.is_slt as isSlt,
        bui.unit_id as unitId,bui.unit_name as unitName, bp.pro_id as projectId , bp.pro_name as projectName,
        saa.remark,bai.protocol,saa.cost as costs,
        case when (saa.id is null or saa.status = '0') then '0' when saa.status = '1' then '1' when saa.status = '2' then '2' when saa.status = '3' then '3' end as sltStatus
        FROM bm_agreement_info bai
        LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
        LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
        LEFT JOIN slt_agreement_apply saa on saa.agreement_id = bai.agreement_id
        where bai.status = '1' AND bui.type_id != '1731'
        <if test="unitIds != null and unitIds.size() > 0">
            and bui.unit_id in
            <foreach item="item" index="index" collection="unitIds" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        <if test="projectId != null  and projectId != ''">
            and bp.pro_id = #{projectId}
        </if>
        <if test="sltStatus != null">
            and bai.is_slt = #{sltStatus}
        </if>
        <if test="agreementCode != null">
            and bai.agreement_code like concat('%',#{agreementCode},'%')
        </if>
        GROUP BY bai.agreement_id
        ORDER BY bai.create_time desc
    </select>

    <select id="getSltExam" resultType="com.bonus.material.settlement.domain.SltAgreementApply">
        select saa.id,
            saa.code,
            GROUP_CONCAT(DISTINCT sar.agreement_id) as agreementId,
            GROUP_CONCAT(DISTINCT bui.unit_name) as unitName,
            GROUP_CONCAT(DISTINCT bp.pro_name) as projectName,
            saa.cost,
            saa.status
        from slt_agreement_apply saa
            left join slt_agreement_relation sar on saa.id = sar.apply_id
            LEFT JOIN bm_agreement_info bai on sar.agreement_id = bai.agreement_id
            LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
            LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
        where 1=1
        <if test="unitId != null  and unitId != ''">
            and bui.unit_id = #{unitId}
        </if>
        <if test="projectId != null  and projectId != ''">
            and bp.pro_id = #{projectId}
        </if>
        <if test="sltStatus != null  and sltStatus != ''">
            and saa.status = #{sltStatus}
        </if>
        GROUP BY saa.id
    </select>

    <update id="updSltInfo">
        update slt_agreement_info
        set num = #{num},
            update_time = now()
        where id = #{id}
    </update>

    <insert id="insSltInfo">
        insert into slt_agreement_info (agreement_id,type_id,ma_id,num,return_num,start_time,status,lease_id,lease_price,buy_price,is_slt,company_id,lease_type,create_time,publish_task,source)
        values (#{agreementId},#{record.typeId},#{record.maId},#{record.outNum},#{record.returnNum},now(),0,#{record.parentId},#{ma.finalPrice},#{ma.buyPrice},'0',#{record.companyId},#{record.leaseType},now(),#{record.publishTask},#{record.source});
    </insert>

    <select id="getLeaseList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            res.agreementId,
            res.unitName,
            res.projectName,
            res.companyId,
            res.typeId,
            res.typeName,
            res.modelName,
            res.mtUnitName,
            res.leasePrice,
            SUM(res.num) as num,
            res.startTime,
            res.endTime,
            res.leaseDays
        FROM
            (
                select sai.id,
                       sai.agreement_id as agreementId,
                       bui.unit_name as unitName,
                       bp.pro_name as projectName,
                       sai.company_id as companyId,
                       sai.type_id as typeId,
                       sai.ma_id as maId,
                       mt1.type_name as typeName,
                       mt.type_name as modelName,
                       mt.unit_name as mtUnitName,
                       sai.lease_price as leasePrice,
                       sai.num as num,
                        DATE(sai.start_time) as startTime,
                        DATE(sai.end_time) as endTime,
                        DATEDIFF(IF(sai.end_time is null,CURDATE(),sai.end_time), sai.start_time) + 1 as leaseDays
                from slt_agreement_info sai
                    LEFT JOIN bm_agreement_info bai on sai.agreement_id = bai.agreement_id
                    LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
                    LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
                    left join ma_type mt on sai.type_id = mt.type_id
                    left join ma_type mt1 on mt.parent_id = mt1.type_id
                where
                    sai.agreement_id = #{agreementId}
                    <if test="settlementType != null and settlementType != 0">
                        and mt.jiju_type = #{settlementType}
                    </if>
            ) res
        GROUP BY res.typeId,res.startTime,res.endTime
    </select>

    <select id="getRepairDetailsList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        select tta.agreement_id as agreementId,
            bui.unit_name as unitName,
            bp.pro_name as projectName,
            rc.id as costId,
            rc.type_id as typeId,
            rc.ma_id as maId,
            mt1.type_name as typeName,
            mt.type_name as modelName,
            mt.unit_name as mtUnitName,
            rc.repair_num as num,
            rc.costs as costs,
            case rc.part_type when '0' then '不收费' when '1' then '收费' else '' end as partType,
            case rc.repair_type when '1' then '内部维修' when '2' then '返厂维修' else '' end as repairType,
            rc.company_id as companyId,
            case rc.status when '0' then '未审核' when '1' then '已审核' when '2' then '已驳回' else '' end as repairStatus
        from repair_cost rc
            LEFT JOIN tm_task_agreement tta on rc.task_id = tta.task_id
            LEFT JOIN tm_task tt on rc.task_id = tt.task_id
            LEFT JOIN bm_agreement_info bai on tta.agreement_id = bai.agreement_id
            LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
            LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
            left join ma_type mt on rc.type_id = mt.type_id
            left join ma_type mt1 on mt.parent_id = mt1.type_id
        where rc.status in ('0','1') and rc.repair_type in ('1','2')
        <if test="info.settlementType != null and info.settlementType != 0">
            and mt.jiju_type = #{info.settlementType}
        </if>
        <if test="taskList != null and taskList.size() > 0">
            and rc.task_id in
            <foreach item="task" collection="taskList" open="(" separator="," close=")">
                #{task.taskId}
            </foreach>
        </if>
    </select>

    <select id="getScrapDetailsList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        select tta.agreement_id as agreementId,
        bui.unit_name as unitName,
        bp.pro_name as projectName,
        rc.id as costId,
        rc.type_id as typeId,
        rc.ma_id as maId,
        mt1.type_name as typeName,
        mt.type_name as modelName,
        mt.unit_name as mtUnitName,
        rc.repair_num as num,
        rc.costs as costs,
        case rc.part_type when '0' then '不收费' when '1' then '收费' else '' end as partType,
        case rc.repair_type when '1' then '内部维修' when '2' then '返厂维修' else '' end as repairType,
        rc.company_id as companyId,
        case rc.status when '0' then '未审核' when '1' then '已审核' when '2' then '已驳回' else '' end as repairStatus
        from repair_cost rc
        LEFT JOIN tm_task_agreement tta on rc.task_id = tta.task_id
        LEFT JOIN tm_task tt on rc.task_id = tt.task_id
        LEFT JOIN bm_agreement_info bai on tta.agreement_id = bai.agreement_id
        LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
        LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
        left join ma_type mt on rc.type_id = mt.type_id
        left join ma_type mt1 on mt.parent_id = mt1.type_id
        where rc.status in ('0','1') and rc.repair_type = '3'
        <if test="info.settlementType != null and info.settlementType != 0">
            and mt.jiju_type = #{info.settlementType}
        </if>
        <if test="taskList != null and taskList.size() > 0">
            and rc.task_id in
            <foreach item="task" collection="taskList" open="(" separator="," close=")">
                #{task.taskId}
            </foreach>
        </if>
    </select>

    <select id="getLoseList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            res.agreementId,
            res.unitName,
            res.projectName,
            res.companyId,
            res.typeId,
            res.typeName,
            res.modelName,
            res.mtUnitName,
            res.buyPrice,
            SUM(res.num) as num,
            res.startTime,
            res.endTime,
            res.leaseDays
        FROM
            (
                select sai.id,
                       sai.agreement_id as agreementId,
                       bui.unit_name as unitName,
                       bp.pro_name as projectName,
                       sai.company_id as companyId,
                       sai.type_id as typeId,
                       sai.ma_id as maId,
                       mt1.type_name as typeName,
                       mt.type_name as modelName,
                       mt.unit_name as mtUnitName,
                       mt.buy_price as buyPrice,
                       sai.num as num,
                       sai.start_time as startTime,
                       sai.end_time as endTime,
                       DATEDIFF(sai.end_time, sai.start_time) + 1 as leaseDays
                from slt_agreement_info sai
                     LEFT JOIN bm_agreement_info bai on sai.agreement_id = bai.agreement_id
                     LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
                     LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
                     left join ma_type mt on sai.type_id = mt.type_id
                     left join ma_type mt1 on mt.parent_id = mt1.type_id
                where sai.agreement_id = #{agreementId} and sai.end_time is null
                <if test="settlementType != null and settlementType != 0">
                    and mt.jiju_type = #{settlementType}
                </if>
            ) res
        GROUP BY res.typeId
    </select>

    <select id="getCost" resultType="java.lang.String">
        select cost
        from slt_agreement_apply
        where id = #{id}
    </select>

    <select id="getRelations" resultType="com.bonus.material.settlement.domain.SltAgreementRelation">
        select sar.id,
               bui.unit_name as unitName,
               bp.pro_name as projectName,
               sar.apply_id as applyId,
               sar.agreement_id as agreementId,
               sar.add_cost as addCost,
               sar.sub_cost as subCost,
               sar.remark as remark,
               sar.cost as cost,
               0 as leaseCost,
               sar.repair_cost as repairCost,
               sar.scrap_cost as scrapCost,
               sar.lose_cost as loseCost
        from slt_agreement_relation sar
                 LEFT JOIN bm_agreement_info bai on sar.agreement_id = bai.agreement_id
                 LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
                 LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
        where sar.apply_id = #{id}
    </select>

    <update id="updateRelation">
        update slt_agreement_relation
        set status = #{status}
        where apply_id = #{id}
    </update>

    <update id="updateApply">
        update slt_agreement_apply
        set status = #{status},
            auditor = #{auditor},
            audit_time = now(),
            remark = #{remark}
        where id = #{id}
    </update>

    <update id="updateMaStatus">
        update ma_machine
        set ma_status =#{status}
        where ma_id = #{maId}
    </update>

    <update id="backRejectSltCope">
        update
            slt_agreement_info sai
        join
            back_apply_info bai on sai.back_id = bai.id
        set
            sai.end_time = null, sai.back_id = null, sai.status = '0', sai.update_time = CURRENT_TIMESTAMP
        where
            bai.task_id = #{backTaskId} and sai.status = '1'
    </update>

    <select id="getRejectCount" resultType="int">
        select
        count(id)
        from slt_agreement_apply saa
        where saa.agreement_id = #{agreementId} and saa.status = '3' and saa.settlement_type = #{settlementType}
    </select>

    <select id="getBeforeSettlementCount" resultType="int">
        select
            count(id)
        from slt_agreement_apply saa
        where saa.agreement_id = #{agreementId} and (saa.status = '1' or saa.status = '2')
    </select>

    <insert id="insertSltAgreementApply" parameterType="com.bonus.material.settlement.domain.vo.SltInfoVo" useGeneratedKeys="true" keyProperty="id">
        insert into slt_agreement_apply
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="agreementId != null">agreement_id,</if>
            <if test="agreementCode != null">`code`,</if>
            <if test="settlementType != null">settlement_type,</if>
            <if test="createBy != null">creator,</if>
            <if test="createTime != null">create_time,</if>
            status,
            <if test="totalCostAll != null">cost,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="agreementId != null">#{agreementId},</if>
            <if test="agreementCode != null">#{agreementCode},</if>
            <if test="settlementType != null">#{settlementType,jdbcType=TINYINT},</if>
            <if test="createBy != null">#{createBy},</if>
            <if test="createTime != null">#{createTime},</if>
            1,
            <if test="totalCostAll != null">#{totalCostAll},</if>
        </trim>
    </insert>

    <update id="updateBmAgreementStatus">
        update
            bm_agreement_info bai
        left join
            ma_type mt on bai.type_id = mt.type_id
        set
            bai.is_slt = 1, bai.update_by = #{createBy}, bai.update_time = #{updateTime}
        where
            bai.agreement_id = #{agreementId}
            and mt.jiju_type = #{settlementType}
    </update>

    <!-- 循环插入lease -->
    <insert id="insertSltAgreementDetailLease" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo">
        insert into slt_agreement_details (apply_id, type_id,ma_id,slt_type,num,start_time,end_time,price,money)
        values
        <foreach collection="list" item="item" separator=",">
            (#{id}, #{item.typeId}, #{item.maId},1,#{item.num},#{item.startTime},#{item.endTime},#{item.leasePrice},#{item.costs})
        </foreach>
    </insert>

    <!-- 循环插入repair -->
    <insert id="insertSltAgreementDetailRepair" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo">
        insert into slt_agreement_details (apply_id, type_id,ma_id,slt_type,num,money,is_charge)
        values
        <foreach collection="list" item="item" separator=",">
            (#{id}, #{item.typeId}, #{item.maId},3,#{item.num},#{item.costs},
            <choose>
                <when test="item.partType == '收费'">1</when>
                <otherwise>0</otherwise>
            </choose>)
        </foreach>
    </insert>

    <!-- 循环插入scrap -->
    <insert id="insertSltAgreementDetailScrap" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo">
        insert into slt_agreement_details (apply_id, type_id,ma_id,slt_type,num,money,is_charge)
        values
        <foreach collection="list" item="item" separator=",">
            (#{id}, #{item.typeId}, #{item.maId},4,#{item.num},#{item.costs},
            <choose>
                <when test="item.partType == '收费'">1</when>
                <otherwise>0</otherwise>
            </choose>)
        </foreach>
    </insert>

    <!-- 循环插入lose -->
    <insert id="insertSltAgreementDetailLose" parameterType="com.bonus.material.settlement.domain.SltAgreementInfo">
        insert into slt_agreement_details (apply_id, type_id,ma_id,slt_type,num,money)
        values
        <foreach collection="list" item="item" separator=",">
            (#{id}, #{item.typeId}, #{item.maId},2,#{item.num},#{item.costs})
        </foreach>
    </insert>

    <select id="getSltList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            saa.id as id, bai.agreement_id as agreementId, bai.agreement_code as agreementCode, saa.settlement_type as settlementType,
            bui.unit_id as unitId,bui.unit_name as unitName, bp.pro_id as projectId , bp.pro_name as projectName,
            saa.remark,bai.protocol,saa.cost as costs,su.nick_name as auditor,saa.audit_time as auditTime,
            case when  saa.status = '1' then '1' when saa.status = '2' then '2' when saa.status = '3' then '3' end as sltStatus
        FROM bm_agreement_info bai
        LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
        LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
        LEFT JOIN slt_agreement_apply saa on saa.agreement_id = bai.agreement_id
        LEFT JOIN sys_user su ON saa.auditor = su.user_id and su.del_flag = 0
        where bai.status = '1' and saa.status in ('1','2','3')
        <if test="unitId != null  and unitId != ''">
            and bui.unit_id = #{unitId}
        </if>
        <if test="projectId != null  and projectId != ''">
            and bp.pro_id = #{projectId}
        </if>
        <choose>
            <when test="sltStatus == '1'.toString()">
                and saa.status = '1'
            </when>
            <when test="sltStatus == '2'.toString()">
                and saa.status = '2'
            </when>
            <when test="sltStatus == '3'.toString()">
                and saa.status = '3'
            </when>
        </choose>
        ORDER BY bai.create_time desc
    </select>

    <select id="getRejectId" resultType="Long">
        select
        id
        from slt_agreement_apply saa
        where saa.agreement_id = #{agreementId}
    </select>

    <update id="updateRejectCount">
        update slt_agreement_apply
        set status = '1',
            update_time = now(),
            audit_Time = null,
            auditor = null,
            remark = null,
            cost = #{totalCostAll}
        where agreement_id = #{agreementId} and settlement_type = #{settlementType}
    </update>

    <update id="costExame">
        update slt_agreement_apply
        <set>
            <if test="status != null and status!=''">status = #{status},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="auditTime != null">audit_time = #{auditTime},</if>
            <if test="auditor != null and auditor!=''">auditor = #{auditor},</if>
            <if test="remark != null and remark!=''">remark = #{remark}</if>
        </set>
        where id = #{id}
    </update>

    <delete id="costDeleteDetail">
        delete from slt_agreement_details where apply_id = #{id}
    </delete>

    <update id="updateBmAgreementReject">
        update
            bm_agreement_info bai
        set
            bai.is_slt = #{isSlt}, bai.update_by = #{auditor}, bai.update_time = #{auditTime}
        where
            bai.agreement_id = #{agreementId}
    </update>

    <update id="backInUseNum">
        update
        slt_agreement_info sai
        join
        back_apply_info bai on sai.back_id = bai.id
        set
        sai.end_time = null, sai.back_id = null, sai.status = '0', sai.update_time = CURRENT_TIMESTAMP
        where
        bai.task_id = #{preTaskId} and sai.status = '1'
        <if test="typeId != null">
            and sai.type_id = #{typeId}
        </if>
        <if test="maId != null">
            and sai.ma_id = #{maId}
        </if>
    </update>

    <select id="getProjectListByUnitIds" resultType="int">
        /*根据往来单位id关联协议查询工程*/
        SELECT
        bmp.pro_id AS id
        FROM
        bm_project bmp
        LEFT JOIN sys_dept sd ON sd.dept_id = bmp.imp_unit
        LEFT JOIN bm_agreement_info bai ON bai.project_id = bmp.pro_id
        AND bai.`status` = '1'
        LEFT JOIN bm_unit bu ON bu.unit_id = bai.unit_id
        AND bu.del_flag = '0'
        WHERE
        sd.del_flag = '0'
        AND sd.`status` = '0'
        AND bmp.del_flag = '0'
        <if test="unitId != null">
            AND bu.unit_id = #{unitId}
        </if>
    </select>


    <select id="getProjectList" resultType="com.bonus.common.biz.domain.ProjectTreeNode">
        /*根据往来单位id关联协议查询工程*/
        SELECT
        *
        FROM
        (
        SELECT
        bmp.pro_id AS id,
        bmp.pro_name AS name,
        concat( 'gs', bmp.imp_unit ) AS parentId,
        2 AS level
        FROM
        bm_project bmp
        LEFT JOIN sys_dept sd ON sd.dept_id = bmp.imp_unit
        LEFT JOIN bm_agreement_info bai ON bai.project_id = bmp.pro_id
        AND bai.`status` = '1'
        LEFT JOIN bm_unit bu ON bu.unit_id = bai.unit_id
        AND bu.del_flag = '0'
        WHERE
        sd.del_flag = '0'
        AND sd.`status` = '0'
        AND bmp.del_flag = '0'
        <if test="projectId != null">
            AND bmp.pro_id = #{projectId}
        </if>
        UNION
        SELECT DISTINCT
        concat( 'gs', sd.dept_id ) AS id,
        sd.dept_name AS proName,
        '0' AS parentId,
        1 AS level
        FROM
        sys_dept sd
        LEFT JOIN bm_project bmp ON sd.dept_id = bmp.imp_unit
        LEFT JOIN bm_agreement_info bai ON bai.project_id = bmp.pro_id
        AND bai.`status` = '1'
        LEFT JOIN bm_unit bu ON bu.unit_id = bai.unit_id
        WHERE
        bmp.pro_id IS NOT NULL
        AND sd.del_flag = '0'
        AND sd.`status` = '0'
        AND bmp.del_flag = '0'
        <if test="projectId != null">
            AND bmp.pro_id = #{projectId}
        </if>
        ) a
        ORDER BY
        level
    </select>

    <select id="getAgreementInfoById" resultType="com.bonus.material.common.domain.vo.AgreementVo">
        SELECT agreement_id AS agreementId,
               agreement_code AS agreementCode,
               is_slt AS isSlt
        FROM bm_agreement_info
        WHERE
        unit_id IN
        <foreach item="item" index="index" collection="unitIds" open="(" separator="," close=")">
            #{item}
        </foreach>
        AND project_id = #{projectId} AND status = '1'
    </select>

    <select id="getSltAgreementInfoById" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            sai.agreement_id as agreementId
        FROM
            slt_agreement_info sai
                LEFT JOIN ma_type mt1 ON mt1.type_id = sai.type_id
                AND mt1.del_flag = '0'
                LEFT JOIN ma_type mt2 ON mt2.type_id = mt1.parent_id
                AND mt2.del_flag = '0'
                LEFT JOIN ma_type mt3 ON mt2.parent_id = mt3.type_id
                AND mt3.del_flag = '0'
                LEFT JOIN ma_type mt4 ON mt3.parent_id = mt4.type_id
                AND mt4.del_flag = '0'
                LEFT JOIN ma_type_manage mt ON mt4.type_id = mt.type_id
        WHERE
            mt.user_id = #{userId}
        GROUP BY 	sai.agreement_id
    </select>

    <select id="selectTheSettledCountByAgreementIdType" resultType="int">
        select
            count(1) from slt_agreement_apply saa
        where
            saa.agreement_id = #{agreementId}
            and saa.settlement_type = #{sltType}
            and (saa.status = '1' or saa.status = '2')
    </select>

    <select id="getSltReportedList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            saa.id as id, bai.agreement_id as agreementId, bai.agreement_code as agreementCode, saa.settlement_type as settlementType,
            bui.unit_id as unitId,bui.unit_name as unitName, bp.pro_id as projectId , bp.pro_name as projectName,
            saa.remark,saa.cost as costs,su.nick_name as auditor,saa.audit_time as auditTime,
            saa.create_time as createTime,
            SUM(IF(sad.slt_type = '1',sad.money,0)) AS leaseCost,
            SUM(IF(sad.slt_type = '2',sad.money,0)) AS loseCost,
            SUM(IF(sad.slt_type = '3' AND sad.is_charge = '1',sad.money,0)) AS repairCost,
            SUM(IF(sad.slt_type = '4' AND sad.is_charge = '1',sad.money,0)) AS scrapCost,
            case when  saa.status = '1' then '1' when saa.status = '2' then '2' when saa.status = '3' then '3' end as sltStatus
        FROM
            bm_agreement_info bai
            LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
            LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
            LEFT JOIN slt_agreement_apply saa on saa.agreement_id = bai.agreement_id
            <if test="settlementType != null">
                and saa.settlement_type = #{settlementType}
            </if>
            LEFT JOIN slt_agreement_details sad ON saa.id = sad.apply_id
            LEFT JOIN sys_user su ON saa.auditor = su.user_id and su.del_flag = 0
        where
            bai.status = '1' and saa.status in ('1','2','3')
            <if test="unitId != null  and unitId != ''">
                and bui.unit_id = #{unitId}
            </if>
            <if test="projectId != null  and projectId != ''">
                and bp.pro_id = #{projectId}
            </if>
            <if test="agreementCode != null  and agreementCode != ''">
                and bai.agreement_code = #{agreementCode}
            </if>
            <if test="startTime != null and endTime != null">
                and saa.create_time between #{startTime} and #{endTime}
            </if>
            <if test="agreementIds != null and agreementIds.size() > 0">
                and bai.agreement_id in
                <foreach item="item" index="index" collection="agreementIds" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>

            <if test="sltStatus != null">
                <choose>
                    <when test="sltStatus == '1'.toString()">
                        and saa.status = '1'
                    </when>
                    <when test="sltStatus == '2'.toString()">
                        and saa.status = '2'
                    </when>
                    <when test="sltStatus == '3'.toString()">
                        and saa.status = '3'
                    </when>
                </choose>
            </if>
        GROUP BY bai.agreement_id, saa.settlement_type
        ORDER BY saa.create_time desc
    </select>

    <select id="getSltReportList" resultMap="SltAgreementInfoResult">
        SELECT
            bai.agreement_id,
            bai.agreement_code as agreementCode,
            bai.is_slt as isSlt,
            bai.unit_id as unitId,
            bui.unit_name as unitName,
            bai.project_id as projectId,
            bp.pro_name as projectName,
            saa.remark,
            bai.protocol,
            saa.cost as costs,
            CASE
                WHEN saa.id IS NULL OR saa.status = '0' THEN '0'
                WHEN saa.status = '1' THEN '1'
                WHEN saa.status = '2' THEN '2'
                WHEN saa.status = '3' THEN '3'
                ELSE '0'
            END as sltStatus
        FROM bm_agreement_info bai
        INNER JOIN bm_unit bui ON bui.unit_id = bai.unit_id AND bui.type_id != '1731'
        LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
        LEFT JOIN slt_agreement_apply saa ON saa.agreement_id = bai.agreement_id AND (saa.status IS NULL OR saa.status != '2')
        WHERE bai.status = '1'
            AND (bai.is_slt = '0' OR bai.is_slt IS NULL)
            <if test="unitIds != null and unitIds.size() > 0">
                AND bai.unit_id IN
                <foreach item="item" index="index" collection="unitIds" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="projectId != null and projectId != ''">
                AND bai.project_id = #{projectId}
            </if>
            <if test="sltStatus != null and sltStatus != ''">
                AND bai.is_slt = #{sltStatus}
            </if>
            <if test="agreementCode != null and agreementCode != ''">
                AND bai.agreement_code LIKE CONCAT('%', #{agreementCode}, '%')
            </if>
            <if test="unitName != null and unitName != ''">
                AND bui.unit_name LIKE CONCAT('%', #{unitName}, '%')
            </if>
            <if test="projectName != null and projectName != ''">
                AND bp.pro_name LIKE CONCAT('%', #{projectName}, '%')
            </if>
        ORDER BY bai.create_time DESC
    </select>

    <select id="getLeaseListBatch" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            res.agreementId,
            res.unitName,
            res.projectName,
            res.companyId,
            res.typeId,
            res.typeName,
            res.modelName,
            res.mtUnitName,
            res.leasePrice,
            SUM(res.num) as num,
            res.startTime,
            res.endTime,
            res.leaseDays
        FROM
            (
            select sai.id,
                sai.agreement_id as agreementId,
                bui.unit_name as unitName,
                bp.pro_name as projectName,
                sai.company_id as companyId,
                sai.type_id as typeId,
                mt1.type_name as typeName,
                mt.type_name as modelName,
                mt.unit_name as mtUnitName,
                sai.lease_price as leasePrice,
                sai.num as num,
                DATE(sai.start_time) as startTime,
                DATE(sai.end_time) as endTime,
                DATEDIFF(IF(sai.end_time is null,CURDATE(),sai.end_time), sai.start_time) + 1 as leaseDays
            from
                slt_agreement_info sai
                LEFT JOIN bm_agreement_info bai on sai.agreement_id = bai.agreement_id
                LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
                LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
                left join ma_type mt on sai.type_id = mt.type_id
                left join ma_type mt1 on mt.parent_id = mt1.type_id
            <where>
                <if test="agreementIds != null and agreementIds.size > 0">
                    and sai.agreement_id in
                    <foreach collection="agreementIds" index="index" item="item" open="(" separator="," close=")">
                            #{item}
                    </foreach>
                </if>
                <if test="settlementType != null and settlementType != 0">
                    and mt.jiju_type = #{settlementType}
                </if>
            </where>
        ) res
        GROUP BY res.agreementId,res.typeId,res.startTime,res.endTime
    </select>

    <select id="getLoseListBatch" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        SELECT
            res.agreementId, res.unitName, res.projectName, res.companyId, res.typeId,
            res.typeName, res.modelName, res.mtUnitName, res.buyPrice, res.startTime, res.endTime, res.leaseDays,
            SUM(res.num) as num
        FROM
            (
            select sai.id,
                sai.agreement_id as agreementId,
                bui.unit_name as unitName,
                bp.pro_name as projectName,
                sai.company_id as companyId,
                sai.type_id as typeId,
                sai.ma_id as maId,
                mt1.type_name as typeName,
                mt.type_name as modelName,
                mt.unit_name as mtUnitName,
                mt.buy_price as buyPrice,
                sai.num as num,
                sai.start_time as startTime,
                sai.end_time as endTime,
                DATEDIFF(sai.end_time, sai.start_time) + 1 as leaseDays
            from
                slt_agreement_info sai
                LEFT JOIN bm_agreement_info bai on sai.agreement_id = bai.agreement_id
                LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
                LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
                left join ma_type mt on sai.type_id = mt.type_id
                left join ma_type mt1 on mt.parent_id = mt1.type_id
            where
                sai.agreement_id in
                <foreach item="item" index="index" collection="agreementIds" open="(" separator="," close=")">
                    #{item}
                </foreach>
                and sai.end_time is null
                <if test="settlementType != null and settlementType != 0">
                    and mt.jiju_type = #{settlementType}
                </if>
        ) res
        GROUP BY res.typeId, res.agreementId
    </select>

    <select id="getRepairDetailsListBatch" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        select
        tta.agreement_id as agreementId,
        bai.agreement_code as agreementCode,
        bui.unit_name as unitName,
        bp.pro_name as projectName,
        rc.id as costId,
        rc.type_id as typeId,
        rc.ma_id as maId,
        mt1.type_name as typeName,
        mt.type_name as modelName,
        mt.unit_name as mtUnitName,
        rc.repair_num as num,
        rc.costs as costs,
        case rc.part_type when '0' then '不收费' when '1' then '收费' else '' end as partType,
        case rc.repair_type when '1' then '内部维修' when '2' then '返厂维修' else '' end as repairType,
        rc.company_id as companyId,
        case rc.status when '0' then '未审核' when '1' then '已审核' when '2' then '已驳回' else '' end as repairStatus
        from repair_cost rc
        left join tm_task_agreement tta on rc.task_id = tta.task_id
        left join tm_task tt on rc.task_id = tt.task_id
        left join bm_agreement_info bai on tta.agreement_id = bai.agreement_id
        left join bm_project bp ON bp.pro_id = bai.project_id
        left join bm_unit bui ON bui.unit_id = bai.unit_id
        left join ma_type mt on rc.type_id = mt.type_id
        left join ma_type mt1 on mt.parent_id = mt1.type_id
        where rc.status in ('0','1')
        and rc.repair_type in ('1','2')
        <if test="info.settlementType != null and info.settlementType != 0">
            and mt.jiju_type = #{info.settlementType}
        </if>
        <if test="info.agreementIds != null and info.agreementIds.size > 0">
            and tta.agreement_id in
            <foreach item="aid" collection="info.agreementIds" open="(" separator="," close=")">
                #{aid}
            </foreach>
        </if>
    </select>

    <select id="getScrapDetailsListBatch" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        select
            tta.agreement_id as agreementId,
            bai.agreement_code as agreementCode,
            bui.unit_name as unitName,
            bp.pro_name as projectName,
            rc.id as costId,
            rc.type_id as typeId,
            rc.ma_id as maId,
            mt1.type_name as typeName,
            mt.type_name as modelName,
            mt.unit_name as mtUnitName,
            rc.repair_num as num,
            rc.costs as costs,
            case rc.part_type when '0' then '不收费' when '1' then '收费' else '' end as partType,
            case rc.repair_type when '1' then '内部维修' when '2' then '返厂维修' when '3' then '其他维修' else '' end as repairType,
            rc.company_id as companyId,
            case rc.status when '0' then '未审核' when '1' then '已审核' when '2' then '已驳回' else '' end as repairStatus
            from repair_cost rc
            LEFT JOIN tm_task_agreement tta on rc.task_id = tta.task_id
            LEFT JOIN tm_task tt on rc.task_id = tt.task_id
            LEFT JOIN bm_agreement_info bai on tta.agreement_id = bai.agreement_id
            LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
            LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
            LEFT JOIN ma_type mt on rc.type_id = mt.type_id
            LEFT JOIN ma_type mt1 on mt.parent_id = mt1.type_id
            where rc.status in ('0','1')
            and rc.repair_type = '3'
            <if test="info.settlementType != null and info.settlementType != 0">
                and mt.jiju_type = #{info.settlementType}
            </if>
            <if test="info.agreementIds != null and info.agreementIds.size > 0">
                and tta.agreement_id in
                <foreach item="aid" collection="info.agreementIds" open="(" separator="," close=")">
                    #{aid}
                </foreach>
            </if>
    </select>

    <select id="getLostReportList" resultType="com.bonus.material.settlement.domain.SltAgreementInfo">
        select sai.id,
               sai.agreement_id as agreementId,
                bai.agreement_code as agreementCode,
               bui.unit_name as unitName,
               bp.pro_name as projectName,
               sai.type_id as typeId,
               sai.ma_id as maId,
               mt1.type_name as typeName,
               mt.type_name as modelName,
               mt.unit_name as mtUnitName,
               mt.buy_price as buyPrice,
               sum(sai.num) as num
        from
            slt_agreement_info sai
            LEFT JOIN bm_agreement_info bai on sai.agreement_id = bai.agreement_id
            LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
            LEFT JOIN bm_unit bui ON bui.unit_id = bai.unit_id
            left join ma_type mt on sai.type_id = mt.type_id
            left join ma_type mt1 on mt.parent_id = mt1.type_id
        <where>
            <if test="settlementType != null and settlementType != 0">
                and mt.jiju_type = #{settlementType}
            </if>
            <if test="startTime != null and endTime != null">
                and sai.create_time between #{startTime} and #{endTime}
            </if>
            <if test="agreementCode != null and agreementCode != ''">
                and bai.agreement_code like concat('%',#{agreementCode},'%')
            </if>
        </where>
        GROUP BY
            sai.agreement_id,mt.type_id
    </select>


    <select id="selectLeasePeriodCostList" parameterType="com.bonus.material.settlement.domain.dto.PeriodCostQueryDto" resultMap="PeriodCostResultMap">
        SELECT
            bai.agreement_id, bai.agreement_code, bai.unit_id,
            bu.unit_name,
            bai.project_id,
            bp.pro_name as project_name,
            sai.type_id,
            mt.type_name as model_name, mt.buy_price,
            mt1.type_name as type_name,
            sai.ma_id, sai.num, sai.lease_price, sai.start_time, sai.end_time,
            bai.is_slt AS is_settled,
            sai.slt_time AS settlement_time, sai.status,
            mt.unit_name as mt_unit_name, mt.comsumable,
            bai.remark
        FROM bm_agreement_info bai
        INNER JOIN slt_agreement_info sai ON bai.agreement_id = sai.agreement_id
        LEFT JOIN bm_unit bu ON bai.unit_id = bu.unit_id
        LEFT JOIN bm_project bp ON bai.project_id = bp.pro_id
        LEFT JOIN ma_type mt ON sai.type_id = mt.type_id AND mt.`level` = '4'
        LEFT JOIN ma_type mt1 ON mt.parent_id = mt1.type_id AND mt1.`level` = '3'
        <where>
            bai.status = '1'
            AND mt.jiju_type = #{sltManageType}
            <if test="agreementCode != null and agreementCode != ''">
                AND bai.agreement_code LIKE concat('%',#{agreementCode},'%')
            </if>
            <if test="agreementId != null and agreementId > 0">
                AND bai.agreement_id = #{agreementId}
            </if>
            <if test="agreementIds != null and agreementIds.size() > 0">
                AND bai.agreement_id IN
                <foreach collection="agreementIds" item="agreementId" open="(" separator="," close=")">
                    #{agreementId}
                </foreach>
            </if>
            <if test="unitIds != null and unitIds.size() > 0">
                AND bai.unit_id IN
                <foreach collection="unitIds" item="unitId" open="(" separator="," close=")">
                    #{unitId}
                </foreach>
            </if>
            <if test="projectIds != null and projectIds.size() > 0">
                AND bai.project_id IN
                <foreach collection="projectIds" item="projectId" open="(" separator="," close=")">
                    #{projectId}
                </foreach>
            </if>
            <if test="typeIds != null and typeIds.size() > 0">
                AND sai.type_id IN
                <foreach collection="typeIds" item="typeId" open="(" separator="," close=")">
                    #{typeId}
                </foreach>
            </if>
            <if test="settlementStatus != null and settlementStatus != ''">
                AND bai.is_slt = #{settlementStatus}
            </if>
            <if test="unitName != null and unitName != ''">
                AND bu.unit_name LIKE CONCAT('%', #{unitName}, '%')
            </if>
            <if test="projectName != null and projectName != ''">
                AND bp.project_name LIKE CONCAT('%', #{projectName}, '%')
            </if>
            <if test="companyId != null">
                AND bai.company_id = #{companyId}
            </if>
            <!-- 数据库层面的时间范围过滤 - 修正跨区间租赁逻辑 -->
            AND (
                <!-- 已结算协议：租赁期间与查询区间有交集 -->
                (bai.is_slt = 1 AND (
                    <!-- 情况1：领料时间在查询区间内 -->
                    (sai.start_time IS NOT NULL AND DATE(sai.start_time) &gt;= #{startDate} AND DATE(sai.start_time) &lt;= #{endDate})
                    OR
                    <!-- 情况2：退料时间在查询区间内 -->
                    (sai.end_time IS NOT NULL AND DATE(sai.end_time) &gt;= #{startDate} AND DATE(sai.end_time) &lt;= #{endDate})
                    OR
                    <!-- 情况3：结算时间在查询区间内 -->
                    (sai.slt_time IS NOT NULL AND DATE(sai.slt_time) &gt;= #{startDate} AND DATE(sai.slt_time) &lt;= #{endDate})
                    OR
                    <!-- 情况4：跨区间租赁（领料在区间前，退料/结算在区间后） -->
                    (sai.start_time IS NOT NULL AND DATE(sai.start_time) &lt; #{startDate} AND
                     ((sai.end_time IS NOT NULL AND DATE(sai.end_time) &gt; #{endDate}) OR (sai.slt_time IS NOT NULL AND DATE(sai.slt_time) &gt; #{endDate})))
                ))
                OR
                <!-- 未结算协议：租赁期间与查询区间有交集 -->
                ((bai.is_slt = 0 OR bai.is_slt IS NULL) AND (
                    <!-- 情况1：领料时间在查询区间内 -->
                    (sai.start_time IS NOT NULL AND DATE(sai.start_time) &gt;= #{startDate} AND DATE(sai.start_time) &lt;= #{endDate})
                    OR
                    <!-- 情况2：退料时间在查询区间内 -->
                    (sai.end_time IS NOT NULL AND DATE(sai.end_time) &gt;= #{startDate} AND DATE(sai.end_time) &lt;= #{endDate})
                    OR
                    <!-- 情况3：跨区间租赁（领料在区间前，退料在区间后或未退料） -->
                    (sai.start_time IS NOT NULL AND DATE(sai.start_time) &lt; #{startDate} AND (sai.end_time IS NULL OR DATE(sai.end_time) &gt; #{endDate}))
                    OR
                    <!-- 情况4：设备状态为在用（未退料）且领料时间不晚于查询结束时间 -->
                    (sai.status = '0' AND sai.start_time IS NOT NULL AND DATE(sai.start_time) &lt;= #{endDate})
                ))
            )
        </where>
        ORDER BY bai.agreement_code, sai.type_id, sai.ma_id
    </select>

    <select id="getSltReportListCount" resultType="int">
        SELECT
            count(*)
        FROM bm_agreement_info bai
        INNER JOIN bm_unit bui ON bui.unit_id = bai.unit_id AND bui.type_id != '1731'
        LEFT JOIN bm_project bp ON bp.pro_id = bai.project_id
        LEFT JOIN slt_agreement_apply saa ON saa.agreement_id = bai.agreement_id AND (saa.status IS NULL OR saa.status != '2')
        WHERE bai.status = '1'
        AND (bai.is_slt = '0' OR bai.is_slt IS NULL)
        <if test="unitIds != null and unitIds.size() > 0">
            AND bai.unit_id IN
            <foreach item="item" index="index" collection="unitIds" open="(" separator="," close=")">
                #{item}
            </foreach>
        </if>
        <if test="projectId != null and projectId != ''">
            AND bai.project_id = #{projectId}
        </if>
        <if test="sltStatus != null and sltStatus != ''">
            AND bai.is_slt = #{sltStatus}
        </if>
        <if test="agreementCode != null and agreementCode != ''">
            AND bai.agreement_code LIKE CONCAT('%', #{agreementCode}, '%')
        </if>
        <if test="unitName != null and unitName != ''">
            AND bui.unit_name LIKE CONCAT('%', #{unitName}, '%')
        </if>
        <if test="projectName != null and projectName != ''">
            AND bp.pro_name LIKE CONCAT('%', #{projectName}, '%')
        </if>
        ORDER BY bai.create_time DESC
    </select>

    <select id="selectPeriodCostListForCharge" parameterType="com.bonus.material.settlement.domain.dto.PeriodCostQueryDto" resultMap="PeriodCostResultMap">
        select
            ptc.agreement_id, bai.agreement_code, ptc.type_id, ptc.lease_num as num, ptc.start_time, ptc.end_time, ptc.day as lease_day,
            ptc.price, ptc.lease_money as lease_cost, ptc.cost_type, ptc.mark_time, mt.type_name as model_name, mt1.type_name as type_name
        from project_temp_cost ptc
        inner join bm_agreement_info bai on ptc.agreement_id = bai.agreement_id
        LEFT JOIN ma_type mt ON ptc.type_id = mt.type_id AND mt.`level` = '4'
        LEFT JOIN ma_type mt1 ON mt.parent_id = mt1.type_id AND mt1.`level` = '3'
        where ptc.mark_time = #{startDate}
        <if test="agreementId != null">
            and ptc.agreement_id = #{agreementId}
        </if>
        <if test="agreementCode != null">
            and bai.agreement_code = #{agreementCode}
        </if>
    </select>
</mapper>
