package com.yem.wm.es.contractamtlist.util;

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author xwudd
 * @Description
 * @date 15:10
 **/
public class FunUtil {

    /**
     * @description 获取外销合同
     * @author xwudd
     * @param[1] saleOrderId
     * return
     * @time 2023/11/16 15:15
     */

    public static DynamicObject getSaleOrder(Long saleOrderId){
        return BusinessDataServiceHelper.loadSingle(saleOrderId, "yem_es_salesorder");
    }

    /**
     * @description 合同信息赋值
     * @author xwudd
     * @param[1] entity
     * @param[2] saleOrder
     * return
     * @time 2023/11/16 17:08
     */

    public static void setContractInfo(DynamicObject entity,DynamicObject[] saleOrders,DynamicObject obj,String flag){
        String name = obj.getDynamicObjectType().getName();
        for(DynamicObject saleOrder : saleOrders){
            DynamicObjectCollection saleOrderInfos = entity.getDynamicObjectCollection("yem_saleorderinfo");
            DynamicObject addNew = saleOrderInfos.addNew();
            addNew.set("yem_saleorg",saleOrder.get("org"));//销售组织
            addNew.set("yem_saleoorderno",saleOrder.get("billno"));//外销合同号
            addNew.set("yem_producttype",saleOrder.get("yem_bd_products"));//产品类型
            addNew.set("yem_customer",saleOrder.get("yem_customer"));//客户
            addNew.set("yem_saleuser",saleOrder.get("yem_operator"));//销售员
            addNew.set("yem_reccondition",saleOrder.get("yem_reccondition"));//收款条件
            addNew.set("yem_bizdate",saleOrder.get("yem_signdate"));//签订日期
            addNew.set("yem_clientcountry",saleOrder.get("yem_clientcountry"));//贸易国别
            addNew.set("yem_currency",saleOrder.get("yem_currency"));//合同币别
            addNew.set("yem_currencybase",saleOrder.get("yem_currencybase"));//本位币
            addNew.set("yem_exrate",saleOrder.get("yem_exrate"));//汇率
            addNew.set("yem_amount",saleOrder.get("yem_offeramount"));//合同总额
            addNew.set("yem_amountbase",saleOrder.get("yem_offerstandardcoin"));//合同本位币金额
            addNew.set("yem_iscreditcontract",isCreditContract(saleOrder));//是否信用证合同
            DynamicObjectCollection paymentInfos = addNew.getDynamicObjectCollection("yem_paymentinfo");//收款信息
            DynamicObjectCollection payInfos = addNew.getDynamicObjectCollection("yem_payinfo");//收款明细
            DynamicObjectCollection detailInfos = addNew.getDynamicObjectCollection("yem_detailinfo");//明细信息
            DynamicObjectCollection IOUInfos = addNew.getDynamicObjectCollection("yem_iouinfo");//欠条信息
            DynamicObject[] payBills = getPayBills(saleOrder,obj,flag);//收款单
            DynamicObject[] shipBills = getShipBills(saleOrder,obj,flag);//出运
            DynamicObject[] deliver = getDeliver(saleOrder,obj,flag);//发货
            DynamicObject[] tradeApp = getTradeApp(saleOrder,obj,flag);//国贸贷款欠条申请
            Map<DynamicObject, Map<DynamicObject, List<DynamicObject>>> orderFlowPath = getOrderFlowPath(saleOrder, shipBills, deliver);
            if("yem_es_salesorder".equals(name)){
                setSalePaymentInfo(saleOrder,paymentInfos,payBills,shipBills,deliver,tradeApp);//收款信息赋值（实际收款）
            }
            if("yem_es_exportpresent".equals(name)){
                setSalePaymentInfo(saleOrder,paymentInfos,payBills,shipBills,deliver,tradeApp);//收款信息赋值（实际收款）
            }
            if("yem_shippingdetails".equals(name)){
                if("A".equals(flag)){
                    setSalePaymentInfo(saleOrder,paymentInfos,payBills,shipBills,deliver,tradeApp);//收款信息赋值（实际收款）
                }
                if("B".equals(flag)){
                    setShipPaymentInfo(saleOrder,paymentInfos,payBills,shipBills,deliver,tradeApp,obj);//收款信息赋值（款项占用）
                }

            }
            if("yem_es_delivernotice".equals(name)){
                if("A".equals(flag)){
                    setSalePaymentInfo(saleOrder,paymentInfos,payBills,shipBills,deliver,tradeApp);//收款信息赋值（实际收款）
                }
                if("B".equals(flag)){
                    setDeliverPaymentInfo(saleOrder,paymentInfos,payBills,shipBills,deliver,tradeApp,obj);//收款信息赋值（款项占用）
                }

            }
            setPayInfo(saleOrder,payInfos,payBills);//收款明细赋值
            setDetailInfos(saleOrder,detailInfos,orderFlowPath.get(saleOrder));//明细信息赋值
            setIOUInfo(IOUInfos,tradeApp);//欠条信息赋值
        }
    }

    /**
     * @description 收款信息赋值（实际收款）
     * @author xwudd
     * @param[1] saleOrder
     * @param[2] paymentInfos
     * @param[3] gatherings
     * @param[4] shippingDetails
     * @param[5] deliverNotices
     * @param[6] tradeApps
     * return
     * @time 2023/11/17 17:17
     */

