package com.yem.wm.fm.gathering.from;

import com.alibaba.druid.util.StringUtils;
import com.yem.or.utils.OrderApiUtils;
import com.yem.wm.im.debcrednotenew.utils.DebCredUtils;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.form.*;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.RefBillEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.mvc.bill.BillView;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author power
 * @ClassName 收款单 yem_gathering
 * @description: 收款单表单插件
 * @date 2023/8/18
 */
public class GatheringEcit extends AbstractBillPlugIn implements BeforeF7SelectListener {
//    @Override
//    public void afterCreateNewData(EventObject e) {
//        setBillType();
//    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setBillType();
        lockContractCustomer();
        setDefaultFinancialOrg();
    }

    /**
     * 公司为英轩重工时，财务组织默认等于国际事业部
     */
    private void setDefaultFinancialOrg() {
        IDataModel model = this.getModel();
        DynamicObject org = (DynamicObject) model.getValue("org");
        if (YEM.isNotEmpty(org) && "110".equals(org.getString("number"))) {
            model.setValue("yem_org", BusinessDataServiceHelper.loadSingle("bos_org", "id", new QFilter[]{new QFilter("number", "=", "116")}));
        }
    }

    /**
     * 2、收款单-业务登记，如果存在认领明细，真实合同客户锁定，不可编辑；
     */
    private void lockContractCustomer() {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        int rowCount = 0;
        DynamicObjectCollection claimdetail = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
        for (DynamicObject dynamicObject : claimdetail) {
            DynamicObjectCollection receiptdetail = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
            rowCount += receiptdetail.size();
        }

        if (rowCount > 0) {
            view.setEnable(false, "yem_comegoman");
        } else {
            view.setEnable(true, "yem_comegoman");
        }
    }

    @Override
    public void registerListener(EventObject e) {
        RefBillEdit billAskFor = this.getControl("yem_salcontractno");
        billAskFor.addBeforeF7SelectListener(this);
//        EntryGrid detailedInfor = this.getControl("yem_salcontractno");
//        detailedInfor.addHyperClickListener((HyperLinkClickListener) this);
        RefBillEdit shippingDetailsNo = this.getControl("yem_shippingdetailsno");
        shippingDetailsNo.addBeforeF7SelectListener(this);
        RefBillEdit tradeappnum = this.getControl("yem_tradeappnum");
        if (tradeappnum != null) {
            tradeappnum.addBeforeF7SelectListener(this);
        }
    }


    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        filtersalcontractno(e);
        String name = e.getProperty().getName();
        int row = e.getRow();
        switch (name) {
            case "yem_shippingdetailsno":
                selectF7ShippingDetails(e, row);
                break;
            case "yem_tradeappnum":
                selectF7TradeappNum(e);
            default:
                break;
        }
    }

    private void selectF7TradeappNum(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        long comegoman = dataEntity.getLong("yem_comegoman.id");
        if (YEM.isNotEmpty(comegoman)) {
            e.addCustomQFilter(new QFilter("yem_client.id", QCP.equals, comegoman));
        }
        e.addCustomQFilter(new QFilter("yem_remainunwamount", QCP.not_equals, 0));
        e.addCustomQFilter(new QFilter("yem_remainunwamount", QCP.large_than, 0));
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        ChangeData cd = e.getChangeSet()[0];
        ChangeData[] changeData = e.getChangeSet();
        int row = changeData[0].getRowIndex();
        lockContractCustomer();
        switch (name) {
            case "yem_claimamt":
                addAmount(this.getModel());
                this.claimamtcount();
                ifclaimamt(row);
                calcConversionRate(row);
                break;
            case "yem_moneynature":
            case "yem_moneytype":
                addAmount(this.getModel());
                break;
            case "yem_discountamt":
                this.cashdiscountcount();
                break;
            case "yem_salcontractno":
                this.salcontractnoCarry(row, this.getModel());
                break;
            case "yem_sumreceivableamt":
            case "yem_sumclaimamt":
                this.claimstate();
                break;
            case "yem_shippingdetailsno":
                this.setShipAmt(row, this.getModel());
                break;
            case "yem_receivableamt":
                this.claimamtcount();
                break;
            case "yem_tradeappnum":
                carryTradeappnum(row);
                break;
            case "yem_iouwriteoffamo":
                checkIouwriteoffamo();
                break;
            case "yem_salcontractclaamt":
                calcConversionRate(row);
                break;
            case "yem_receiptaccount":
                bringReceiptCurrency();
                break;
            default:
                break;
        }
    }

    /**
     * 选择收款名称时，携带银行账户的币别到汇款币别字段；
     */
    private void bringReceiptCurrency() {
        IDataModel model = this.getModel();
        DynamicObject receiptaccount = (DynamicObject) model.getValue("yem_receiptaccount");
        if (receiptaccount != null) {
            DynamicObjectCollection currency = receiptaccount.getDynamicObjectCollection("currency");
            if (currency != null && !currency.isEmpty()) {
                model.setValue("yem_receivepayment", currency.get(0).getDynamicObject("fbasedataid"));
            }
        } else {
            model.setValue("yem_receivepayment", null);
        }
    }

    /**
     * 转换率
     *
     * @param row
     */
    private void calcConversionRate(int row) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        int rowIndex = model.getEntryCurrentRowIndex("yem_receiptdetail");
        DynamicObject dynamicObject = dataEntity.getDynamicObjectCollection("yem_receiptdetail").get(rowIndex).getDynamicObjectCollection("yem_claimdetail").get(row);
        BigDecimal claimamt = dynamicObject.getBigDecimal("yem_claimamt");
        BigDecimal discountamt = dynamicObject.getBigDecimal("yem_salcontractclaamt");
        if (claimamt.compareTo(BigDecimal.ZERO) == 0) {
            model.setValue("yem_conversionrate", BigDecimal.ZERO, row);
        } else {
            model.setValue("yem_conversionrate", discountamt.divide(claimamt, 4, RoundingMode.HALF_UP), row);
        }
    }

    /**
     * 检查欠条核销金额是否超过欠条金额
     */
    private void checkIouwriteoffamo() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_iouswriteoff");
        for (DynamicObject dynamicObject : collection) {
            int rowIdx = collection.indexOf(dynamicObject);
            BigDecimal unwriteoffamount = dynamicObject.getBigDecimal("yem_unwriteoffamount");
            BigDecimal iouwriteoffamo = dynamicObject.getBigDecimal("yem_iouwriteoffamo");
            if (iouwriteoffamo.compareTo(unwriteoffamount) > 0) {
                this.getView().showErrorNotification("收款欠条核销第 " + (rowIdx + 1) + " 行,欠条核销金额不能超过欠条剩余未核销金额!");
                this.getModel().setValue("yem_iouwriteoffamo", BigDecimal.ZERO, rowIdx);
            }
        }
    }

    /**
     * 本次发运对应的应申请欠条金额
     *
     * @param row
     */
    private void carryTradeappnum(int row) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_iouswriteoff");
        DynamicObject dynamicObject = collection.get(row);
        DynamicObject tradeappnum = dynamicObject.getDynamicObject("yem_tradeappnum");
        if (tradeappnum == null) {
            model.setValue("yem_iouamount", null, row);
            model.setValue("yem_ioudate", null, row);
            model.setValue("yem_iouamountcurr", null, row);
            model.setValue("yem_unwriteoffamount", null, row);
            return;
        }

        tradeappnum = BusinessDataServiceHelper.loadSingle(tradeappnum.getPkValue(), tradeappnum.getDynamicObjectType().getName());
        model.setValue("yem_iouamount", tradeappnum.getBigDecimal("yem_thisshipiouamt"), row);
        model.setValue("yem_ioudate", tradeappnum.getDate("yem_bizdate"), row);
        model.setValue("yem_iouamountcurr", tradeappnum.getLong("yem_currency.id"), row);
        model.setValue("yem_unwriteoffamount", tradeappnum.getBigDecimal("yem_remainunwamount"), row);

    }

    /**
     * //将认领明细中的所有金额，按照款项性质+款项类型金额合并汇总(收款单-业务登记）
     */

    private void addAmount(IDataModel model) {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");
        HashMap<String, List<BigDecimal>> datas = new LinkedHashMap<>();
        if (yemBilltype != null) {
            String billtype = yemBilltype.getString("number");
            if ("yem_gathering_BJ".equals(billtype)) {
                DynamicObjectCollection yem_receiptdetail = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
                for (DynamicObject receiptdetail : yem_receiptdetail) {
                    DynamicObjectCollection claimdetail = receiptdetail.getDynamicObjectCollection("yem_claimdetail");
                    for (DynamicObject temp : claimdetail) {
                        String string = temp.getString("yem_moneynature");
                        long aLong = temp.getLong("yem_moneytype.id");
                        BigDecimal yemClaimamt = temp.getBigDecimal("yem_claimamt");
                        String key = string + "分隔" + aLong;
                        List<BigDecimal> list = new ArrayList<BigDecimal>();
                        if (string != null && aLong != 0 && !datas.containsKey(key)) {
                            list.add(yemClaimamt);
                            datas.put(key, list);
                        } else if (datas.containsKey(key)) {
                            List<BigDecimal> newList = datas.get(key);
                            newList.add(yemClaimamt);
                            datas.put(key, newList);
                        }
                    }
                }
                model.deleteEntryData("yem_receiptdetailtotal");
                for (String str : datas.keySet()) {
                    List<BigDecimal> bigDecimals = datas.get(str);
                    BigDecimal count = BigDecimal.ZERO;
                    for (BigDecimal dc : bigDecimals) {
                        count = count.add(dc);
                    }
                    String[] split = str.split("分隔");
                    int yemReceiptdetailtotal = model.createNewEntryRow("yem_receiptdetailtotal");
                    model.setValue("yem_claimamttl", count, yemReceiptdetailtotal);
                    model.setValue("yem_moneynaturetl", split[0], yemReceiptdetailtotal);
                    model.setValue("yem_moneytypetl", Long.valueOf(split[1]), yemReceiptdetailtotal);
                    model.setValue("yem_receiptusetl", findUseId(split[0], Long.valueOf(split[1])), yemReceiptdetailtotal);
                }
            }
        }
    }

    /**
     * 款项性质+款项类型 两个条件从认领明细中找到第一个收款用途
     */
    public long findUseId(String nature, long type) {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_receiptdetail = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
        for (DynamicObject dt : yem_receiptdetail) {
            DynamicObjectCollection yem_claimdetail = dt.getDynamicObjectCollection("yem_claimdetail");
            for (DynamicObject dc : yem_claimdetail) {
                String string = dc.getString("yem_moneynature");
                long aLong = dc.getLong("yem_moneytype.id");
                if (YEM.isNotEmpty(nature) && YEM.isNotEmpty(type) && nature.equals(string) && type == aLong) {
                    return dc.getLong("yem_receiptuse.id");
                }
            }
        }
        return -1;
    }

    /**
     * 删除单据体触发 子分录 申请金额 汇总拆分费用合计
     */
    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        //通过单据体行删除事件来触发


        String entryName = e.getEntryProp().getName();
        if ("yem_claimdetail".equals(entryName)) {
            cashdiscountcount();
            claimamtcount();
        }
    }


    /**
     * 子分录 认领金额  汇总收款明细 合计
     */
    private void claimamtcount() {
//        DynamicObject billtype = (DynamicObject) this.getView().getModel().getValue("yem_billtype");
//        String billtypenum = billtype.getString("number");
        //目标单单据体数据
        EntryGrid entry = this.getControl("yem_claimdetail");
        //合计单据体的认领金额字段
        BigDecimal sumreceivableamt = entry.getSum("yem_claimamt");
        BigDecimal sumreceivableamtbase = entry.getSum("yem_claimamtbase");
        //设置合计字段到单据头的总金额字段(kded_amount)
        this.getModel().setValue("yem_claimamt_a", sumreceivableamt);
        this.getModel().setValue("yem_claimamtbase_a", sumreceivableamtbase);

        BigDecimal receivableamt = (BigDecimal) this.getModel().getValue("yem_receivableamt");
        if (sumreceivableamt.compareTo(BigDecimal.ZERO) == 0) {
            this.getModel().setValue("yem_claimstate_a", "A");
        }
        if (sumreceivableamt.compareTo(BigDecimal.ZERO) != 0 && sumreceivableamt.compareTo(receivableamt) == -1) {
            this.getModel().setValue("yem_claimstate_a", "B");
        }
        if (sumreceivableamt.compareTo(receivableamt) == 0) {
            this.getModel().setValue("yem_claimstate_a", "C");
        }
    }

    /**
     * 认领金额值 不能超过父分录的应收金额
     */
    private void ifclaimamt(int row) {
        //目标单单据体数据
        EntryGrid entry = this.getControl("yem_claimdetail");
        //合计单据体的认领金额字段
        BigDecimal sumreceivableamt = entry.getSum("yem_claimamt");
        BigDecimal sumreceivableamtbase = entry.getSum("yem_claimamtbase");
        //设置合计字段到单据头的总金额字段(kded_amount)
        this.getModel().setValue("yem_claimamt_a", sumreceivableamt);
        this.getModel().setValue("yem_claimamtbase_a", sumreceivableamtbase);

        BigDecimal receivableamt = (BigDecimal) this.getModel().getValue("yem_receivableamt");
        if (sumreceivableamt.compareTo(receivableamt) == 1) {
            this.getView().showErrorNotification("您输入的认领金额已经超过收款明细的应收金额，请重新输入");
            this.getModel().setValue("yem_claimamt", BigDecimal.ZERO, row);
            this.getModel().setValue("yem_claimamtbase", BigDecimal.ZERO, row);
        }
    }

    /**
     * 子分录 现金折扣 汇总拆分费用合计
     */
    private void cashdiscountcount() {
        //目标单单据体数据
        EntryGrid entry = this.getControl("yem_claimdetail");
        //合计单据体的金额字段
        BigDecimal discountamt = entry.getSum("yem_discountamt");
        BigDecimal discountamtbase = entry.getSum("yem_discountamtbase");
        //设置合计字段到单据头的总金额字段(kded_amount)
        this.getModel().setValue("yem_cashdiscount", discountamt);
        this.getModel().setValue("yem_cashdiscountbase", discountamtbase);
    }

    /**
     * @Description 根据布局给单据类型
     */
    public void setBillType() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        FormShowParameter fsp = this.getView().getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        String key = ((BillView) this.getView()).getRootControl().getKey();
        QFilter qFilter = null;
        if (OperationStatus.ADDNEW == status) {
            if (key.equals("yem_gathering_cw")) {
                qFilter = new QFilter("number", QCP.equals, "yem_gathering_BJ");
            }
            if (qFilter != null) {
                DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
                model.setValue("yem_billtype", billType);
            }
        }
    }

    /**
     * 合同号 带出 款项类型 业务员 单据类型 合同金额 部门
     */
    public void salcontractnoCarry(int row, IDataModel model) {
        DynamicObject salcontract = (DynamicObject) model.getValue("yem_salcontractno", row);
        if (salcontract != null) {
            Long salcontractno = (Long) salcontract.get("id");
            DynamicObject salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder",
                    "yem_billtypetext,yem_operator,yem_bd_products,yem_offeramount,yem_offerstandardcoin," +
                            "yem_billtype,yem_currency,yem_department",
                    new QFilter[]{new QFilter("yem_es_salesorder.id", QCP.equals, salcontractno),});
            String billtypetext = salesorder.getString("yem_billtype.number");
            DynamicObject operator = salesorder.getDynamicObject("yem_operator");
            DynamicObject products = salesorder.getDynamicObject("yem_bd_products");
            BigDecimal offeramount = salesorder.getBigDecimal("yem_offeramount");
            BigDecimal offerstandardcoin = salesorder.getBigDecimal("yem_offerstandardcoin");
            Long currency = salesorder.getLong("yem_currency.id");
            Long department = salesorder.getLong("yem_department.id");


            if ("yem_es_salesorder_PJ".equals(billtypetext)) {
                model.setValue("yem_billtype_b", "PJHT", row);
            }
            if ("yem_es_salesorder_ZJ".equals(billtypetext)) {
                model.setValue("yem_billtype_b", "ZJHT", row);
            }
//           this.getModel().setValue("yem_billtype_b",billtypetext,row);
            model.setValue("yem_operator_b", operator, row);
            model.setValue("yem_productclassify", products, row);
            model.setValue("yem_salcontractamt", offeramount, row);
            model.setValue("yem_contractamtbase", offerstandardcoin, row);
            model.setValue("yem_contractrelevcuy", currency, row);

            model.setValue("yem_department_b", department, row);


        }
    }

    /**
     * 保存操作完成后执行 刷新操作
     */
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);

        if (StringUtils.equals("save", operateKey)) {
            OperationResult opResult = e.getOperationResult();
            if (opResult != null && opResult.isSuccess()) {

                writeBackToradeapp(dataEntity);

                this.getView().invokeOperation("refresh");
            }
        }

        if (StringUtils.equals("rejection", operateKey)) {
            OperationResult opResult = e.getOperationResult();
            if (opResult != null && opResult.isSuccess()) {
                model.setValue("yem_financeaffirm", "C");
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                this.getView().updateView("yem_financeaffirm");
            }
        }


