<?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.web.arap.mapper.ArapOffsetMapper">

    <insert id="syncOpenPayFromRecv">
        insert into arap_open_pay (
            org_id, src_type, src_id, pay_no, pay_date, request_unit, cust_no, cust_name, bank_no,
            total_amt, open_amt, settle_status, del_flag, create_by, create_time, update_by, update_time
        )
        select r.org_id, 'RECV', r.id, r.recv_no, r.recv_date, r.cust_no, r.cust_no, r.cust_name, ifnull(r.bank_no, ''),
               ifnull(r.recv_amt, 0), ifnull(r.recv_amt, 0), '0', '0', r.create_by, now(), r.update_by, now()
        from arap_recv r
        where r.del_flag = '0'
          and r.org_id = #{orgId}
          and not exists (
              select 1 from arap_open_pay p
              where p.org_id = r.org_id and p.src_type = 'RECV' and p.src_id = r.id
          )
    </insert>

    <insert id="syncOpenPayFromRefund">
        insert into arap_open_pay (
            org_id, src_type, src_id, pay_no, pay_date, request_unit, cust_no, cust_name, bank_no,
            total_amt, open_amt, settle_status, del_flag, create_by, create_time, update_by, update_time
        )
        select r.org_id, 'REFUND', r.id, r.ref_no, r.ref_date, r.cust_no, r.cust_no, r.cust_name, ifnull(r.bank_no, ''),
               (0 - ifnull(r.ref_amt, 0)), (0 - ifnull(r.ref_amt, 0)), '0', '0', r.create_by, now(), r.update_by, now()
        from arap_refund r
        where r.del_flag = '0'
          and r.org_id = #{orgId}
          and not exists (
              select 1 from arap_open_pay p
              where p.org_id = r.org_id and p.src_type = 'REFUND' and p.src_id = r.id
          )
    </insert>

    <insert id="syncOrderOpenFromDelivery">
        insert into arap_order_open (
            org_id, doc_type, src_id, doc_no, doc_date, cust_no, cust_name, total_amt, open_amt, offset_status, remark, del_flag, create_by, create_time, update_by, update_time
        )
        select s.org_id, 'DELIVERY', s.id, s.delivery_num, s.document_date, s.customer_num, s.customer_name,
               cast(ifnull(s.total_amount, '0') as decimal(18,4)),
               cast(ifnull(s.total_amount, '0') as decimal(18,4)),
               ifnull(cast(s.offset_status as char), '0'), s.remark, '0', s.create_by, now(), s.update_by, now()
        from sales_delivery s
        where s.del_flag = '0'
          and s.org_id = #{orgId}
          and not exists (
              select 1 from arap_order_open o
              where o.org_id = s.org_id and o.doc_type = 'DELIVERY' and o.doc_no = s.delivery_num
          )
    </insert>

    <insert id="syncOrderOpenFromReturn">
        insert into arap_order_open (
            org_id, doc_type, src_id, doc_no, doc_date, cust_no, cust_name, total_amt, open_amt, offset_status, remark, del_flag, create_by, create_time, update_by, update_time
        )
        select s.org_id, 'RETURN', s.id, s.return_num, s.document_date, s.customer_num, s.receivable_customer,
               abs(cast(ifnull(s.total_amount, '0') as decimal(18,4))),
               abs(cast(ifnull(s.total_amount, '0') as decimal(18,4))),
               ifnull(cast(s.offset_status as char), '0'), s.remark, '0', s.create_by, now(), s.update_by, now()
        from sales_return s
        where s.del_flag = '0'
          and s.org_id = #{orgId}
          and not exists (
              select 1 from arap_order_open o
              where o.org_id = s.org_id and o.doc_type = 'RETURN' and o.doc_no = s.return_num
          )
    </insert>

    <select id="selectOpenPayList" parameterType="com.ruoyi.web.arap.domain.ArapOffset" resultType="com.ruoyi.web.arap.domain.vo.ArapOpenPayVo">
        select id, src_type as srcType, src_id as srcId, pay_no as payNo, pay_date as payDate, request_unit as requestUnit,
               cust_no as custNo, cust_name as custName, bank_no as bankNo, total_amt as totalAmt, open_amt as openAmt, settle_status as settleStatus
        from arap_open_pay
        <where>
            del_flag = '0'
            and org_id = #{orgId}
            and settle_status = '0'
            <if test="requestUnit != null and requestUnit != ''">and request_unit = #{requestUnit}</if>
            <if test="custNo != null and custNo != ''">and cust_no = #{custNo}</if>
            <if test="custName != null and custName != ''">and cust_name like concat('%', #{custName}, '%')</if>
            <if test="offStartDate != null">and pay_date &gt;= #{offStartDate}</if>
            <if test="offEndDate != null">and pay_date &lt;= #{offEndDate}</if>
            <if test="invoiceNo != null and invoiceNo != ''">and invoice_no like concat('%', #{invoiceNo}, '%')</if>
            <if test="invoiceStatus != null and invoiceStatus != ''">and invoice_status = #{invoiceStatus}</if>
            <if test="ccyNo != null and ccyNo != ''">and ccy_no = #{ccyNo}</if>
            <if test="ccyName != null and ccyName != ''">and ccy_name like concat('%', #{ccyName}, '%')</if>
            <if test="billRemark != null and billRemark != ''">and bill_remark like concat('%', #{billRemark}, '%')</if>
            <if test="acctYm != null and acctYm != ''">and acct_ym = #{acctYm}</if>
            <if test="hasRecvData != null and hasRecvData != ''">and has_recv_data = #{hasRecvData}</if>
            <if test="params != null and params.idList != null and params.idList.size() > 0">
                and id in
                <foreach collection="params.idList" item="id" open="(" close=")" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
        order by pay_date desc, pay_no desc
    </select>

    <select id="selectOrderOpenList" resultType="com.ruoyi.web.arap.domain.vo.ArapOrderOpenVo">
        select id, doc_type as docType, cust_no as custNo, cust_name as custName, doc_date as docDate, doc_no as docNo,
               total_amt as totalAmt, open_amt as openAmt,
               0 as offAmt, 0 as offDiscAmt, open_amt as unoffAmt, 0 as afterTaxDiscAmt, 0 as recvArAmt
        from arap_order_open
        <where>
            del_flag = '0'
            and org_id = #{orgId}
            and cust_no = #{custNo}
            and open_amt &gt; 0
            <if test="startDate != null">and doc_date &gt;= #{startDate}</if>
            <if test="endDate != null">and doc_date &lt;= #{endDate}</if>
            <if test="remark != null and remark != ''">and remark like concat('%', #{remark}, '%')</if>
        </where>
        order by doc_date desc, doc_no desc
    </select>

    <select id="selectTodayMaxSeq" resultType="java.lang.Integer">
        select max(cast(right(off_no, 4) as unsigned))
        from arap_offset
        where org_id = #{orgId}
          and date_format(off_date, '%Y%m%d') = #{dateText}
          and del_flag = '0'
    </select>

    <insert id="insertOffset" parameterType="com.ruoyi.web.arap.domain.ArapOffset" useGeneratedKeys="true" keyProperty="id">
        insert into arap_offset (
            org_id, off_date, off_no, request_unit, cust_no, cust_name, total_open_amt, avail_amt, total_off_amt,
            rev_status, del_flag, create_by, create_time, update_by, update_time
        ) values (
            #{orgId}, #{offDate}, #{offNo}, #{requestUnit}, #{custNo}, #{custName}, #{totalOpenAmt}, #{availAmt}, #{totalOffAmt},
            #{revStatus}, #{delFlag}, #{createBy}, now(), #{updateBy}, now()
        )
    </insert>

    <insert id="insertOffsetItemBatch">
        insert into arap_offset_item (
            org_id, off_id, off_no, doc_type, cust_no, cust_name, doc_date, doc_no, total_amt, open_amt, off_amt, off_disc_amt,
            unoff_amt, after_tax_disc_amt, recv_ar_amt, recv_no, recv_type, rev_status, del_flag, create_by, create_time, update_by, update_time
        ) values
        <foreach collection="list" item="item" separator=",">
            (
                #{item.orgId}, #{item.offId}, #{item.offNo}, #{item.docType}, #{item.custNo}, #{item.custName}, #{item.docDate}, #{item.docNo}, #{item.totalAmt}, #{item.openAmt}, #{item.offAmt}, #{item.offDiscAmt},
                #{item.unoffAmt}, #{item.afterTaxDiscAmt}, #{item.recvArAmt}, #{item.recvNo}, #{item.recvType}, #{item.revStatus}, #{item.delFlag}, #{item.createBy}, now(), #{item.updateBy}, now()
            )
        </foreach>
    </insert>

    <update id="decreaseOrderOpen">
        update arap_order_open
        set open_amt = case when open_amt - #{amt} &lt; 0 then 0 else open_amt - #{amt} end,
            offset_status = case when open_amt - #{amt} &lt;= 0 then '1' else '0' end,
            update_by = #{updateBy},
            update_time = now()
        where org_id = #{orgId}
          and doc_type = #{docType}
          and doc_no = #{docNo}
          and del_flag = '0'
    </update>

    <update id="decreaseOpenPay">
        update arap_open_pay
        set open_amt = case
                         when total_amt &gt;= 0 then case when open_amt - #{amt} &lt; 0 then 0 else open_amt - #{amt} end
                         else case when open_amt + #{amt} &gt; 0 then 0 else open_amt + #{amt} end
                       end,
            settle_status = case
                              when total_amt &gt;= 0 and open_amt - #{amt} &lt;= 0 then '1'
                              when total_amt &lt; 0 and open_amt + #{amt} &gt;= 0 then '1'
                              else '0'
                            end,
            update_by = #{updateBy},
            update_time = now()
        where id = #{id}
          and org_id = #{orgId}
          and del_flag = '0'
    </update>

    <select id="selectOffsetList" parameterType="com.ruoyi.web.arap.domain.ArapOffset" resultType="com.ruoyi.web.arap.domain.ArapOffset">
        select id, org_id as orgId, off_date as offDate, off_no as offNo, request_unit as requestUnit, cust_no as custNo, cust_name as custName,
               total_open_amt as totalOpenAmt, avail_amt as availAmt, total_off_amt as totalOffAmt, rev_status as revStatus, del_flag as delFlag,
               create_by as createBy, create_time as createTime, update_by as updateBy, update_time as updateTime
        from arap_offset
        <where>
            del_flag = '0'
            and org_id = #{orgId}
            <if test="offStartDate != null">and off_date &gt;= #{offStartDate}</if>
            <if test="offEndDate != null">and off_date &lt;= #{offEndDate}</if>
            <if test="offNo != null and offNo != ''">and off_no like concat('%', #{offNo}, '%')</if>
            <if test="requestUnit != null and requestUnit != ''">and request_unit = #{requestUnit}</if>
            <if test="custName != null and custName != ''">and cust_name like concat('%', #{custName}, '%')</if>
        </where>
        order by off_date desc, off_no desc
    </select>

    <select id="selectOffsetById" resultType="com.ruoyi.web.arap.domain.ArapOffset">
        select id, org_id as orgId, off_date as offDate, off_no as offNo, request_unit as requestUnit, cust_no as custNo, cust_name as custName,
               total_open_amt as totalOpenAmt, avail_amt as availAmt, total_off_amt as totalOffAmt, rev_status as revStatus, del_flag as delFlag
        from arap_offset
        where id = #{id}
          and org_id = #{orgId}
          and del_flag = '0'
    </select>

    <select id="selectOffsetItems" resultType="com.ruoyi.web.arap.domain.ArapOffsetItem">
        select id, org_id as orgId, off_id as offId, off_no as offNo, doc_type as docType, cust_no as custNo, cust_name as custName,
               doc_date as docDate, doc_no as docNo, total_amt as totalAmt, open_amt as openAmt, off_amt as offAmt, off_disc_amt as offDiscAmt,
               unoff_amt as unoffAmt, after_tax_disc_amt as afterTaxDiscAmt, recv_ar_amt as recvArAmt, recv_no as recvNo, recv_type as recvType,
               rev_status as revStatus, del_flag as delFlag
        from arap_offset_item
        where off_id = #{offId}
          and org_id = #{orgId}
          and del_flag = '0'
        order by id asc
    </select>

    <update id="markItemReversed">
        update arap_offset_item
        set rev_status = '1',
            update_by = #{updateBy},
            update_time = now()
        where id = #{id}
          and org_id = #{orgId}
          and del_flag = '0'
          and rev_status = '0'
    </update>

    <update id="increaseOrderOpen">
        update arap_order_open
        set open_amt = open_amt + #{amt},
            offset_status = '0',
            update_by = #{updateBy},
            update_time = now()
        where org_id = #{orgId}
          and doc_type = #{docType}
          and doc_no = #{docNo}
          and del_flag = '0'
    </update>

    <update id="updateOffsetReverseStatus">
        update arap_offset
        set rev_status = #{status},
            update_by = #{updateBy},
            update_time = now()
        where id = #{offId}
          and org_id = #{orgId}
          and del_flag = '0'
    </update>

</mapper>