    public static void setSalePaymentInfo(DynamicObject saleOrder,DynamicObjectCollection paymentInfos,DynamicObject[] gatherings,DynamicObject[] shippingDetails,DynamicObject[] deliverNotices,DynamicObject[] tradeApps){
        DynamicObject addNew = paymentInfos.addNew();
        BigDecimal rapRate = PaymentControlUtil.getRapRate(saleOrder);
        BigDecimal sumUnClaimAmt = gaugeOutfitSum(gatherings, "yem_sumunclaimamt");//未认领金额合计（客户金额（已收款未认领））
        BigDecimal contractPayment = PaymentControlUtil.getContractPayment(saleOrder);//合同实际金额 A
        BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(saleOrder);//生产预收汇比例
        BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(saleOrder);//发货预收汇比例
        BigDecimal contractPaymentAdv = PaymentControlUtil.getAdvancePayment(contractPayment, procPreRapRate);//合同实际下单预收金额 B
        BigDecimal collection = PaymentControlUtil.getCollection(saleOrder, gatherings);//合同下单已认领金额 C
        BigDecimal allBalancePayment = PaymentControlUtil.getAllBalancePayment(shippingDetails);//已发运金额 D
        BigDecimal allDeliverPayment = PaymentControlUtil.getAllDeliverPayment(deliverNotices);//已发货金额 E
        BigDecimal shipArrearsAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allBalancePayment, rapRate));//发运欠款金额 F
        BigDecimal deliverArrearsAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allDeliverPayment,rapRate));//发货欠款金额 G
        BigDecimal thisShipIOUAmt = gaugeOutfitSum(tradeApps, "yem_thisshipiouamt");//累计欠条金额 H
        BigDecimal IOUResidueAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allBalancePayment, rapRate));
        BigDecimal preCollection = PaymentControlUtil.getPreCollection(saleOrder, gatherings, "D");//合同下单预收金额
        BigDecimal shipCollection = PaymentControlUtil.getPreCollection(saleOrder, gatherings, "E");//合同发货预收金额
        BigDecimal advancePayment = PaymentControlUtil.getAdvancePayment(contractPayment, shipPreRapRate);//合同实际发货预收金额
        BigDecimal orderedAmount = PaymentControlUtil.getOrderedAmount(saleOrder, "A");

        BigDecimal amountsOwedShipments = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allBalancePayment, procPreRapRate));
        BigDecimal calcShipAmount = PaymentControlUtil.getCalcShipAmount(saleOrder);//发运欠款金额2
        BigDecimal addedAmountsOwedShipments;
        if (amountsOwedShipments.compareTo(BigDecimal.ZERO) > 0) {
            addedAmountsOwedShipments = calcShipAmount;
        } else {
            addedAmountsOwedShipments = amountsOwedShipments.add(calcShipAmount);//发运欠款金额 = amountsOwedShipments + calcShipAmount
        }

        BigDecimal amountsOwedDeliver = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment, procPreRapRate));//发货欠款金额2
        BigDecimal calcDeliverAmount = PaymentControlUtil.getCalcDeliverAmount(saleOrder);//发货欠款金额2
        BigDecimal addedAmountsOwedDeliver;
        if (amountsOwedDeliver.compareTo(BigDecimal.ZERO) > 0) {
            addedAmountsOwedDeliver = calcDeliverAmount;
        } else {
            addedAmountsOwedDeliver = amountsOwedDeliver.add(calcDeliverAmount);;//发货欠款金额 = amountsOwedDeliver + calcDeliverAmount
        }
        BigDecimal iOUResidueAmount = PaymentControlUtil.getIOUResidueAmount(saleOrder);//欠条剩余金额

        addNew.set("yem_currency_pay",saleOrder.get("yem_currency"));
        addNew.set("yem_currencybase_pay",saleOrder.get("yem_currencybase"));
        addNew.set("yem_customeramt",sumUnClaimAmt.setScale(2, RoundingMode.HALF_UP));//客户金额（已收款未认领）
        // 新增  客户-收款单-财务信息：已认领金额合计的汇总值
        addNew.set("yem_customeramtcfmed", gaugeOutfitSum(gatherings, "yem_sumclaimamt").setScale(2, RoundingMode.HALF_UP));// 客户金额（已认领）
        addNew.set("yem_orderrealityamt",contractPayment.setScale(2, RoundingMode.HALF_UP));//合同实际金额
        // 新增
        addNew.set("yem_accshiprecedamo", advancePayment.setScale(2, RoundingMode.HALF_UP));//合同实际发货预收金额
        // 新增
        BigDecimal amountOrdered = PaymentControlUtil.getAdvancePayment(orderedAmount, procPreRapRate);
        addNew.set("yem_orderedamo", amountOrdered.setScale(2, RoundingMode.HALF_UP));//已下单金额
        // 修改
        addNew.set("yem_orderrealityadvamt", contractPaymentAdv.setScale(2, RoundingMode.HALF_UP));//合同实际下单预收金额
        // 修改
        addNew.set("yem_orderclaimamount", preCollection.setScale(2, RoundingMode.HALF_UP));//合同下单已认领金额
        // 新增
        addNew.set("yem_shipclaimamount", shipCollection.setScale(2, RoundingMode.HALF_UP));//合同发货已认领金额
        addNew.set("yem_shipamt_p", allBalancePayment.setScale(2, RoundingMode.HALF_UP));//已发运金额
        addNew.set("yem_deliveramt_p",allDeliverPayment.setScale(2, RoundingMode.HALF_UP));//已发货金额
        // 新增
        addNew.set("yem_orderarrearsamo", preCollection.setScale(2, RoundingMode.HALF_UP).subtract(amountOrdered.setScale(2, RoundingMode.HALF_UP)));//下单欠款金额
        // 修改
        addNew.set("yem_shipdebtamt", addedAmountsOwedShipments.setScale(2, RoundingMode.HALF_UP));//发运欠款金额
        // 修改
        addNew.set("yem_deliverdebtamt", addedAmountsOwedDeliver.setScale(2, RoundingMode.HALF_UP));//发货欠款金额
        addNew.set("yem_accumulateiocamt", thisShipIOUAmt.setScale(2, RoundingMode.HALF_UP));//累计欠条金额
        addNew.set("yem_iocresidueamt", iOUResidueAmount.setScale(2, RoundingMode.HALF_UP));//欠条剩余金额


        BigDecimal contractClimeAmt = PaymentControlUtil.getAllContractClimeAmt(saleOrder, "A");
        // 合同已认领金额
        addNew.set("yem_contractclaimamt", contractClimeAmt);
        // 合同未认领金额
        addNew.set("yem_contractunclaimamt", contractPayment.setScale(2, RoundingMode.HALF_UP).subtract(contractClimeAmt.setScale(2, RoundingMode.HALF_UP)));
    }


    /**
     * @description 收款信息赋值（款项占用）
     * @author xwudd
     * @param[1] saleOrder
     * @param[2] paymentInfos
     * @param[3] gatherings
     * @param[4] shippingDetails
     * @param[5] deliverNotices
     * @param[6] tradeApps
     * return
     * @time 2023/11/17 17:17
     */

    public static void setShipPaymentInfo(DynamicObject saleOrder, DynamicObjectCollection paymentInfos, DynamicObject[] gatherings, DynamicObject[] shippingDetails, DynamicObject[] deliverNotices, DynamicObject[] tradeApps, DynamicObject obj) {
        DynamicObject addNew = paymentInfos.addNew();
        BigDecimal rapRate = PaymentControlUtil.getRapRate(saleOrder);
        BigDecimal sumUnClaimAmt = gaugeOutfitSum(gatherings, "yem_sumunclaimamt");//未认领金额合计（客户金额（已收款未认领））
        BigDecimal contractPayment = PaymentControlUtil.getContractPayment(saleOrder);//合同实际金额 A
        BigDecimal contractPaymentAdv = PaymentControlUtil.getAdvancePayment(contractPayment, rapRate);//合同实际下单预收金额 B
        BigDecimal collection = PaymentControlUtil.getCollection(saleOrder, gatherings);//合同下单已认领金额 C
        DynamicObject[] exThisShippingDetails = getThisShippingDetails(shippingDetails, obj);//本次出运
        BigDecimal allBalancePayment = getAllBalancePayment(shippingDetails, obj, "yem_offeramount");//已发运占用金额 D
        BigDecimal allDeliverPayment = getNewAllDeliverPayment(exThisShippingDetails);//已发货占用金额 E
        BigDecimal thisAmt = getThisAmt(obj);//本次出运/发货金额
        BigDecimal thisShipAmt = getThisShipAmt(obj);//本次出运金额
        BigDecimal historyShipDebtAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allBalancePayment, rapRate));//历史出运欠款金额 F
        BigDecimal historyDeliverDebtAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allDeliverPayment, rapRate));//历史发货欠款金额 G
        BigDecimal thisShipIOUAmt = gaugeOutfitSum(tradeApps, "yem_thisshipiouamt");//累计欠条金额 H
        BigDecimal thisShipDebtAmt = historyShipDebtAmt.subtract(PaymentControlUtil.getBalancePayment(thisAmt, rapRate));//本次出运欠款金额
        BigDecimal abs = getAbs(thisShipDebtAmt);
        BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(saleOrder);//生产预收汇比例
        BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(saleOrder);//发货预收汇比例

        BigDecimal changeContractPaymentAdv = PaymentControlUtil.getAdvancePayment(contractPayment, procPreRapRate);//合同实际下单预收金额 B change


        // 新增  客户-收款单-财务信息：已认领金额合计的汇总值
        addNew.set("yem_customeramtcfmed", gaugeOutfitSum(gatherings, "yem_sumclaimamt").setScale(2, RoundingMode.HALF_UP));// 客户金额（已认领）

        BigDecimal advancePayment = PaymentControlUtil.getAdvancePayment(contractPayment, shipPreRapRate);//合同实际发货预收金额 new

        BigDecimal preCollection = PaymentControlUtil.getPreCollection(saleOrder, gatherings, "D");//合同下单已认领金额 C change

        BigDecimal shipCollection = PaymentControlUtil.getPreCollection(saleOrder, gatherings, "E");//合同发货预收金额

        BigDecimal orderedAmount = PaymentControlUtil.getOrderedAmount(saleOrder, "B");

        BigDecimal amountsOwedDeliver = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment, procPreRapRate));//发货欠款金额2
        BigDecimal calcDeliverAmount = PaymentControlUtil.getNewCalcShipAmount(exThisShippingDetails, shipPreRapRate);//发货欠款金额2
        BigDecimal addedAmountsOwedDeliver;
        if (amountsOwedDeliver.compareTo(BigDecimal.ZERO) > 0) {
            addedAmountsOwedDeliver = calcDeliverAmount;
        } else {
            addedAmountsOwedDeliver = amountsOwedDeliver.add(calcDeliverAmount);;//发货欠款金额 = amountsOwedDeliver + calcDeliverAmount
        }
        BigDecimal iOUResidueAmount = PaymentControlUtil.getIOUResidueAmount(saleOrder);//欠条剩余金额