//        if("rejection".equals(operateKey)){
//
//            String financeaffirm = (String) this.getModel().getValue("yem_financeaffirm");
//            if("B".equals(financeaffirm)){
//                throw  new KDBizException("财务状态为财务确认，无法进行驳回!");
//            }else {
//
//            }
//
//        }
//        if("unaudit".equals(operateKey)){
//            String yem_financeaffirm = (String) this.getModel().getValue("yem_financeaffirm");
//            if("B".equals(yem_financeaffirm)){
//                throw  new KDBizException("财务状态为财务确认，无法进行反审核!");
//            }
//        }

        if (StringUtils.equals("submit", operateKey)) {
            OperationResult opResult = e.getOperationResult();
            if (opResult != null && opResult.isSuccess()) {
                model.setValue("yem_financeaffirm", "A");
            }
        }

        if ("test_sync_status".equals(operateKey)) {
//            orderplat(1951608220288057344L, null);
        }
    }

    /**
     * 欠条核销金额 反写 国贸贷款欠条申请
     *
     * @param dataEntity
     */
    private void writeBackToradeapp(DynamicObject dataEntity) {
        long id = dataEntity.getLong("id");
        // 收款欠条核销
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_iouswriteoff");
        if (collection.isEmpty()) {
            QFilter qFilter = new QFilter("yem_debtwriteoffamo.yem_invoicenuma.id", QCP.equals, id);
            DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_im_tradeapp", qFilter.toArray());
            if (single == null) return;
            DynamicObjectCollection debtwriteoffamo = single.getDynamicObjectCollection("yem_debtwriteoffamo");
            List<Integer> list = new ArrayList<>();
            for (DynamicObject dynamicObject : debtwriteoffamo) {
                if (YEM.isNotEmpty(id) && id == dynamicObject.getLong("yem_invoicenuma.id")) {
                    int index = debtwriteoffamo.indexOf(dynamicObject);
                    list.add(index);
                }
            }
            Collections.reverse(list);
            for (Integer i : list) {
                debtwriteoffamo.remove(debtwriteoffamo.get(i));
            }
            calcRemainunwamount(single);
            SaveServiceHelper.save(new DynamicObject[]{single});
        }

        for (DynamicObject dynamicObject : collection) {
            DynamicObject bill = dynamicObject.getDynamicObject("yem_tradeappnum");
            if (bill == null) continue;
            DynamicObject single = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
            if (single == null) continue;

            // 收款核销分录
            DynamicObjectCollection debtwriteoffamo = single.getDynamicObjectCollection("yem_debtwriteoffamo");
            Set<Integer> set = new LinkedHashSet<>();
            for (DynamicObject object : debtwriteoffamo) {
                DynamicObject invoicenuma = object.getDynamicObject("yem_invoicenuma");
                if (invoicenuma == null) continue;
                if (invoicenuma.getLong("id") == id) {
                    int index = debtwriteoffamo.indexOf(object);
                    set.add(index);
                }
            }
            List<Integer> list = new ArrayList<>(set);
            Collections.reverse(list);
            for (Integer i : list) {
                debtwriteoffamo.remove(debtwriteoffamo.get(i));
            }
            calcRemainunwamount(single);
            SaveServiceHelper.save(new DynamicObject[]{single});
        }

        for (DynamicObject dynamicObject : collection) {
            DynamicObject bill = dynamicObject.getDynamicObject("yem_tradeappnum");
            if (bill == null) continue;
            DynamicObject single = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
            if (single == null) continue;

            // 收款核销分录
            DynamicObjectCollection debtwriteoffamo = single.getDynamicObjectCollection("yem_debtwriteoffamo");
            DynamicObject addNew = debtwriteoffamo.addNew();
            addNew.set("yem_invoicenuma", dataEntity.get("id"));
            addNew.set("yem_paymentdate", dataEntity.getDate("yem_bizdate"));
            addNew.set("yem_writeoffamount", dynamicObject.get("yem_iouwriteoffamo"));
            addNew.set("yem_amountremake", dynamicObject.get("yem_iouremake"));
            calcRemainunwamount(single);
            SaveServiceHelper.save(new DynamicObject[]{single});
        }
    }

    private void calcRemainunwamount(DynamicObject single) {
        DynamicObjectCollection collection = single.getDynamicObjectCollection("yem_debtwriteoffamo");
        BigDecimal sum = BigDecimal.ZERO;
        for (DynamicObject dynamicObject : collection) {
            BigDecimal writeoffamount = dynamicObject.getBigDecimal("yem_writeoffamount");
            sum = sum.add(writeoffamount);
        }
        single.set("yem_writtenoffamount", sum);
        single.set("yem_remainunwamount", single.getBigDecimal("yem_thisshipiouamt").subtract(sum));
    }


    /**
     * 根据真实客户过滤 过滤合同号字段
     */

    public void filtersalcontractno(BeforeF7SelectEvent e) {
        DynamicObject datas = this.getModel().getDataEntity(true);
        Control control = (Control) e.getSource();
        String key = control.getKey();
        if ("yem_salcontractno".equals(key)) {
            DynamicObject comegoman = datas.getDynamicObject("yem_comegoman");
            if (comegoman != null) {
                Long id = comegoman.getLong("id");

                QFilter qFilter = new QFilter("yem_customer.id", QCP.equals, id);
                e.addCustomQFilter(qFilter);
            }
        }
    }

    /**
     * 认领状态
     * 如果认领金额等于应收金额，置为认领完成，认领金额大于0且小于应收金额，就置为部分认领，如果认领金额为0
     */
    public void claimstate() {
        BigDecimal sumreceivableamt = (BigDecimal) this.getModel().getValue("yem_sumreceivableamt");
        BigDecimal sumclaimamt = (BigDecimal) this.getModel().getValue("yem_sumclaimamt");
        if (sumreceivableamt.compareTo(sumclaimamt) == 0) {
            this.getModel().setValue("yem_claimstate", "C");
        }
        if (sumclaimamt.compareTo(BigDecimal.ZERO) == 1 && sumclaimamt.compareTo(sumreceivableamt) == -1) {
            this.getModel().setValue("yem_claimstate", "B");
        }
        if (sumclaimamt.compareTo(BigDecimal.ZERO) == 0) {
            this.getModel().setValue("yem_claimstate", "A");
        }
    }

    /**
     * @description 选择出运明细号带出出运金额
     * @author xwudd
     * @param[1] rowIndex
     * return
     * @time 2023/11/6 16:20
     */

    public void setShipAmt(int rowIndex, IDataModel model) {
        DynamicObject shippingDetailsNo = (DynamicObject) model.getValue("yem_shippingdetailsno", rowIndex);
        if (YEM.isNotEmpty(shippingDetailsNo)) {
            shippingDetailsNo = BusinessDataServiceHelper.loadSingle(shippingDetailsNo.getPkValue(), shippingDetailsNo.getDynamicObjectType().getName());
            model.setValue("yem_shipamt", shippingDetailsNo.getBigDecimal("yem_offeramount"), rowIndex);
        } else {
            model.setValue("yem_shipamt", BigDecimal.ZERO, rowIndex);
        }
    }

    public void selectF7ShippingDetails(BeforeF7SelectEvent e, int row) {
        IDataModel model = this.getModel();
        DynamicObject salContractNo = (DynamicObject) model.getValue("yem_salcontractno", row);
        if (YEM.isNotEmpty(salContractNo)) {
            List<Long> ids = new ArrayList<>();
            DynamicObject[] shippingDetails = BusinessDataServiceHelper.load("yem_shippingdetails", "id",
                    new QFilter[]{new QFilter("yem_sourcebilltype", QCP.equals, salContractNo.getDynamicObjectType().getName()),
                            new QFilter("yem_sourcebillid", QCP.equals, salContractNo.getPkValue())});
            for (DynamicObject shippingDetail : shippingDetails) {
                ids.add(shippingDetail.getLong("id"));
            }
            e.addCustomQFilter(new QFilter("id", QCP.in, ids));
        } else {
            e.addCustomQFilter(new QFilter("id", QCP.equals, 0L));
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String operateKey = operate.getOperateKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IPageCache pageCache = this.getPageCache();

        boolean dataChanged = model.getDataChanged();
        String pageId = dataEntity.getDynamicObjectType().getName();
        String[] noCheck = new String[]{"save", "delete", "refresh", "close", "modify", "new", "newentrya1", "copyentryrowa", "insertentrya", "deleteentrya1", "batchfillentrya", "newentryb", "insertentryb", "copyentryrowb", "deleteentryb", "batchfillentryb"};

        if (dataChanged && !Arrays.asList(noCheck).contains(operateKey) && ("yem_gathering".equals(pageId) || "yem_gathering_cw".equals(pageId))) {
            throw new KDBizException("检测到单据内容更新，请保存后再进行操作！");
        }

        if ("claim".equals(operateKey) || "changeclaim".equals(operateKey)) {
            EntryGrid receiptdetail = this.getControl("yem_receiptdetail");
            int[] selectRows = receiptdetail.getSelectRows();
            if ("claim".equals(operateKey)) {
                if (selectRows.length == 0) {
                    view.showErrorNotification("请选择要认领的收款明细行!");
                    args.setCancel(true);
                    return;
                }
                if (selectRows.length > 1) {
                    view.showErrorNotification("只能选择一行收款明细行进行认领!");
                    args.setCancel(true);
                    return;
                }
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
                String claimstate = collection.get(selectRows[0]).getString("yem_claimstate_a");
                if ("C".equals(claimstate)) {
                    view.showErrorNotification("当行已认领完成，不能重复认领!");
                    args.setCancel(true);
                    return;
                }
            }
            EntryGrid claimdetail = this.getControl("yem_claimdetail");
            int[] selectSubRows = claimdetail.getSelectRows();
            if ("changeclaim".equals(operateKey)) {
                if (selectSubRows.length == 0) {
                    view.showErrorNotification("请选择要修改认领的认领明细行!");
                    args.setCancel(true);
                    return;
                }
                if (selectSubRows.length > 1) {
                    view.showErrorNotification("只能选择一行认领明细进行修改认领!");
                    args.setCancel(true);
                    return;
                }
                int rowIndex = model.getEntryCurrentRowIndex("yem_receiptdetail");
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
                DynamicObject dynamicObject = collection.get(rowIndex);
                DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
                int selectSubRow = selectSubRows[0];
                DynamicObject subObject = subCollection.get(selectSubRow);
                //查询是否生成贷记单
                DynamicObject yem_salcontractno = subObject.getDynamicObject("yem_salcontractno");
                if (yem_salcontractno != null) {
                    String billno = yem_salcontractno.getString("billno");
//                    QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
//                    qFilter.and(new QFilter("yem_creditnotesource.yem_contractno_s.id", QCP.equals, yem_salcontractno.getLong("id")));
                    QFilter qFilter1 = new QFilter("yem_sourcebillno", QCP.equals, billno);
                    qFilter1.and(new QFilter("yem_partscredit", QCP.equals, "C"));
                    qFilter1.or(new QFilter("yem_creditnotesource.yem_contractno_s.id", QCP.equals, yem_salcontractno.getLong("id")));
//                    DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_debcrednote", "id", qFilter1.toArray());
                    DynamicObjectCollection data = QueryServiceHelper.query("yem_debcrednote", "id,billno", new QFilter[]{qFilter1}, null);
                    if (data.size() > 0) {
                        List list = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {
                            DynamicObject object = data.get(i);
                            String fbillno = object.getString("billno");
                            list.add(fbillno);
                        }
                        if (list.size() > 0) {
                            String err = "选择行合同号【" + billno + "】已存在贷记单【" + DebCredUtils.dedupAndJoin(list, ";") + "】，禁止修改！";
                            view.showErrorNotification(err);
                            return;
                        }
                    }
                }
                DynamicObject claimman = subObject.getDynamicObject("yem_claimman");
                if (claimman == null) return;
                if (claimman.getLong("id") != YEM.getCurrentUserId()) {
                    view.showErrorNotification("认领人不是当前用户，不允许修改");
                    return;
                }

            }
            FormShowParameter parameter = new FormShowParameter();
            parameter.setStatus(OperationStatus.ADDNEW);
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            parameter.setFormId("yem_gathering_claim");
            parameter.setCustomParam("opType", operateKey);
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_gathering_claim"));
            view.showForm(parameter);
        }

        if ("deleteentrya1".equals(operateKey)) {
            Map<String, Long> salcontractnomap = new HashMap<>();
            Map<String, List> map = new HashMap<>();
            List deletelist = new ArrayList<>();
            List undeletelist = new ArrayList<>();
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
            EntryGrid claimdetail = this.getControl("yem_receiptdetail");
            int[] selectSubRows = claimdetail.getSelectRows();
            for (int row : selectSubRows) {
                DynamicObject dynamicObject = collection.get(row);
                DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
                for (int i = 0; i < subCollection.size(); i++) {
                    DynamicObject subObject = subCollection.get(i);
                    DynamicObject yem_salcontractno = subObject.getDynamicObject("yem_salcontractno");
                    if (yem_salcontractno != null) {
                        String billno = yem_salcontractno.getString("billno");
                        long id = yem_salcontractno.getLong("id");
                        if (!salcontractnomap.containsKey(billno)) {
                            salcontractnomap.put(billno, id);
                        }
                    }
                }
            }
            //查询是否生成贷记单
            if (salcontractnomap.size() > 0) {
                for (String key : salcontractnomap.keySet()) {
                    Long aLong = salcontractnomap.get(key);
                    QFilter qFilter = new QFilter("yem_creditnotesource.yem_contractno_s.id", QCP.equals, aLong);
                    DynamicObjectCollection data = QueryServiceHelper.query("yem_debcrednote", "id,billstatus,billno", new QFilter[]{qFilter}, null);
                    if (data.size() > 0) {
                        List list = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {
                            DynamicObject object = data.get(i);
                            String billstatus = object.getString("billstatus");
                            if (billstatus.equals("C")) {
                                String fbillno = object.getString("billno");
                                list.add(fbillno);
                                undeletelist.add(fbillno);
                            } else {
                                long id = object.getLong("id");
                                deletelist.add(id);
                            }
                        }
                        map.put(key, list);
                    }
                }
            }
            if (undeletelist.size() > 0 && map.size() > 0) {
                StringBuffer err = new StringBuffer();
                for (String key : map.keySet()) {
                    List list = map.get(key);
                    if (list.size() > 0) {
                        err.append("选择行【" + key + "】已存在贷记单【" + DebCredUtils.dedupAndJoin(list, ";") + "】，禁止删除！").append("\r\n");
                    }
                }
                if (err.length() > 0) {
                    view.showErrorNotification(err.toString());
                    args.setCancel(true);
                    return;
                }
            }
            //删除
            if (undeletelist.size() == 0 && deletelist.size() > 0) {
                pageCache.put("deletelist", DebCredUtils.dedupLongAndJoin(deletelist, ";"));
                view.showConfirm("查询到当前合同号已产生贷记单，删除行后会删除对应单据，是否继续？", MessageBoxOptions.YesNo,
                        new ConfirmCallBackListener(operateKey, this));
//                args.setCancel(true);
//                deletedebcrednote(deletelist);
            }
        }
        if ("deleteentryb".equals(operateKey)) {
            List undeletelist = new ArrayList<>();
            int rowIndex = model.getEntryCurrentRowIndex("yem_receiptdetail");
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
            DynamicObject dynamicObject = collection.get(rowIndex);
            DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
            EntryGrid claimdetail = this.getControl("yem_claimdetail");
            int[] selectSubRows = claimdetail.getSelectRows();
            Map<String, Long> salcontractnomap = new HashMap<>();
            Map<String, List> map = new HashMap<>();
            List deletelist = new ArrayList<>();
            for (int row : selectSubRows) {
                DynamicObject subObject = subCollection.get(row);
                DynamicObject yem_salcontractno = subObject.getDynamicObject("yem_salcontractno");
                if (yem_salcontractno != null) {
                    String billno = yem_salcontractno.getString("billno");
                    long id = yem_salcontractno.getLong("id");
                    if (!salcontractnomap.containsKey(billno)) {
                        salcontractnomap.put(billno, id);
                    }
                }
            }
            //查询是否生成贷记单
            if (salcontractnomap.size() > 0) {
                for (String key : salcontractnomap.keySet()) {
                    Long aLong = salcontractnomap.get(key);
//                    QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
                    QFilter qFilter = new QFilter("yem_creditnotesource.yem_contractno_s.id", QCP.equals, aLong);
                    DynamicObjectCollection data = QueryServiceHelper.query("yem_debcrednote", "id,billno,billstatus", new QFilter[]{qFilter}, null);
                    if (data.size() > 0) {
                        List list = new ArrayList<>();
                        for (int i = 0; i < data.size(); i++) {
                            DynamicObject object = data.get(i);
                            String billstatus = object.getString("billstatus");
                            if (billstatus.equals("C")) {
                                String fbillno = object.getString("billno");
                                list.add(fbillno);
                                undeletelist.add(fbillno);
                            } else {
                                long id = object.getLong("id");
                                deletelist.add(id);
                            }
                        }
                        map.put(key, list);
                    }
                }
            }
            if (undeletelist.size() > 0 && map.size() > 0) {
                StringBuffer err = new StringBuffer();
                for (String key : map.keySet()) {
                    List list = map.get(key);
                    if (list.size() > 0) {
                        err.append("选择行【" + key + "】已存在贷记单【" + DebCredUtils.dedupAndJoin(list, ";") + "】，禁止删除！").append("\r\n");
                    }
                }
                if (err.length() > 0) {
                    view.showErrorNotification(err.toString());
                    args.setCancel(true);
                    return;
                }
            }
            //删除
            if (undeletelist.size() == 0 && deletelist.size() > 0) {
                deletedebcrednote(deletelist);
            }
        }

        if ("statusconvertcwqr".equals(operateKey)) {
            this.getView().invokeOperation("save");
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        if ("yem_gathering_claim".equals(actionId)) {
            addAmount(this.getModel());
            this.claimamtcount();
            deleteBlockRow();
            Map<Long, BigDecimal> map = new HashMap<>();
            DynamicObject dataEntity = model.getDataEntity(true);
            DynamicObjectCollection yem_receiptdetail = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
            for (int i = 0; i < yem_receiptdetail.size(); i++) {
                DynamicObject receiptdetail = yem_receiptdetail.get(i);
                DynamicObjectCollection yem_claimdetail = receiptdetail.getDynamicObjectCollection("yem_claimdetail");
                for (int j = 0; j < yem_claimdetail.size(); j++) {
                    DynamicObject object = yem_claimdetail.get(j);
                    BigDecimal yem_claimamt = object.getBigDecimal("yem_claimamt");

                    Object salcontractno = object.get("yem_salcontractno");
                    if (salcontractno instanceof Long) {
                        long id = object.getLong("yem_salcontractno");
                        if (!map.containsKey(id)) {
                            map.put(id, yem_claimamt);
                        } else {
                            BigDecimal bigDecimal = map.get(id);
                            map.put(id, bigDecimal.add(yem_claimamt));
                        }
                    }
                    if (salcontractno instanceof DynamicObject) {
                        DynamicObject yem_salcontractno = object.getDynamicObject("yem_salcontractno");
                        if (yem_salcontractno != null) {
                            long id = yem_salcontractno.getLong("id");
                            if (!map.containsKey(id)) {
                                map.put(id, yem_claimamt);
                            } else {
                                BigDecimal bigDecimal = map.get(id);
                                map.put(id, bigDecimal.add(yem_claimamt));
                            }
                        }
                    }
                }
            }
            view.invokeOperation("save");
            if (map.size() > 0) {
                for (long key : map.keySet()) {
                    Generatecredit(key, map.get(key));
                    orderplat(key, map.get(key));
                }
            }
        }
        view.invokeOperation("save");
        view.invokeOperation("refresh");
    }

    /**
     * 生成贷记单
     *
     * @param salcontractno 合同id
     * @param yem_claimamt
     */
    public void Generatecredit(long salcontractno, BigDecimal yem_claimamt) {
        IDataModel model = this.getModel();
        DynamicObject emp = model.getDataEntity(true);
        DynamicObject dataEntitie = BusinessDataServiceHelper.loadSingle(salcontractno, "yem_es_salesorder");
        String billno = dataEntitie.getString("billno");
        QFilter qFilter1 = new QFilter("yem_sourcebillno", QCP.equals, billno);
        qFilter1.and(new QFilter("yem_partscredit", QCP.equals, "C"));
        DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_debcrednote", "id", qFilter1.toArray());
        if (billType == null) {
            String yem_isgiftgiveparts = dataEntitie.getString("yem_isgiftgiveparts");
            String yem_partscredit = dataEntitie.getString("yem_partscredit");
            BigDecimal yem_offeramount = dataEntitie.getBigDecimal("yem_offeramount");//金额（价格条款）
            if (yem_isgiftgiveparts.equals("A") && yem_partscredit.equals("C")) {
                BigDecimal yemclaimamt = BigDecimal.ZERO;
                //查询合同已认领金额
                QFilter qFilter = new QFilter("id", QCP.not_equals, emp.getPkValue());//
                qFilter.and(new QFilter("yem_receiptdetail.yem_claimdetail.yem_salcontractno.id", QCP.equals, salcontractno));
//                qFilter.and();
                DynamicObjectCollection data = QueryServiceHelper.query("yem_gathering",
                        "id,yem_receiptdetail.yem_claimdetail.yem_salcontractno,yem_receiptdetail.yem_claimdetail.yem_salcontractclaamt yem_claimamt",
                        new QFilter[]{qFilter}, null);
                if (data.size() > 0) {
                    for (int i = 0; i < data.size(); i++) {
                        DynamicObject object = data.get(i);
                        BigDecimal claimamt = object.getBigDecimal("yem_claimamt");
                        yemclaimamt = yemclaimamt.add(claimamt);
                    }
                }
                yemclaimamt = yem_claimamt.add(yemclaimamt);
                if (yem_offeramount.compareTo(yemclaimamt) == 0) {
                    //产生贷记单
                    DynamicObject debcrednote = DebCredUtils.AddSKDGenerate(dataEntitie, emp.getString("billno"));
                    OperationResult Operate = OperationServiceHelper.executeOperate("save", debcrednote.getDynamicObjectType().getName(), new DynamicObject[]{debcrednote}, OperateOption.create());
                    if (Operate.isSuccess()) {
                        OperationResult submitResult = OperationServiceHelper.executeOperate("submit", "yem_debcrednote", new Object[]{debcrednote.getPkValue()}, OperateOption.create());
                        if (submitResult.isSuccess()) {
                            OperationResult auditResult = OperationServiceHelper.executeOperate("audit", "yem_debcrednote", new Object[]{debcrednote.getPkValue()}, OperateOption.create());
                            if (auditResult.isSuccess()) {

                            } else {
                                List<IOperateInfo> allErrorOrValidateInfo = auditResult.getAllErrorOrValidateInfo();
                                String message = auditResult.getMessage();
                                throw new KDBizException("贷记单审核失败，" + message + "，" + allErrorOrValidateInfo);
                            }
                        } else {
                            List<IOperateInfo> allErrorOrValidateInfo = submitResult.getAllErrorOrValidateInfo();
                            String message = submitResult.getMessage();
                            throw new KDBizException("贷记单提交失败，" + message + "，" + allErrorOrValidateInfo);
                        }
                    } else {
                        List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
                        String message = Operate.getMessage();
                        throw new KDBizException("贷记单保存失败，" + message + "，" + allErrorOrValidateInfo);
                    }
                }
//            }
            }
        }
    }

    private void deleteBlockRow() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
        for (DynamicObject dynamicObject : collection) {
            DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
            for (int i = subCollection.size() - 1; i >= 0; i--) {
                DynamicObject subObject = subCollection.get(i);
                BigDecimal salcontractamt = subObject.getBigDecimal("yem_claimamt");
                if (salcontractamt.compareTo(BigDecimal.ZERO) == 0) {
                    subCollection.remove(subObject);
                }
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        String callBackId = e.getCallBackId();
        MessageBoxResult result = e.getResult();
        IFormView view = (IFormView) e.getSource();
        IDataModel model = view.getModel();
        IPageCache pageCache = view.getPageCache();
        if ("deleteentrya1".equals(callBackId)) {
            if (result == MessageBoxResult.Yes) {
                List<Long> list = new ArrayList<>();
                String deletelist = pageCache.get("deletelist");
                String[] split = deletelist.split(";");
                for (int i = 0; i < split.length; i++) {
                    list.add(Long.valueOf(split[i]));
                }
                deletedebcrednote(list);
                OperationResult save = view.invokeOperation("save");
                view.invokeOperation("refresh");
            }
            if (result == MessageBoxResult.No) {
                view.invokeOperation("refresh");
                return;
            }
        }
    }

    /**
     * 删除贷记单
     *
     * @param deletelist
     */
    private void deletedebcrednote(List<Long> deletelist) {
        QFilter qFilter = new QFilter("id", QCP.in, deletelist);
        DynamicObjectCollection data = QueryServiceHelper.query("yem_debcrednote", "id,billstatus", new QFilter[]{qFilter});
        for (DynamicObject debcrednote : data) {
            long id = debcrednote.getLong("id");
            String billstatus = debcrednote.getString("billstatus");
            if (billstatus.equals("A")) {
                OperationResult delete = OperationServiceHelper.executeOperate("delete", "yem_debcrednote", new Object[]{id}, OperateOption.create());
                if (!delete.isSuccess()) {
                    String message = delete.getMessage();
                    List<IOperateInfo> allErrorOrValidateInfo = delete.getAllErrorOrValidateInfo();
                    throw new KDBizException(String.format("《借/贷记单》删除失败，%s，%s", message, allErrorOrValidateInfo));
                }
            } else {
                //反审核
                OperationResult unAudit = OperationServiceHelper.executeOperate("unaudit", "yem_debcrednote", new Object[]{id}, OperateOption.create());
                if (unAudit.isSuccess()) {
                    OperationResult delete = OperationServiceHelper.executeOperate("delete", "yem_debcrednote", new Object[]{id}, OperateOption.create());
                    if (!delete.isSuccess()) {
                        String message = delete.getMessage();
                        List<IOperateInfo> allErrorOrValidateInfo = delete.getAllErrorOrValidateInfo();
                        throw new KDBizException(String.format("《借/贷记单》删除失败，%s，%s", message, allErrorOrValidateInfo));
                    }
                } else {
                    String message = unAudit.getMessage();
                    List<IOperateInfo> allErrorOrValidateInfo = unAudit.getAllErrorOrValidateInfo();
                    throw new KDBizException(String.format("《借/贷记单》删除失败，%s，%s", message, allErrorOrValidateInfo));
                }
            }
        }
    }

    /**
     * 同步下单平台
     */
    private void orderplat(long salcontractno, BigDecimal yem_claimamt) {
        IDataModel model = this.getModel();
        DynamicObject emp = model.getDataEntity(true);
        List<Map<String, Object>> list = new ArrayList<>();
        DynamicObject dataEntitie = BusinessDataServiceHelper.loadSingle(salcontractno, "yem_es_salesorder");
        BigDecimal yem_offeramount = dataEntitie.getBigDecimal("yem_offeramount");//金额（价格条款）
        long yemSourcebillid = dataEntitie.getLong("yem_sourcebillid");//来源单据ID 客户需求单id
        BigDecimal yemclaimamt = BigDecimal.ZERO;
        //查询合同已认领金额
        QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");//
        qFilter.and(new QFilter("yem_receiptdetail.yem_claimdetail.yem_salcontractno.id", QCP.equals, salcontractno));
        DynamicObjectCollection data = QueryServiceHelper.query("yem_gathering",
                "id,yem_receiptdetail.yem_claimdetail.yem_salcontractno,yem_receiptdetail.yem_claimdetail.yem_salcontractclaamt yem_claimamt",
                new QFilter[]{qFilter}, null);
        if (data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                DynamicObject object = data.get(i);
                BigDecimal claimamt = object.getBigDecimal("yem_claimamt");
                yemclaimamt = yemclaimamt.add(claimamt);
            }
        }
//        else {
//            yemclaimamt = yem_claimamt.add(yemclaimamt);
//        }

        if (yem_offeramount.compareTo(yemclaimamt) == 0) {
            DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_im_clientdemand", "id,billno,yem_orderplatid"
                    , new QFilter[]{new QFilter("id", QCP.equals, yemSourcebillid)});
            if (single != null) {
                Map<String, Object> map = new HashMap<>();
                String yemOrderplatid = single.getString("yem_orderplatid");
                map.put("id", yemOrderplatid);
                map.put("status", "3");
                map.put("logisticsNo", "");
                map.put("ladingDate", "");
                list.add(map);
            }
        }
        OrderApiUtils.partsorderlist(list);
    }
}