//        if (historyShipDebtAmt.compareTo(BigDecimal.ZERO) > 0) {
//            addNew.set("yem_thisshipapplyresmta", abs.setScale(2, RoundingMode.HALF_UP));//本次发运应申请欠条金额
//        } else {
//            addNew.set("yem_thisshipapplyresmta", abs.add(historyShipDebtAmt).setScale(2, RoundingMode.HALF_UP));//本次发运应申请欠条金额
//        }
        addNew.set("yem_thisshipamt", thisAmt.setScale(2, RoundingMode.HALF_UP));//本次发运金额
        // 新增
        addNew.set("yem_thisdeliveramt", thisShipAmt.setScale(2, RoundingMode.HALF_UP));//本次发货金额
        addNew.set("yem_currency_pay", saleOrder.get("yem_currency"));
        addNew.set("yem_currencybase_pay", saleOrder.get("yem_currencybase"));
        addNew.set("yem_customeramt", sumUnClaimAmt.setScale(2, RoundingMode.HALF_UP));//客户金额（已收款未认领）
        addNew.set("yem_orderrealityamt", contractPayment.setScale(2, RoundingMode.HALF_UP));//合同实际金额
        // 修改
        addNew.set("yem_orderrealityadvamt", changeContractPaymentAdv.setScale(2, RoundingMode.HALF_UP));//合同实际下单预收金额
        // 新增
        addNew.set("yem_accshiprecedamo", advancePayment.setScale(2, RoundingMode.HALF_UP));//合同实际发货预收金额
        // 修改
        addNew.set("yem_orderclaimamount", preCollection.setScale(2, RoundingMode.HALF_UP));//合同下单已认领金额
        // 新增
        addNew.set("yem_shipclaimamount", shipCollection.setScale(2, RoundingMode.HALF_UP));//合同发货已认领金额
        // 新增
        BigDecimal amountOrdered = PaymentControlUtil.getAdvancePayment(orderedAmount, procPreRapRate);
        addNew.set("yem_orderedamo", amountOrdered.setScale(2, RoundingMode.HALF_UP));//已下单金额
        // 新增
        addNew.set("yem_orderarrearsamo", preCollection.setScale(2, RoundingMode.HALF_UP).subtract(amountOrdered.setScale(2, RoundingMode.HALF_UP)));//下单欠款金额

        addNew.set("yem_shipoocuamt", allBalancePayment.setScale(2, RoundingMode.HALF_UP));//已出运金额
        addNew.set("yem_deliveroccuamt", allDeliverPayment.setScale(2, RoundingMode.HALF_UP));//已发货金额

        BigDecimal amountsOwedShipments = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allBalancePayment, procPreRapRate));
        BigDecimal calcShipAmount = PaymentControlUtil.getHistoryCalcShipAmount(exThisShippingDetails, shipPreRapRate);//发运欠款金额2
        BigDecimal addedAmountsOwedShipments;
        if (amountsOwedShipments.compareTo(BigDecimal.ZERO) > 0) {
            addedAmountsOwedShipments = calcShipAmount;
        } else {
            addedAmountsOwedShipments = amountsOwedShipments.add(calcShipAmount);//发运欠款金额 = thisAmountsOwedShipments + thisCalcShipAmount
        }

        // 修改
        addNew.set("yem_historyshipdebtamt", addedAmountsOwedShipments.setScale(2, RoundingMode.HALF_UP));//历史发运欠款金额
        // 修改
        addNew.set("yem_historydeliverdebtamt", addedAmountsOwedDeliver.setScale(2, RoundingMode.HALF_UP));//历史发货欠款金额

        BigDecimal newThisDeliverDebtAmt;
        BigDecimal formulaTwo = BigDecimal.ZERO;
        BigDecimal formulaOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allBalancePayment, procPreRapRate));//400 - 1224 *0.3
        if (formulaOne.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal subtract = formulaOne.subtract(PaymentControlUtil.getAdvancePayment(thisAmt, procPreRapRate));
            if (subtract.compareTo(BigDecimal.ZERO) > 0) {
                formulaTwo = BigDecimal.ZERO;
            } else {
                formulaTwo = subtract;
            }
        } else {
            formulaTwo = BigDecimal.ZERO.subtract(PaymentControlUtil.getAdvancePayment(thisAmt, procPreRapRate));
        }

        BigDecimal formulaThreeRes = BigDecimal.ZERO;
        BigDecimal formulaThree = PaymentControlUtil.getThisCalcShipAmount(obj, thisAmt, shipPreRapRate, saleOrder);

        if (formulaThree.compareTo(BigDecimal.ZERO) > 0) {
            formulaTwo = BigDecimal.ZERO;
        } else {
            formulaThreeRes = formulaThree;
        }

        newThisDeliverDebtAmt = formulaTwo.add(formulaThreeRes);
        // 修改
        addNew.set("yem_thisshipdebtamt", newThisDeliverDebtAmt.setScale(2, RoundingMode.HALF_UP));//本次发运欠款金额

        BigDecimal newThisShipDebtAmt;
//                                     C                                                             E                  Ee
//        BigDecimal shipElementOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment.add(thisShipAmt), procPreRapRate));
        BigDecimal shipElementOne = BigDecimal.ZERO;
        BigDecimal eleShipOneOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment, procPreRapRate));//下单预收欠款
        BigDecimal eleShipOneTwo;//发货预收欠款
        if (eleShipOneOne.compareTo(BigDecimal.ZERO) > 0) {
            shipElementOne = shipElementOne.add(eleShipOneOne);
            eleShipOneTwo = eleShipOneOne.subtract(PaymentControlUtil.getAdvancePayment(thisShipAmt, procPreRapRate));
        } else {
            eleShipOneTwo = BigDecimal.ZERO.subtract(PaymentControlUtil.getAdvancePayment(thisShipAmt, procPreRapRate));
        }

        if (eleShipOneOne.compareTo(BigDecimal.ZERO) > 0) {
            shipElementOne = shipElementOne.add(eleShipOneOne.add(eleShipOneTwo));
        }
        shipElementOne = shipElementOne.add(eleShipOneTwo);

        BigDecimal shipElementTwo = PaymentControlUtil.getHistoryCalcShipAmount(saleOrder, PaymentControlUtil.getAllShipPayment(shippingDetails), obj);
        if (shipElementOne.compareTo(BigDecimal.ZERO) > 0) {
            newThisShipDebtAmt = shipElementTwo;
        } else {
            newThisShipDebtAmt = shipElementOne.add(shipElementTwo);
        }

        // 修改
        addNew.set("yem_thisdeliverdebtamt", newThisShipDebtAmt);//本次发货欠款金额
        addNew.set("yem_accumulateiocamt", thisShipIOUAmt.setScale(2, RoundingMode.HALF_UP));//累计欠条金额
        // 修改
        addNew.set("yem_iocresidueamt", iOUResidueAmount.setScale(2, RoundingMode.HALF_UP));//欠条剩余金额
        addNew.set("yem_thisshipapplyresmta", getAbs(newThisDeliverDebtAmt).setScale(2, RoundingMode.HALF_UP));//本次发运应申请欠条金额

        BigDecimal contractClimeAmt = PaymentControlUtil.getAllContractClimeAmt(saleOrder, "B");
        // 合同已认领金额
        addNew.set("yem_contractclaimamt", contractClimeAmt);
        // 合同未认领金额
        addNew.set("yem_contractunclaimamt", contractPayment.setScale(2, RoundingMode.HALF_UP).subtract(contractClimeAmt.setScale(2, RoundingMode.HALF_UP)));
    }

    /**
     * 过滤掉本次的
     * @param shippingDetails
     * @param obj
     * @return
     */
    public static DynamicObject[] getThisShippingDetails(DynamicObject[] shippingDetails, DynamicObject obj)
    {
        if (shippingDetails.length == 0) return shippingDetails;
        ArrayList<DynamicObject> arrayList = new ArrayList<>(Arrays.asList(shippingDetails));
        arrayList.removeIf(shippingDetail -> shippingDetail.getLong("id") == obj.getLong("id"));
        return arrayList.toArray(new DynamicObject[0]);
    }


    /**
     * @description 收款信息赋值
     * @author xwudd
     * @param[1] saleOrder
     * @param[2] paymentInfos
     * @param[3] gatherings
     * @param[4] shippingDetails
     * @param[5] deliverNotices
     * @param[6] tradeApps
     * return
     * @time 2023/11/17 17:17
     */

    public static void setDeliverPaymentInfo(DynamicObject saleOrder, DynamicObjectCollection paymentInfos, DynamicObject[] gatherings, DynamicObject[] shippingDetails, DynamicObject[] deliverNotices, DynamicObject[] tradeApps, DynamicObject obj)
    {
        DynamicObject addNew = paymentInfos.addNew();
        BigDecimal rapRate = PaymentControlUtil.getRapRate(saleOrder);
        BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(saleOrder);//生产预收汇比例
        BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(saleOrder);//发货预收汇比例
        BigDecimal sumUnClaimAmt = gaugeOutfitSum(gatherings, "yem_sumunclaimamt");//未认领金额合计（客户金额（已收款未认领））
        BigDecimal contractPayment = PaymentControlUtil.getContractPayment(saleOrder);//合同实际金额 A
        BigDecimal contractPaymentAdv = PaymentControlUtil.getAdvancePayment(contractPayment, procPreRapRate);//合同实际下单预收金额 B
        BigDecimal collection = PaymentControlUtil.getCollection(saleOrder, gatherings);//合同下单已认领金额 C
        DynamicObject thisShippingDetails = getThisShippingDetailsByDeliver(obj);
        BigDecimal allBalancePayment = getAllBalancePayment(shippingDetails, thisShippingDetails, "yem_offeramount");//已发运占用金额 D
        BigDecimal allDeliverPayment = getAllBalancePayment(deliverNotices, obj, "yem_totalallamount");//已发货占用金额 E
        BigDecimal thisAmt = getThisAmt(obj);//本次出运/发货金额
        BigDecimal historyShipDebtAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allBalancePayment, rapRate));//历史出运欠款金额 F
        BigDecimal historyDeliverDebtAmt = collection.subtract(contractPaymentAdv).subtract(PaymentControlUtil.getBalancePayment(allDeliverPayment, rapRate));//历史发货欠款金额 G
        BigDecimal thisShipIOUAmt = gaugeOutfitSum(tradeApps, "yem_thisshipiouamt");//累计欠条金额 H
        BigDecimal thisDeliverDebtAmt = historyDeliverDebtAmt.subtract(PaymentControlUtil.getBalancePayment(thisAmt, rapRate));//本次发货欠款金额
        DynamicObject[] exThisShippingDetails = getThisShippingDetails(shippingDetails, thisShippingDetails);//本次出运

        BigDecimal advancePayment = PaymentControlUtil.getAdvancePayment(contractPayment, shipPreRapRate);//合同实际发货预收金额 new
        BigDecimal shipCollection = PaymentControlUtil.getPreCollection(saleOrder, gatherings, "E");//合同发货预收金额
        BigDecimal preCollection = PaymentControlUtil.getPreCollection(saleOrder, gatherings, "D");//合同下单已认领金额 C change
        BigDecimal orderedAmount = PaymentControlUtil.getOrderedAmount(saleOrder, "B");
        BigDecimal iOUResidueAmount = PaymentControlUtil.getIOUResidueAmount(saleOrder);//欠条剩余金额
        BigDecimal amountsOwedShipments = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allBalancePayment, procPreRapRate));
        BigDecimal calcShipAmount = PaymentControlUtil.getHistoryCalcShipAmount(exThisShippingDetails, shipPreRapRate);//发运欠款金额2
        BigDecimal thisShipAmt = getThisShipAmt(thisShippingDetails);//本次出运金额
        BigDecimal addedAmountsOwedShipments;
        if (amountsOwedShipments.compareTo(BigDecimal.ZERO) > 0) {
            addedAmountsOwedShipments = calcShipAmount;
        } else {
            addedAmountsOwedShipments = amountsOwedShipments.add(calcShipAmount);//发运欠款金额 = thisAmountsOwedShipments + thisCalcShipAmount
        }

        BigDecimal amountsOwedDeliver = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment, procPreRapRate));//发货欠款金额2
        BigDecimal calcDeliverAmount = PaymentControlUtil.getNewCalcShipAmount(exThisShippingDetails, shipPreRapRate);//发货欠款金额2
        BigDecimal addedAmountsOwedDeliver;
        if (amountsOwedDeliver.compareTo(BigDecimal.ZERO) > 0) {
            addedAmountsOwedDeliver = calcDeliverAmount;
        } else {
            addedAmountsOwedDeliver = amountsOwedDeliver.add(calcDeliverAmount);;//发货欠款金额 = amountsOwedDeliver + calcDeliverAmount
        }

        BigDecimal newThisDeliverDebtAmt;
//                                            C                                                           D                 Dd
//        BigDecimal deliverElementOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allBalancePayment.add(thisAmt), procPreRapRate));
        BigDecimal deliverElementOne = BigDecimal.ZERO;
        BigDecimal eleOneOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allBalancePayment, procPreRapRate));
        BigDecimal eleOneTwo;
        if (eleOneOne.compareTo(BigDecimal.ZERO) > 0) {
            deliverElementOne = deliverElementOne.add(eleOneOne);
            eleOneTwo = eleOneOne.subtract(PaymentControlUtil.getAdvancePayment(thisAmt, procPreRapRate));
        } else {
            eleOneTwo = BigDecimal.ZERO.subtract(PaymentControlUtil.getAdvancePayment(thisAmt, procPreRapRate));
        }
        if (eleOneOne.compareTo(BigDecimal.ZERO) > 0) {
            deliverElementOne = deliverElementOne.add(eleOneOne.add(eleOneTwo));
        }
        deliverElementOne = deliverElementOne.add(eleOneTwo);

        BigDecimal deliverElementTwo = PaymentControlUtil.getHistoryCalcShipAmount(saleOrder, thisAmt, obj);
        if (deliverElementOne.compareTo(BigDecimal.ZERO) > 0) {
            newThisDeliverDebtAmt = deliverElementTwo;
        } else {
            newThisDeliverDebtAmt = deliverElementOne.add(deliverElementTwo);
        }

        BigDecimal newThisShipDebtAmt;
//                                      C                                                             E                  Ee
//        BigDecimal shipElementOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment.add(thisShipAmt), procPreRapRate));
        BigDecimal shipElementOne = BigDecimal.ZERO;
        BigDecimal eleShipOneOne = preCollection.subtract(PaymentControlUtil.getAdvancePayment(allDeliverPayment, procPreRapRate));
        BigDecimal eleShipOneTwo;
        if (eleShipOneOne.compareTo(BigDecimal.ZERO) > 0) {
            shipElementOne = shipElementOne.add(eleShipOneOne);
            eleShipOneTwo = eleShipOneOne.subtract(PaymentControlUtil.getAdvancePayment(thisShipAmt, procPreRapRate));
        } else {
            eleShipOneTwo = BigDecimal.ZERO.subtract(PaymentControlUtil.getAdvancePayment(thisShipAmt, procPreRapRate));
        }

        if (eleShipOneOne.compareTo(BigDecimal.ZERO) > 0) {
            shipElementOne = shipElementOne.add(eleShipOneOne.add(eleShipOneTwo));
        }
        shipElementOne = shipElementOne.add(eleShipOneTwo);

        BigDecimal shipElementTwo = PaymentControlUtil.getHistoryCalcShipAmount(saleOrder, PaymentControlUtil.getAllShipPayment(shippingDetails), obj);
        if (shipElementOne.compareTo(BigDecimal.ZERO) > 0) {
            newThisShipDebtAmt = shipElementTwo;
        } else {
            newThisShipDebtAmt = shipElementOne.add(shipElementTwo);
        }

        // 新增  客户-收款单-财务信息：已认领金额合计的汇总值
        addNew.set("yem_customeramtcfmed", gaugeOutfitSum(gatherings, "yem_sumclaimamt").setScale(2, RoundingMode.HALF_UP));// 客户金额（已认领）
        // 新增
        addNew.set("yem_accshiprecedamo", advancePayment.setScale(2, RoundingMode.HALF_UP));//合同实际发货预收金额
        // 新增
        addNew.set("yem_shipclaimamount", shipCollection.setScale(2, RoundingMode.HALF_UP));//合同发货已认领金额
        BigDecimal amountOrdered = PaymentControlUtil.getAdvancePayment(orderedAmount, procPreRapRate);
        // 新增
        addNew.set("yem_orderedamo", amountOrdered.setScale(2, RoundingMode.HALF_UP));//已下单金额
        // 新增
        addNew.set("yem_orderarrearsamo", preCollection.setScale(2, RoundingMode.HALF_UP).subtract(amountOrdered.setScale(2, RoundingMode.HALF_UP)));//下单欠款金额
        addNew.set("yem_thisdeliveramt", thisAmt.setScale(2, RoundingMode.HALF_UP));//本次发货金额
        // 新增
        addNew.set("yem_thisdeliverdebtamt", newThisShipDebtAmt);//本次发货欠款金额
        addNew.set("yem_currency_pay", saleOrder.get("yem_currency"));
        addNew.set("yem_currencybase_pay", saleOrder.get("yem_currencybase"));
        addNew.set("yem_customeramt", sumUnClaimAmt.setScale(2, RoundingMode.HALF_UP));//客户金额（已收款未认领）
        addNew.set("yem_orderrealityamt", contractPayment.setScale(2, RoundingMode.HALF_UP));//合同实际金额
        addNew.set("yem_orderrealityadvamt", contractPaymentAdv.setScale(2, RoundingMode.HALF_UP));//合同实际下单预收金额
        addNew.set("yem_orderclaimamount", preCollection.setScale(2, RoundingMode.HALF_UP));//合同下单已认领金额
        addNew.set("yem_shipoocuamt", allBalancePayment.setScale(2, RoundingMode.HALF_UP));//已出运占用金额
        addNew.set("yem_deliveroccuamt", allDeliverPayment.setScale(2, RoundingMode.HALF_UP));//已发货占用金额
        // 修改
        addNew.set("yem_historyshipdebtamt", addedAmountsOwedShipments.setScale(2, RoundingMode.HALF_UP));//历史发运欠款金额
        // 修改
        addNew.set("yem_historydeliverdebtamt", addedAmountsOwedDeliver.setScale(2, RoundingMode.HALF_UP));//历史发货欠款金额
        addNew.set("yem_accumulateiocamt", thisShipIOUAmt.setScale(2, RoundingMode.HALF_UP));//累计欠条金额
        // 修改
        addNew.set("yem_iocresidueamt", iOUResidueAmount.setScale(2, RoundingMode.HALF_UP));//欠条剩余金额
        // 新增
        addNew.set("yem_thisshipdebtamt", newThisDeliverDebtAmt.setScale(2, RoundingMode.HALF_UP));//本次发运欠款金额
        // 新增
        addNew.set("yem_thisshipapplyresmta", getAbs(newThisDeliverDebtAmt).setScale(2, RoundingMode.HALF_UP));//本次发运应申请欠条金额
        // 新增
        addNew.set("yem_thisshipamt", thisAmt.setScale(2, RoundingMode.HALF_UP));//本次发运金额
    }

    private static DynamicObject getThisShippingDetailsByDeliver(DynamicObject obj)
    {
        long sourcebillid = obj.getLong("yem_sourcebillid");
        return BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_shippingdetails");
    }

    /**
     * @description 收款明细赋值
     * @author xwudd
     * @param[1] saleOrder
     * @param[2] payInfos
     * @param[3] gatherings
     * return
     * @time 2023/11/17 11:38
     */

    public static void setPayInfo(DynamicObject saleOrder,DynamicObjectCollection payInfos,DynamicObject[] gatherings){
        long saleOrderId = saleOrder.getLong("id");
        for(DynamicObject gathering : gatherings){
            DynamicObjectCollection receiptDetails = gathering.getDynamicObjectCollection("yem_receiptdetail");
            for(DynamicObject receiptDetail : receiptDetails){
                DynamicObjectCollection claimDetails = receiptDetail.getDynamicObjectCollection("yem_claimdetail");
                for(DynamicObject claimDetail : claimDetails){
                    DynamicObject salContractNo = claimDetail.getDynamicObject("yem_salcontractno");
                    DynamicObject shippingdetailsno = claimDetail.getDynamicObject("yem_shippingdetailsno");
                    if(YEM.isNotEmpty(salContractNo)){
                        long id = salContractNo.getLong("id");
                        if(saleOrderId == id){
                            DynamicObject addNew = payInfos.addNew();
                            addNew.set("yem_gatheringno",gathering.get("billno"));//收款单号
                            addNew.set("yem_gatheringcurrency",gathering.get("yem_currency"));//收款币别
                            addNew.set("yem_gatheringcurrencybase",gathering.get("yem_currencybase"));//本位币
                            addNew.set("yem_payregisterdate",gathering.get("yem_bizdate"));//收款登记日期
                            addNew.set("yem_moneytypetl",receiptDetail.get("yem_moneytypetl_a"));//款项类型

                            addNew.set("yem_receivableamt",receiptDetail.get("yem_receivableamt"));//应收金额
                            addNew.set("yem_receivableamtbase",receiptDetail.get("yem_receivableamtbase"));//应收金额（本位币）
                            addNew.set("yem_moneynaturetl", claimDetail.getString("yem_moneynature"));//款项性质
                            addNew.set("yem_contractno",salContractNo.get("billno"));//合同号
                            addNew.set("yem_shipnos", shippingdetailsno == null ? "" : shippingdetailsno.get("billno"));//发运单号
                            addNew.set("yem_payclaimamt",claimDetail.get("yem_claimamt"));//收款认领金额
                            addNew.set("yem_payclaimamtbase",claimDetail.get("yem_claimamtbase"));//收款认领金额（本位币）
                            addNew.set("yem_ordercurr",claimDetail.get("yem_contractrelevcuy"));//合同关联币别
                            addNew.set("yem_orderclaimamt",claimDetail.get("yem_salcontractclaamt"));//合同认领金额
                            addNew.set("yem_remark",claimDetail.get("yem_remark_b"));//备注
                            addNew.set("yem_claimuser",claimDetail.get("yem_claimman"));//认领人
                            addNew.set("yem_claimdate",claimDetail.get("yem_claimdate"));//认领时间
                        }
                    }
                }
            }
        }
    }

    /**
     * @description 明细信息赋值
     * @author xwudd
     * @param[1] entity
     * @param[2] map
     * return
     * @time 2023/11/16 17:07
     */

    public static void setDetailInfos(DynamicObject saleOrder,DynamicObjectCollection detailInfos,Map<DynamicObject, List<DynamicObject>> shipMap){
        if(YEM.isNotEmpty(shipMap) && shipMap.size() > 0){
            Set<DynamicObject> shipMapKeys = shipMap.keySet();
            for(DynamicObject shipMapKey : shipMapKeys){
                List<DynamicObject> deliverList = shipMap.get(shipMapKey);
                if (!"C".equals(shipMapKey.get("billstatus"))) continue;
                if(YEM.isNotEmpty(deliverList) && deliverList.size() > 0){
                    for(DynamicObject deliver : deliverList){
                        DynamicObject addNew = detailInfos.addNew();
                        addNew.set("yem_saleorderno",saleOrder.get("billno"));
                        addNew.set("yem_shipdetailno",shipMapKey.get("billno"));
                        addNew.set("yem_shipdetailstatus",shipMapKey.get("billstatus"));
                        addNew.set("yem_shipdate",shipMapKey.get("yem_bizdate"));
                        addNew.set("yem_shipamt",shipMapKey.get("yem_offeramount"));
                        addNew.set("yem_delivernoticeno",deliver.get("billno"));
                        addNew.set("yem_deliverdate",deliver.get("yem_bizdate"));
                        addNew.set("yem_deliveramt",deliver.get("yem_totalallamount"));
                    }
                }else{
                    DynamicObject addNew = detailInfos.addNew();
                    addNew.set("yem_saleorderno",saleOrder.get("billno"));
                    addNew.set("yem_shipdetailno",shipMapKey.get("billno"));
                    addNew.set("yem_shipdetailstatus",shipMapKey.get("billstatus"));
                    addNew.set("yem_shipdate",shipMapKey.get("yem_bizdate"));
                    addNew.set("yem_shipamt",shipMapKey.get("yem_offeramount"));
                }
            }
        }else{
            DynamicObject addNew = detailInfos.addNew();
            addNew.set("yem_saleorderno",saleOrder.get("billno"));
        }
    }

    /**
     * @description 欠条信息赋值
     * @author xwudd
     * @param[1] entity
     * @param[2] map
     * return
     * @time 2023/11/16 18:04
     */

    public static void setIOUInfo(DynamicObjectCollection IOUInfos,DynamicObject[] tradeApps){
        for(DynamicObject tradeApp : tradeApps){
            DynamicObject addNew = IOUInfos.addNew();
            addNew.set("yem_saleorderno_ioc",tradeApp.get("yem_corebillno"));//外销合同号
            addNew.set("yem_shipdetailno_ioc",tradeApp.get("yem_sourcebillno"));//出运明细单号
            addNew.set("yem_tradeappno",tradeApp.get("billno"));//国贸欠款欠条单号
            addNew.set("yem_bizdate_ioc",tradeApp.get("yem_bizdate"));//业务日期
            addNew.set("yem_iouamt",tradeApp.get("yem_thisshipiouamt"));//欠条金额
            addNew.set("yem_writeoffiouamo", tradeApp.get("yem_writtenoffamount"));//已核销金额
            addNew.set("yem_unwriteoffiouamo", tradeApp.get("yem_remainunwamount"));//未核销金额
        }
    }


    /**
     * @description 获取已审核 认领合同的 收款单
     * @author xwudd
     * @param[1] saleOrder
     * return
     * @time 2023/11/17 11:03
     */

    public static DynamicObject[] getPayBills(DynamicObject saleOrder,DynamicObject obj,String flag){
        long saleOrderId = saleOrder.getLong("id");
        String selectfields = DynamicObjectUtil.getSelectfields("yem_gathering", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_gathering","yem_receiptdetail",false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_gathering","yem_receiptdetail","yem_claimdetail",false);

//        QFilter qFilter = new QFilter("yem_receiptdetail.yem_claimdetail.yem_salcontractno", QCP.equals, saleOrderId);
        QFilter qFilter = new QFilter("yem_comegoman.id", QCP.equals, saleOrder.getLong("yem_customer.id"));
        qFilter.and(new QFilter("yem_financeaffirm", QCP.equals, "B"));
        qFilter = getBillStatusQFilter(qFilter,obj,flag);
        return BusinessDataServiceHelper.load("yem_gathering", selectfields, qFilter.toArray());
    }

    /**
     * @description 获取合同向下已审核的出运明细
     * @author xwudd
     * @param[1] saleOrder
     * return
     * @time 2023/11/17 14:32
     */

    public static DynamicObject[] getShipBills(DynamicObject saleOrder,DynamicObject obj,String flag){
        String saleOrderType = saleOrder.getDynamicObjectType().getName();
        long saleOrderId = saleOrder.getLong("id");
        QFilter qFilter = new QFilter("yem_corebillid", QCP.equals, saleOrderId);
        qFilter.and(new QFilter("yem_corebilltype",QCP.equals,saleOrderType));
        String name = obj.getDynamicObjectType().getName();
        getBillStatusQFilter(qFilter,obj,flag);
        String selectfields = DynamicObjectUtil.getSelectfields("yem_shippingdetails", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_shippingdetails","yem_es_materialinfo",false);
        DynamicObject[] shippingDetails = BusinessDataServiceHelper.load("yem_shippingdetails", selectfields, qFilter.toArray());
        return shippingDetails;
    }

    /**
     * @description 获取合同向下已审核的发货通知单
     * @author xwudd
     * @param[1] saleOrder
     * return
     * @time 2023/11/17 14:32
     */

    public static DynamicObject[] getDeliver(DynamicObject saleOrder,DynamicObject obj,String flag){
        String saleOrderType = saleOrder.getDynamicObjectType().getName();
        long saleOrderId = saleOrder.getLong("id");
        QFilter qFilter = new QFilter("yem_corebillid", QCP.equals, saleOrderId);
        qFilter.and(new QFilter("yem_corebilltype",QCP.equals,saleOrderType));
        String name = obj.getDynamicObjectType().getName();
        getBillStatusQFilter(qFilter,obj,flag);
        String selectfields = DynamicObjectUtil.getSelectfields("yem_es_delivernotice", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_es_delivernotice","yem_es_materialinfo",false);
        DynamicObject[] shippingDetails = BusinessDataServiceHelper.load("yem_es_delivernotice", selectfields, qFilter.toArray());
        return shippingDetails;
    }

    /**
     * @description 获取合同向下出运向下的国贸贷款欠条申请
     * @author xwudd
     * @param[1] saleOrder
     * return
     * @time 2023/11/17 16:45
     */

    public static DynamicObject[] getTradeApp(DynamicObject saleOrder,DynamicObject obj,String flag){
        String saleOrderType = saleOrder.getDynamicObjectType().getName();
        long saleOrderId = saleOrder.getLong("id");
        String selectfields = DynamicObjectUtil.getSelectfields("yem_im_tradeapp", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_im_tradeapp","yem_im_tradeapp_em",false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_im_tradeapp","yem_im_shipmoney_f",false);
        QFilter qFilter = new QFilter("yem_corebillid", QCP.equals, saleOrderId);
        qFilter.and(new QFilter("yem_corebilltype",QCP.equals,saleOrderType));
        qFilter = getBillStatusQFilter(qFilter,obj,flag);
        DynamicObject[] tradeApps = BusinessDataServiceHelper.load("yem_im_tradeapp", selectfields, qFilter.toArray());
        return tradeApps;
    }

    /**
     * @description 获取外销合同 -》出运明细 -》发货通知单 流程信息
     * @author xwudd
     * @param[1] saleOrders
     * @param[2] shippingDetails
     * @param[3] deliverNotices
     * return
     * @time 2023/11/16 16:41
     */

    public static Map<DynamicObject,Map<DynamicObject, List<DynamicObject>>> getOrderFlowPath (DynamicObject saleOrder,DynamicObject[] shippingDetails,DynamicObject[] deliverNotices){
        Map<DynamicObject,Map<DynamicObject, List<DynamicObject>>> saleMap = new HashMap();
        Map<DynamicObject, List<DynamicObject>> shipMap = new HashMap<>();
        saleMap.put(saleOrder,shipMap);
        Set<DynamicObject> saleMapKeys = saleMap.keySet();
        for(DynamicObject shippingDetail : shippingDetails){
            long coreBillId = shippingDetail.getLong("yem_corebillid");
            for(DynamicObject saleMapKey : saleMapKeys){
                long saleId = saleMapKey.getLong("id");
                if(coreBillId == saleId){
                    shipMap = saleMap.get(saleMapKey);
                    List<DynamicObject> deliverList = new ArrayList<>();
                    shipMap.put(shippingDetail,deliverList);
                }
            }
        }

        for(DynamicObject deliverNotice : deliverNotices){
            long sourceBillId = deliverNotice.getLong("yem_sourcebillid");
            long coreBillId = deliverNotice.getLong("yem_corebillid");
            for(DynamicObject saleMapKey : saleMapKeys){
                long saleId = saleMapKey.getLong("id");
                if(coreBillId == saleId){
                    shipMap = saleMap.get(saleMapKey);
                    Set<DynamicObject> shipMapKeys = shipMap.keySet();
                    for(DynamicObject shipMapKey : shipMapKeys){
                        long shipId = shipMapKey.getLong("id");
                        if(sourceBillId == shipId){
                            List<DynamicObject> deliverList = shipMap.get(shipMapKey);
                            deliverList.add(deliverNotice);
                        }
                    }
                }
            }
        }
        return saleMap;
    }


    /**
     * @description 判断合同是否是信用证合同
     * @author xwudd
     * @param[1] saleOrder
     * return
     * @time 2023/11/21 16:45
     */

    public static Boolean isCreditContract(DynamicObject saleOrder){
        DynamicObjectCollection paymentPlans = saleOrder.getDynamicObjectCollection("yem_es_salescontrac_s");
        for(DynamicObject paymentPlan : paymentPlans){
            DynamicObject rapStyle = paymentPlan.getDynamicObject("yem_rapstyle");
            if(YEM.isNotEmpty(rapStyle)){
                String number = rapStyle.getString("number");
                if("L/C".equals(number) || "JSFS08".equals(number)){
                    return true;
                }
            }
        }
        return false;
    }

    public static BigDecimal gaugeOutfitSum(DynamicObject[] objs,String fieldKey){
        BigDecimal sum = BigDecimal.ZERO;
        for(DynamicObject obj : objs){
            sum = sum.add(obj.getBigDecimal(fieldKey));
        }
        return sum;
    }


    public static QFilter getBillStatusQFilter(QFilter qFilter,DynamicObject obj,String flag){
        String name = obj.getDynamicObjectType().getName();
        if("yem_es_salesorder".equals(name) || "yem_es_exportpresent".equals(name)){
            qFilter.and(new QFilter("billstatus",QCP.equals,"C"));
        }else{
            if("A".equals(flag)){
                qFilter.and(new QFilter("billstatus",QCP.equals,"C"));
            }
            if("B".equals(flag)){
                qFilter.and(new QFilter("billstatus",QCP.in,new String[]{"B","C"}));
            }
        }
        return qFilter;
    }


    /**
     * @description 获取本次出运/发货金额
     * @author xwudd
     * @param[1] obj
     * return
     * @time 2023/11/20 11:27
     */

    public static BigDecimal getThisAmt(DynamicObject obj){
        BigDecimal amt = BigDecimal.ZERO;
        String name = obj.getDynamicObjectType().getName();
        if("yem_shippingdetails".equals(name)){
            amt = obj.getBigDecimal("yem_offeramount");
        }
        if("yem_es_delivernotice".equals(name)){
            amt = obj.getBigDecimal("yem_totalallamount");
        }
        return amt;
    }

    /**
     * 根据发运明细单查询  本次发货金额
     * @param shippingdetails
     * @return
     */
    private static BigDecimal getThisShipAmt(DynamicObject shippingdetails)
    {
        BigDecimal amt = BigDecimal.ZERO;
        String name = shippingdetails.getDynamicObjectType().getName();
        if(!"yem_shippingdetails".equals(name)){
            return amt;
        }
        Long pkValue = (Long) shippingdetails.getPkValue();
        QFilter qFilter = new QFilter("yem_sourcebillid", QCP.equals, pkValue);
        qFilter.and(new QFilter("billstatus", QCP.equals, "C"));
        // 销售出库单
        DynamicObject[] delivernotices = BusinessDataServiceHelper.load("yem_es_delivernotice", "id, billno, yem_totalallamount", qFilter.toArray());
        for (DynamicObject delivernotice : delivernotices) {
            amt = amt.add(getThisAmt(delivernotice));
        }
        return amt;
    }

    /**
     * @description
     * @author xwudd
     * @param[1] amt
     * return
     * @time 2023/11/20 11:49
     */

    public static BigDecimal getAbs(BigDecimal amt){
        if(amt.compareTo(BigDecimal.ZERO) < 0){
            return amt.abs();
        }else{
            return BigDecimal.ZERO;
        }
    }



    public static BigDecimal getAllBalancePayment(DynamicObject[] entitys,DynamicObject obj,String fieldKeys){
        if (obj == null) return BigDecimal.ZERO;
        long id = obj.getLong("id");
        BigDecimal offerAmount = BigDecimal.ZERO;
        for(DynamicObject entity : entitys){
            Long shippingDetailId = entity.getLong("id");
            if(!shippingDetailId.equals(id)){
                offerAmount = offerAmount.add(entity.getBigDecimal(fieldKeys));
            }
        }
        return offerAmount;
    }

    private static BigDecimal getNewAllDeliverPayment(DynamicObject[] shippingDetails)
    {
        BigDecimal amt = BigDecimal.ZERO;
        for (DynamicObject shippingDetail : shippingDetails) {
            QFilter qFilter = new QFilter("yem_sourcebillid", QCP.equals, shippingDetail.getLong("id"));
            getBillStatusQFilter(qFilter,shippingDetail,"B");
            DynamicObject[] delivernotices = BusinessDataServiceHelper.load("yem_es_delivernotice", "id, billno, yem_totalallamount", qFilter.toArray());
            BigDecimal allDeliverPayment = PaymentControlUtil.getAllDeliverPayment(delivernotices);
            amt = amt.add(allDeliverPayment);
        }
        return amt;
    }

    /**
     * @description 打开动态表单
     * @author xwudd
     * @param[1] formId 表单标识
     * @param[2] map 传参     无参传null
     * @param[3] view
     * return
     * @time 2023/8/29 11:19
     */

    public static void viewForm(String formId, Map<String,Object> map, IFormView view){
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId(formId);
        formShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        if(YEM.isNotEmpty(map)){
            formShowParameter.setCustomParams(map);
        }
        view.showForm(formShowParameter);
    }
}
