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

import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.im.debcrednotenew.utils.DebCredUtils;
import com.yem.wm.utils.YEM;
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.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
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.control.events.RowClickEventListener;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
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 java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @Description TODO
 * @Date 2024/1/17 15:23
 * @Created by ZZSLL
 */

public class GatheringClaimFormPlugin extends AbstractFormPlugin implements RowClickEventListener {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView parentView = this.getView().getParentView();
        IDataModel parentModel = parentView.getModel();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        int rowIndex = parentModel.getEntryCurrentRowIndex("yem_receiptdetail");
        int subRowIdx = parentModel.getEntryCurrentRowIndex("yem_claimdetail");
        DynamicObject dataEntity = model.getDataEntity(true);
        model.setValue("yem_receipttype_a", parentModel.getValue("yem_receipttype_a"));
        model.setValue("yem_moneytypetl_a", parentModel.getValue("yem_moneytypetl_a"));
        model.setValue("yem_receivableamt", parentModel.getValue("yem_receivableamt"));
        model.setValue("yem_receivableamtbase", parentModel.getValue("yem_receivableamtbase"));
        model.setValue("yem_remark_a", parentModel.getValue("yem_remark_a"));
        model.setValue("yem_claimamt_a", parentModel.getValue("yem_claimamt_a"));
        model.setValue("yem_claimamtbase_a", parentModel.getValue("yem_claimamtbase_a"));
        model.setValue("yem_claimstate_a", parentModel.getValue("yem_claimstate_a"));

        model.setValue("yem_currencybase", parentModel.getValue("yem_currencybase"));
        model.setValue("yem_currency", parentModel.getValue("yem_currency"));

        DynamicObject parentModelDataEntity = parentModel.getDataEntity(true);
        DynamicObject receiptdetail = parentModelDataEntity.getDynamicObjectCollection("yem_receiptdetail").get(rowIndex);
        if (receiptdetail == null) return;

        FormShowParameter formShowParameter = view.getFormShowParameter();
        String opType = formShowParameter.getCustomParam("opType");
        DynamicObjectCollection collection = receiptdetail.getDynamicObjectCollection("yem_claimdetail");
        DynamicObjectCollection claimdetail = dataEntity.getDynamicObjectCollection("yem_claimdetail");

        if ("claim".equals(opType)) {
            for (int i = 0; i < collection.size(); i++) {
                DynamicObject dynamicObject = collection.get(i);
                DynamicObject object = claimdetail.addNew();
                setEntryValue(object, dynamicObject, "from");
                view.setEnable(false, i, new String[]{"yem_remark_b", "yem_claimamt", "yem_salcontractclaamt", "yem_originid", "yem_claimdate", "yem_moneynature", "yem_moneytype", "yem_productclassify", "yem_receiptuse", "yem_operator_b", "yem_salcontractno", "yem_hidsalcontractno", "yem_billtype_b", "yem_contractrelevcuy", "yem_salcontractamt", "yem_shippingdetailsno", "yem_hidshippingdetailsno", "yem_shipamt", "yem_claimamtbase", "yem_contractamtbase", "yem_conversionrate", "yem_department_b"});
            }
            model.setValue("yem_optype", "A");

        }

        if ("changeclaim".equals(opType)) {
            DynamicObject dynamicObject = collection.get(subRowIdx);
            DynamicObject object = claimdetail.addNew();
            setEntryValue(object, dynamicObject, "from");

            view.setEnable(false, 0, new String[]{"yem_salcontractclaamt", "yem_originid", "yem_claimdate", "yem_moneynature", "yem_moneytype", "yem_productclassify", "yem_receiptuse", "yem_operator_b", "yem_salcontractno", "yem_hidsalcontractno", "yem_billtype_b", "yem_contractrelevcuy", "yem_salcontractamt", "yem_shippingdetailsno", "yem_hidshippingdetailsno", "yem_shipamt", "yem_claimamtbase", "yem_contractamtbase", "yem_conversionrate", "yem_department_b"});
            model.setValue("yem_optype", "B");
        }

        //        yem_unclaimedamo = yem_receivableamt - yem_claimamt_a
        BigDecimal receivableamt = (BigDecimal) model.getValue("yem_receivableamt");
        BigDecimal claimamtA = (BigDecimal) model.getValue("yem_claimamt_a");
        model.setValue("yem_unclaimedamo", receivableamt.subtract(claimamtA));
    }

    private void setEntryValue(DynamicObject object, DynamicObject dynamicObject, String type) {
        object.set("yem_claimman", dynamicObject.get("yem_claimman"));
        object.set("yem_claimdate", dynamicObject.get("yem_claimdate"));
        object.set("yem_moneynature", dynamicObject.get("yem_moneynature"));
        object.set("yem_moneytype", dynamicObject.get("yem_moneytype"));
        object.set("yem_productclassify", dynamicObject.get("yem_productclassify"));
        object.set("yem_receiptuse", dynamicObject.get("yem_receiptuse"));
        object.set("yem_operator_b", dynamicObject.get("yem_operator_b"));
        long salcontractnoid = 0l;
        if ("from".equals(type)) {
            object.set("yem_originid", dynamicObject.getPkValue());
            DynamicObject salcontractno = dynamicObject.getDynamicObject("yem_salcontractno");
            if (salcontractno != null) {
                object.set("yem_salcontractno", salcontractno.get("billno"));
                object.set("yem_hidsalcontractno", salcontractno.getPkValue());
            }
            DynamicObject shippingdetailsno = dynamicObject.getDynamicObject("yem_shippingdetailsno");
            if (shippingdetailsno != null) {
                object.set("yem_shippingdetailsno", shippingdetailsno.get("billno"));
                object.set("yem_hidshippingdetailsno", shippingdetailsno.getPkValue());
            }
        }
        if ("back".equals(type)) {
            long salcontractno = dynamicObject.getLong("yem_hidsalcontractno");
            salcontractnoid = salcontractno;
            if (YEM.isNotEmpty(salcontractno)) {
                object.set("yem_salcontractno", dynamicObject.get("yem_hidsalcontractno"));
            }
            long shippingdetailsno = dynamicObject.getLong("yem_hidshippingdetailsno");
            if (YEM.isNotEmpty(shippingdetailsno)) {
                object.set("yem_shippingdetailsno", dynamicObject.get("yem_hidshippingdetailsno"));
            }
        }

        object.set("yem_shipamt", dynamicObject.get("yem_shipamt"));
        object.set("yem_billtype_b", dynamicObject.get("yem_billtype_b"));
        object.set("yem_salcontractamt", dynamicObject.get("yem_salcontractamt"));
        object.set("yem_salcontractclaamt", dynamicObject.get("yem_salcontractclaamt"));
        object.set("yem_claimamt", dynamicObject.get("yem_claimamt"));
        object.set("yem_claimamtbase", dynamicObject.get("yem_claimamtbase"));
        object.set("yem_discountamt", dynamicObject.get("yem_discountamt"));
        object.set("yem_discountamtbase", dynamicObject.get("yem_discountamtbase"));
        object.set("yem_contractamtbase", dynamicObject.get("yem_contractamtbase"));
        object.set("yem_contractrelevcuy", dynamicObject.get("yem_contractrelevcuy"));
        object.set("yem_conversionrate", dynamicObject.get("yem_conversionrate"));
        object.set("yem_department_b", dynamicObject.get("yem_department_b"));
        object.set("yem_remark_b", dynamicObject.get("yem_remark_b"));

        object.set("yem_orderrefundamt", dynamicObject.get("yem_orderrefundamt"));
        object.set("yem_shiprefundamt", dynamicObject.get("yem_shiprefundamt"));
        object.set("yem_periodrefundamt", dynamicObject.get("yem_periodrefundamt"));
        object.set("yem_creditslipid", dynamicObject.get("yem_creditslipid"));
        object.set("yem_creditslipno", dynamicObject.get("yem_creditslipno"));
//        if (salcontractnoid > 0) {
//            Generatecredit(salcontractnoid, dynamicObject.getBigDecimal("yem_claimamt"));
//        }
        object.set("yem_salesordertext", dynamicObject.get("yem_salesordertext"));

//        object.set("yem_unclaimedamo", dynamicObject.get("yem_unclaimedamo"));
    }

    /**
     * 生成贷记单
     *
     * @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 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("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_claimamt 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 = yemclaimamt.add(yem_claimamt);
                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()) {
//                                //切换正式需去掉
//                        OperationResult estimatedResult = OperationServiceHelper.executeOperate("zyestimated", "yem_debcrednote", new Object[]{debcrednote.getPkValue()}, OperateOption.create());
//                        if (estimatedResult.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);
                    }
                }
            }
        }
    }

    @Override
    public void click(EventObject e) {
        super.click(e);
        Control source = (Control) e.getSource();
        String key = source.getKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IDataModel parentModel = view.getParentView().getModel();
        DynamicObject parentModelDataEntity = parentModel.getDataEntity(true);
        int rowIndex = model.getEntryCurrentRowIndex("yem_claimdetail");
        DynamicObject currency = parentModelDataEntity.getDynamicObject("yem_currency");
        if ("btncancel".equals(key)) {
            view.returnDataToParent(null);
            view.close();
        }
        if ("btnok".equals(key)) {
            btnOk();
        }

        ListShowParameter parameter = new ListShowParameter();
        parameter.setMultiSelect(true);
        parameter.setParentPageId(view.getPageId());
        parameter.setStatus(OperationStatus.VIEW);
        parameter.getOpenStyle().setShowType(ShowType.Modal);
        parameter.getOpenStyle().setCacheId(parameter.getPageId());
        parameter.setLookUp(true);
        parameter.setMultiSelect(false);
        StyleCss css = new StyleCss();
        css.setHeight("580");
        css.setWidth("960");
        parameter.getOpenStyle().setInlineStyleCss(css);
        if ("yem_salcontractno".equals(key)) {
            parameter.setBillFormId("yem_es_salesorder");
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_es_salesorder"));
            ListFilterParameter listFilterParameter = new ListFilterParameter();
            DynamicObject comegoman = parentModelDataEntity.getDynamicObject("yem_comegoman");
            QFilter qFilter = new QFilter("billstatus", QCP.equals, "C");
            if (comegoman != null) {
                Long id = comegoman.getLong("id");
                qFilter.and("yem_customer.id", QCP.equals, id);
            }
            if (YEM.isNotEmpty(currency)) {
                long id = currency.getLong("id");
                qFilter.and("yem_currency.id", QCP.equals, id);
            }
            DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_salesorder", "id", qFilter.toArray());
            Set<Long> pass = new HashSet<>();
            for (DynamicObject dynamicObject : load) {
                DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
                // 合同认领金额
                BigDecimal contractPayment = PaymentControlUtil.getContractClimeAmt(salesOrder, "");
                // 合同金额
                BigDecimal offeramount = salesOrder.getBigDecimal("yem_offeramount");
                if (contractPayment.compareTo(offeramount) < 0) {
                    Long pkValue = (Long) salesOrder.getPkValue();
                    pass.add(pkValue);
                }
            }

            listFilterParameter.setFilter(new QFilter("id", QCP.in, pass));
            parameter.setListFilterParameter(listFilterParameter);
            view.showForm(parameter);
        }

        if ("yem_shippingdetailsno".equals(key)) {
            ListFilterParameter listFilterParameter = new ListFilterParameter();
            QFilter qFilter;
            long salContractNo = (long) model.getValue("yem_hidsalcontractno", rowIndex);
            if (YEM.isNotEmpty(salContractNo)) {
                List<Long> ids = new ArrayList<>();
                QFilter baseFilter = new QFilter("billstatus", QCP.equals, "C");
                baseFilter.and("yem_sourcebilltype", QCP.equals, "yem_es_salesorder");
                baseFilter.and("yem_sourcebillid", QCP.equals, salContractNo);
                baseFilter.and("billstatus", QCP.equals, "C");
                DynamicObject[] shippingDetails = BusinessDataServiceHelper.load("yem_shippingdetails", "id", baseFilter.toArray());
                for (DynamicObject shippingDetail : shippingDetails) {
                    // 款项性质
                    String moneynature = (String) model.getValue("yem_moneynature", rowIndex);
                    DynamicObject single = BusinessDataServiceHelper.loadSingle(shippingDetail.getPkValue(), shippingDetail.getDynamicObjectType().getName());
                    // 发运单号合同认领金额
                    BigDecimal amountClaimed = PaymentControlUtil.getAmountClaimed(new DynamicObject[]{single}, moneynature);
                    // 出运金额
                    BigDecimal allBalancePayment = PaymentControlUtil.getAllBalancePayment(new DynamicObject[]{single});

                    DynamicObject salesorder = BusinessDataServiceHelper.loadSingle(salContractNo, "yem_es_salesorder");

                    BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(salesorder);
                    BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(salesorder);

                    if ("E".equals(moneynature)) {

                        if (amountClaimed.compareTo(PaymentControlUtil.getAdvancePayment(allBalancePayment, shipPreRapRate)) < 0) {
                            Long id = (Long) single.getPkValue();
                            ids.add(id);
                        }
                    }
                    if ("F".equals(moneynature)) {
                        BigDecimal percentagePeriod = getPercentagePeriod(shipPreRapRate, procPreRapRate);
                        if (amountClaimed.compareTo(PaymentControlUtil.getAdvancePayment(allBalancePayment, percentagePeriod)) < 0) {
                            Long id = (Long) single.getPkValue();
                            ids.add(id);
                        }
                    }
                }
                qFilter = new QFilter("id", QCP.in, ids);
            } else {
                qFilter = new QFilter("id", QCP.equals, 0L);
            }
            if (YEM.isNotEmpty(currency)) {
                long id = currency.getLong("id");
                qFilter.and("yem_currency.id", QCP.equals, id);
            }
            listFilterParameter.setFilter(qFilter);
            parameter.setListFilterParameter(listFilterParameter);
            parameter.setBillFormId("yem_shippingdetails");
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_shippingdetails"));
            view.showForm(parameter);
        }
    }

    private void btnOk() {
        IFormView view = this.getView();
        FormShowParameter formShowParameter = view.getFormShowParameter();
        String opType = formShowParameter.getCustomParam("opType");
        IFormView parentView = this.getView().getParentView();
        IDataModel parentModel = parentView.getModel();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        int rowIndex = parentModel.getEntryCurrentRowIndex("yem_receiptdetail");

        DynamicObjectCollection collection = parentModel.getDataEntity(true).getDynamicObjectCollection("yem_receiptdetail");
        DynamicObject parentCollection = collection.get(rowIndex);
        //认领明细
        DynamicObjectCollection parentSubCollection = parentCollection.getDynamicObjectCollection("yem_claimdetail");
        DynamicObjectCollection formCollection = dataEntity.getDynamicObjectCollection("yem_claimdetail");
        if ("claim".equals(opType)) {
            if (!checkEmptyValue()) return;
            if (checkClaimAmount()) return;
            parentSubCollection.clear();
            for (DynamicObject dynamicObject : formCollection) {
                DynamicObject addedNew = parentSubCollection.addNew();
                setEntryValue(addedNew, dynamicObject, "back");
            }
        }
        if ("changeclaim".equals(opType)) {
            if (!checkEmptyValue()) return;
            if (checkClaimAmount()) return;
            if (checkChangeClaimAmount()) return;
            if (formCollection.isEmpty()) return;
            DynamicObject dynamicObject = formCollection.get(0);
            for (DynamicObject object : parentSubCollection) {
                long pkValue = (long) object.getPkValue();
                long originid = dynamicObject.getLong("yem_originid");
                if (pkValue == originid) {
                    setEntryValue(object, dynamicObject, "back");
                }
            }
        }
        this.getView().close();
    }

    private boolean checkEmptyValue() {
        boolean pass = false;
        IDataModel model = this.getModel();
        DynamicObject dynamicObject = model.getDataEntity(true);
        DynamicObjectCollection claimdetail = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
        for (DynamicObject object : claimdetail) {
            // 收款认领金额
            BigDecimal claimamt = object.getBigDecimal("yem_claimamt");
            // 合同认领金额
            BigDecimal salcontractclaamt = object.getBigDecimal("yem_salcontractclaamt");

            if (claimamt.compareTo(BigDecimal.ZERO) == 0) {
                pass = salcontractclaamt.compareTo(BigDecimal.ZERO) == 0;
            }

            if (claimamt.compareTo(BigDecimal.ZERO) > 0) {
                pass = salcontractclaamt.compareTo(BigDecimal.ZERO) > 0;
            }
        }
        if (!pass) {
            throw new KDBizException("请填写收款认领金额、合同认领金额后确认！！");
        }
        return pass;
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        String name = e.getProperty().getName();
        ChangeData data = e.getChangeSet()[0];
        IPageCache cache = this.getPageCache();
        BigDecimal oldVal = BigDecimal.ZERO;
        if ("yem_salcontractclaamt".equals(name)) {
            if (YEM.isNotEmpty(data.getOldValue())) {
                BigDecimal amount = (BigDecimal) data.getOldValue();
                oldVal = oldVal.add(amount);
            }
            cache.put("oldamount", oldVal.toString());
        }
    }

    private boolean checkChangeClaimAmount() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView view = this.getView();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        int rowIndex = parentModel.getEntryCurrentRowIndex("yem_receiptdetail");
        boolean isOverflow = false;
        IPageCache cache = this.getPageCache();
        DynamicObjectCollection subCollection = dataEntity.getDynamicObjectCollection("yem_claimdetail");
        for (DynamicObject subObject : subCollection) {
            int subIndex = subCollection.indexOf(subObject);
            // 款项性质
            String moneynature = subObject.getString("yem_moneynature");
            String salcontractNum = subObject.getString("yem_salcontractno");
            String shippingdetailsNum = subObject.getString("yem_shippingdetailsno");
            if (YEM.isEmpty(moneynature)) continue;
            if (YEM.isNotEmpty(salcontractNum)) {
                DynamicObject salcontractno = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, salcontractNum)});
                // 合同认领金额
                BigDecimal contractClimeAnt = PaymentControlUtil.getContractClimeAmt(salcontractno, moneynature);
                BigDecimal salcontractclaamt = subObject.getBigDecimal("yem_salcontractclaamt");
                BigDecimal hasClimeAmt = getThisLineClaimAmount(rowIndex, subIndex);

                contractClimeAnt = contractClimeAnt.add(salcontractclaamt).subtract(hasClimeAmt);
                // 下单预收款
                if ("D".equals(moneynature)) {
                    // 生产预收比例
                    BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(salcontractno);
                    BigDecimal contractOrderApprovalAmt = PaymentControlUtil.getContractOrderApprovalAmt(salcontractno);

                    // 如果减少进行校验，增加不校验
                    String oldamount = cache.get("oldamount");
                    if (YEM.isNotEmpty(oldamount)) {
                        BigDecimal old = new BigDecimal(oldamount);
                        if (salcontractclaamt.compareTo(old) < 0) {
                            if (contractClimeAnt.compareTo(PaymentControlUtil.getAdvancePayment(contractOrderApprovalAmt, procPreRapRate)) < 0) {
                                view.showErrorNotification(String.format("认领到该合同 [ %s ] 的金额 [ %s ] 小于 [ %s ] (该合同下的下单审批金额合计 [ %s ] * 生产预收比例 [ %s ] ), 不允许修改!",
                                        salcontractno.getString("billno"),
                                        contractClimeAnt.setScale(2, RoundingMode.HALF_UP),
                                        PaymentControlUtil.getAdvancePayment(contractOrderApprovalAmt, procPreRapRate).setScale(2, RoundingMode.HALF_UP),
                                        contractOrderApprovalAmt.setScale(2, RoundingMode.HALF_UP),
                                        procPreRapRate.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP)));
                                return true;
                            }
                        }
                        return false;
                    }
                }

                // 发货预收款
                if ("E".equals(moneynature)) {
                    if (YEM.isNotEmpty(shippingdetailsNum)) {
                        DynamicObject shippingdetailsno = BusinessDataServiceHelper.loadSingle("yem_shippingdetails", new QFilter[]{new QFilter("billno", QCP.equals, shippingdetailsNum)});
                        // 发运向下的所有销售出库金额合计
                        BigDecimal shipSalesIssueAmt = PaymentControlUtil.getContractShipApprovalAmt(shippingdetailsno);
                        // 发货预收比例
                        BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(salcontractno);
                        if (contractClimeAnt.compareTo(PaymentControlUtil.getAdvancePayment(shipSalesIssueAmt, shipPreRapRate)) < 0) {
                            view.showErrorNotification(String.format("认领到该外销合同 [ %s ] 的金额 [ %s ] 小于 [ %s ] (该出运明细下的销售出库金额合计 [ %s ] * 发货预收比例 [ %s ] ), 不允许修改!",
                                    salcontractno.getString("billno"),
                                    contractClimeAnt.setScale(2, RoundingMode.HALF_UP),
                                    PaymentControlUtil.getAdvancePayment(shipSalesIssueAmt, shipPreRapRate).setScale(2, RoundingMode.HALF_UP),
                                    shipSalesIssueAmt.setScale(2, RoundingMode.HALF_UP),
                                    shipPreRapRate.divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP)));
                            return true;
                        }
                    }
                }
            }
        }
        return isOverflow;
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btncancel", "btnok", "yem_salcontractno", "yem_shippingdetailsno", "yem_claimdetail");
        EntryGrid entryGrid = this.getView().getControl("yem_claimdetail");
        entryGrid.addRowClickListener(this);
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        ListSelectedRowCollection returnData = (ListSelectedRowCollection) e.getReturnData();
        if (returnData != null && !returnData.isEmpty()) {
            ListSelectedRow row = returnData.get(0);
            Long pkValue = (Long) row.getPrimaryKeyValue();
            String billNo = row.getBillNo();
            if ("yem_es_salesorder".equals(actionId)) {
                int rowIndex = model.getEntryCurrentRowIndex("yem_claimdetail");
                model.setValue("yem_salcontractno", billNo, rowIndex);
                model.setValue("yem_hidsalcontractno", pkValue, rowIndex);
                model.setValue("yem_salesordertext", billNo, rowIndex);
            }

            if ("yem_shippingdetails".equals(actionId)) {
                int rowIndex = model.getEntryCurrentRowIndex("yem_claimdetail");
                model.setValue("yem_shippingdetailsno", billNo, rowIndex);
                model.setValue("yem_hidshippingdetailsno", pkValue, rowIndex);
            }
        }
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        IFormView view = this.getView();
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObject dynamicObject = dataEntity.getDynamicObjectCollection("yem_claimdetail").get(rowIndex);
        DynamicObject claimman = dynamicObject.getDynamicObject("yem_claimman");
        IFormView parentView = this.getView().getParentView();
        IDataModel parentModel = parentView.getModel();
        DynamicObject parentModelDataEntity = parentModel.getDataEntity(true);
        FormShowParameter formShowParameter = view.getFormShowParameter();
        String opType = formShowParameter.getCustomParam("opType");
        if (claimman == null) return;

        int row = changeData.getRowIndex();
        if (row < 0) return;

        if ("yem_salcontractno".equals(name)) {
            //  合同号 带出 款项类型 业务员 单据类型 合同金额 部门
            String salcontract = (String) model.getValue("yem_salcontractno", row);
            if (YEM.isEmpty(salcontract)) {
                model.setValue("yem_operator_b", null, row);
                model.setValue("yem_productclassify", null, row);
                model.setValue("yem_salcontractamt", null, row);
                model.setValue("yem_contractamtbase", null, row);
                model.setValue("yem_contractrelevcuy", null, row);

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

                model.setValue("yem_shippingdetailsno", null, row);
                model.setValue("yem_claimamt", null, row);
                model.setValue("yem_claimamtbase", null, row);
                model.setValue("yem_salcontractclaamt", null, row);
                model.setValue("yem_contractamtbase", null, row);
                model.setValue("yem_orderrefundamt", null, row);

                model.setValue("yem_billtype_b", null, row);
                model.setValue("yem_hidsalcontractno", null, row);

                model.setValue("yem_orderrefundamt", BigDecimal.ZERO, row);
                model.setValue("yem_shiprefundamt", BigDecimal.ZERO, row);
                model.setValue("yem_periodrefundamt", BigDecimal.ZERO, row);
                return;
            }
            ;
            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.billno", QCP.equals, salcontract),});
            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);
            }
            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);
            calcRefundAmount(row);
        }
        if ("yem_shippingdetailsno".equals(name)) {
            // 选择出运明细号带出出运金额
            String shippingDetailsNo = (String) model.getValue("yem_shippingdetailsno", row);
            if (YEM.isNotEmpty(shippingDetailsNo)) {
                DynamicObject shippingDetails = BusinessDataServiceHelper.loadSingle("yem_shippingdetails", new QFilter[]{new QFilter("billno", QCP.equals, shippingDetailsNo)});
                model.setValue("yem_shipamt", shippingDetails.getBigDecimal("yem_offeramount"), row);
            } else {
                model.setValue("yem_shipamt", BigDecimal.ZERO, row);
                model.setValue("yem_claimamt", BigDecimal.ZERO, row);
                model.setValue("yem_claimamtbase", BigDecimal.ZERO, row);
                model.setValue("yem_salcontractclaamt", BigDecimal.ZERO, row);
                model.setValue("yem_contractamtbase", BigDecimal.ZERO, row);
//                model.setValue("yem_shiprefundamt", BigDecimal.ZERO, row);
                model.setValue("yem_hidshippingdetailsno", null, row);
            }
            calcRefundAmount(row);
        }

        BigDecimal claimamt = dynamicObject.getBigDecimal("yem_claimamt");

        if ("yem_claimamt".equals(name)) {
            // 计算收款认领金额本位币
            BigDecimal exrate = (BigDecimal) parentModel.getValue("yem_exrate");
            model.setValue("yem_claimamtbase", claimamt.multiply(exrate), row);

            BigDecimal sumreceivableamt = BigDecimal.ZERO;

            if ("claim".equals(opType)) {
                // 认领金额值 不能超过父分录的应收金额
                EntryGrid entry = this.getControl("yem_claimdetail");
                sumreceivableamt = entry.getSum("yem_claimamt");
            }

            if ("changeclaim".equals(opType)) {
                int index = parentModel.getEntryCurrentRowIndex("yem_receiptdetail");
                DynamicObjectCollection collection = parentModelDataEntity.getDynamicObjectCollection("yem_receiptdetail").get(index).getDynamicObjectCollection("yem_claimdetail");

                sumreceivableamt = (BigDecimal) model.getValue("yem_claimamt", row);
                Long originid = (Long) model.getValue("yem_originid", row);

                for (DynamicObject object : collection) {
                    Long pkValue = (Long) object.getPkValue();

                    if (!Objects.equals(pkValue, originid)) {
                        sumreceivableamt = sumreceivableamt.add(object.getBigDecimal("yem_claimamt"));
                    }
                }
            }

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

            model.setValue("yem_claimamt_a", sumreceivableamt);

            // 需要维护出运明细单号然后才能维护收款认领金额
            String moneynature = dynamicObject.getString("yem_moneynature");
            if (!"D".equals(moneynature)) {
                // 出运明细单号
                Long shippingdetailsno = dynamicObject.getLong("yem_hidshippingdetailsno");

                if (YEM.isEmpty(shippingdetailsno)) {
                    this.getView().showErrorNotification("请先维护出运明细单号");
                    model.setValue("yem_claimamt", BigDecimal.ZERO);
                    model.setValue("yem_claimamtbase", BigDecimal.ZERO);
                }
            }

            // 如果收款币别和合同币别一致  那么合同认领金额默认等于收款认领金额
            DynamicObject currency = (DynamicObject) model.getValue("yem_currency");
            if (YEM.isEmpty(currency)) return;
            Long currencyId = currency.getLong("id");
            Long contractrelevcuy = dynamicObject.getLong("yem_contractrelevcuy.id");
            if (Objects.equals(currencyId, contractrelevcuy)) {
                model.setValue("yem_salcontractclaamt", claimamt, row);
                view.setEnable(false, row, "yem_salcontractclaamt");
            } else {
                view.setEnable(true, row, "yem_salcontractclaamt");
            }
        }

        if ("yem_claimamt".equals(name) || "yem_salcontractclaamt".equals(name)) {
            // 转换率
            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);
            }
        }

        if ("yem_moneynature".equals(name) || "yem_salcontractclaamt".equals(name)) {
            String moneynature = dynamicObject.getString("yem_moneynature");
            if (!"D".equals(moneynature)) {
                // 合同认领金额
                BigDecimal salcontractclaamt = dynamicObject.getBigDecimal("yem_salcontractclaamt");
                // 出运金额
                BigDecimal shipamt = dynamicObject.getBigDecimal("yem_shipamt");

                if (YEM.isNotEmpty(shipamt)) {
                    if (salcontractclaamt.compareTo(shipamt) > 0) {
                        this.getView().showErrorNotification("认领明细第 " + (row + 1) + " 行,合同认领金额不能超过出运金额");
                    }
                }
            }
        }

        if ("yem_moneynature".equals(name)) {
            String moneynature = (String) model.getValue("yem_moneynature", row);
            // 发货预收款
            view.setEnable("E".equals(moneynature) || "F".equals(moneynature), row, "yem_shippingdetailsno");
            calcRefundAmount(row);

            if ("D".equals(moneynature)) {
                model.setValue("yem_shippingdetailsno", null, row);
                model.setValue("yem_shipamt", null, row);
                model.setValue("yem_claimamt", null, row);
                model.setValue("yem_salcontractclaamt", null, row);
                model.setValue("yem_claimamtbase", null, row);
                model.setValue("yem_contractamtbase", null, row);
            }
        }

        if ("yem_contractrelevcuy".equals(name)) {
            // 如果收款币别和合同币别一致  那么合同认领金额默认等于收款认领金额
            DynamicObject currency = (DynamicObject) model.getValue("yem_currency");
            if (YEM.isEmpty(currency)) return;
            Long currencyId = currency.getLong("id");
            Long contractrelevcuy = dynamicObject.getLong("yem_contractrelevcuy.id");
            view.setEnable(!Objects.equals(currencyId, contractrelevcuy), row, "yem_salcontractclaamt");
        }

        // 认领金额 计算 本位币
        if ("yem_claimamt_a".equals(name)) {
            BigDecimal exrate = parentModelDataEntity.getBigDecimal("yem_exrate");
            BigDecimal value = (BigDecimal) model.getValue("yem_claimamt_a");
            model.setValue("yem_claimamtbase_a", exrate.multiply(value));

            if (value.compareTo(BigDecimal.ZERO) == 0) {
                model.setValue("yem_claimstate_a", "A");
            }
            if (value.compareTo(BigDecimal.ZERO) == 1) {
                model.setValue("yem_claimstate_a", "B");
            }
            if (value.compareTo((BigDecimal) model.getValue("yem_receivableamt")) == 0) {
                model.setValue("yem_claimstate_a", "C");
            }
        }
    }

    /**
     * 检查合同认领金额是否超出
     */
    private boolean checkClaimAmount() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection claimdetails = dataEntity.getDynamicObjectCollection("yem_claimdetail");
        IFormView parentView = this.getView().getParentView();
        IDataModel parentModel = parentView.getModel();
        DynamicObject parentDataEntity = parentModel.getDataEntity(true);

        boolean overflow = false;
        for (DynamicObject dynamicObject : claimdetails) {
            int subRowindex = claimdetails.indexOf(dynamicObject);
            String moneynature = dynamicObject.getString("yem_moneynature");
            int rowIndex = parentModel.getEntryCurrentRowIndex("yem_receiptdetail");
            BigDecimal hasClimeAmt = getThisLineClaimAmount(rowIndex, subRowindex);

            String salcontract = dynamicObject.getString("yem_salcontractno");
            DynamicObject salesorder = null;
            if (YEM.isNotEmpty(salcontract)) {
                salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("yem_es_salesorder.billno", QCP.equals, salcontract),});
            }

            String shippingDetailsNo = dynamicObject.getString("yem_shippingdetailsno");
            DynamicObject shippingDetails = null;
            if (YEM.isNotEmpty(shippingDetailsNo)) {
                shippingDetails = BusinessDataServiceHelper.loadSingle("yem_shippingdetails", new QFilter[]{new QFilter("billno", QCP.equals, shippingDetailsNo)});
            }


            if ("D".equals(moneynature)) {
                if (YEM.isNotEmpty(salesorder)) {
                    // 历史的合同认领金额 + 收款认领金额 - 合同认领金额
                    BigDecimal historyContractClimeAmt = PaymentControlUtil.getContractClimeAmt(salesorder, "D");
                    BigDecimal orderrefundamt = dynamicObject.getBigDecimal("yem_orderrefundamt");
                    BigDecimal salcontractclaamt = dynamicObject.getBigDecimal("yem_salcontractclaamt");
                    BigDecimal subtract = historyContractClimeAmt.add(salcontractclaamt).subtract(hasClimeAmt);
                    if (subtract.subtract(orderrefundamt).compareTo(new BigDecimal("0.1")) > 0) {
                        overflow = true;
                        this.getView().showErrorNotification(String.format("认领明细第 %s 行，合同认领金额合计 [ %s ] 大于该合同的下单应回款 [ %s ]，不能认领！", subRowindex + 1, subtract.setScale(2, RoundingMode.HALF_UP), orderrefundamt.setScale(2, RoundingMode.HALF_UP)));
                        break;
                    }
                }
            }

            if ("E".equals(moneynature)) {
                if (YEM.isNotEmpty(shippingDetails)) {
                    BigDecimal claimContractClimeAmt = PaymentControlUtil.getShipClaimContractClimeAmt(shippingDetails, "E");
                    BigDecimal salcontractclaamt = dynamicObject.getBigDecimal("yem_salcontractclaamt");
                    BigDecimal shiprefundamt = dynamicObject.getBigDecimal("yem_shiprefundamt");
                    BigDecimal subtract = claimContractClimeAmt.add(salcontractclaamt).subtract(hasClimeAmt);
                    if (subtract.subtract(shiprefundamt).compareTo(new BigDecimal("0.1")) > 0) {
                        overflow = true;
                        this.getView().showErrorNotification(String.format("认领明细第 %s 行，合同认领金额合计 [ %s ] 大于该合同的发货应回款 [ %s ]，不能认领！", subRowindex + 1, subtract.setScale(2, RoundingMode.HALF_UP), shiprefundamt.setScale(2, RoundingMode.HALF_UP)));
                        break;
                    }
                }
            }

            if ("F".equals(moneynature)) {
                if (YEM.isNotEmpty(shippingDetails)) {
                    BigDecimal claimContractClimeAmt = PaymentControlUtil.getShipClaimContractClimeAmt(shippingDetails, "F");
                    BigDecimal salcontractclaamt = dynamicObject.getBigDecimal("yem_salcontractclaamt");
                    BigDecimal periodrefundamt = dynamicObject.getBigDecimal("yem_periodrefundamt");
                    BigDecimal subtract = claimContractClimeAmt.add(salcontractclaamt).subtract(hasClimeAmt);
                    if (subtract.subtract(periodrefundamt).compareTo(new BigDecimal("0.1")) > 0) {
                        overflow = true;
                        this.getView().showErrorNotification(String.format("认领明细第 %s 行，合同认领金额合计 [ %s ] 大于该合同的账期应回款 [ %s ]，不能认领！", subRowindex + 1, subtract.setScale(2, RoundingMode.HALF_UP), periodrefundamt.setScale(2, RoundingMode.HALF_UP)));
                        break;
                    }
                }
            }
        }
        return overflow;
    }

    private BigDecimal getThisLineClaimAmount(int index, int subIndex) {
        BigDecimal res = BigDecimal.ZERO;
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        DynamicObject parentDataEntity = parentModel.getDataEntity(true);
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_claimdetail");
        DynamicObject subObject = collection.get(subIndex);
        long originid = subObject.getLong("yem_originid");
        if (YEM.isNotEmpty(originid)) {
            DynamicObjectCollection parentCollection = parentDataEntity.getDynamicObjectCollection("yem_receiptdetail");
            if (!parentCollection.isEmpty()) {
                DynamicObject dynamicObject = parentCollection.get(index);
                DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_claimdetail");
                if (!subCollection.isEmpty()) {
                    if (subIndex > subCollection.size() - 1) {
                        return BigDecimal.ZERO;
                    }
                    for (DynamicObject parentSubObject : subCollection) {
                        Long pkValue = (Long) parentSubObject.getPkValue();
                        if (Objects.equals(pkValue, originid)) {
                            res = parentSubObject.getBigDecimal("yem_salcontractclaamt");
                        }
                    }
                }
            }
        }
        return res;
    }

    /**
     * 计算回款金额
     *
     * @param row
     */
    private void calcRefundAmount(int row) {
        IDataModel model = this.getModel();

        String salcontract = (String) model.getValue("yem_salcontractno", row);
        String shippingDetailsNo = (String) model.getValue("yem_shippingdetailsno", row);

        if (YEM.isNotEmpty(salcontract) && YEM.isEmpty(shippingDetailsNo)) {
            DynamicObject salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("yem_es_salesorder.billno", QCP.equals, salcontract),});

            BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(salesorder);
            BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(salesorder);

            BigDecimal amount = salesorder.getBigDecimal("yem_offeramount");
            BigDecimal orderrefundamt = PaymentControlUtil.getAdvancePayment(amount, procPreRapRate);
            BigDecimal shiprefundamt = PaymentControlUtil.getAdvancePayment(amount, shipPreRapRate);
            BigDecimal rate = getPercentagePeriod(shipPreRapRate, procPreRapRate);
            BigDecimal periodrefundamt = rate.multiply(amount);
            model.setValue("yem_orderrefundamt", orderrefundamt, row);
            model.setValue("yem_shiprefundamt", shiprefundamt, row);
            model.setValue("yem_periodrefundamt", periodrefundamt, row);
        }

        if (YEM.isNotEmpty(salcontract) && YEM.isNotEmpty(shippingDetailsNo)) {
            DynamicObject salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("yem_es_salesorder.billno", QCP.equals, salcontract),});
            DynamicObject shippingDetails = BusinessDataServiceHelper.loadSingle("yem_shippingdetails", new QFilter[]{new QFilter("billno", QCP.equals, shippingDetailsNo)});

            BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(salesorder);
            BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(salesorder);

            BigDecimal amount = shippingDetails.getBigDecimal("yem_offeramount");
            BigDecimal orderrefundamt = PaymentControlUtil.getAdvancePayment(amount, procPreRapRate);
            BigDecimal shiprefundamt = PaymentControlUtil.getAdvancePayment(amount, shipPreRapRate);
            BigDecimal rate = getPercentagePeriod(shipPreRapRate, procPreRapRate);
            BigDecimal periodrefundamt = rate.multiply(amount);
            model.setValue("yem_orderrefundamt", orderrefundamt, row);
            model.setValue("yem_shiprefundamt", shiprefundamt, row);
            model.setValue("yem_periodrefundamt", periodrefundamt, row);
        }
    }

    /**
     * 获取尾款（账期）比例
     *
     * @return
     */
    private BigDecimal getPercentagePeriod(BigDecimal shipPreRapRate, BigDecimal procPreRapRate) {
        return BigDecimal.ONE.subtract(procPreRapRate.multiply(BigDecimal.valueOf(0.01))).subtract(shipPreRapRate.multiply(BigDecimal.valueOf(0.01)));
    }

    /**
     * 计算发货应回款
     *
     * @param shippingDetails
     * @param salesorder
     * @return
     */
    private BigDecimal calcShipRepayable(DynamicObject shippingDetails, DynamicObject salesorder) {
        if (YEM.isEmpty(salesorder)) {
            return BigDecimal.ZERO;
        }

        BigDecimal shipPreRapRate = PaymentControlUtil.getShipPreRapRate(salesorder);
        BigDecimal offeramount = shippingDetails.getBigDecimal("yem_offeramount");
        return PaymentControlUtil.getAdvancePayment(offeramount, shipPreRapRate);
    }

    /**
     * 计算下单因回款
     *
     * @param salesorder
     * @return
     */
    private BigDecimal calcOrderRepayable(DynamicObject salesorder) {
        BigDecimal procPreRapRate = PaymentControlUtil.getProcPreRapRate(salesorder);
        BigDecimal offeramount = salesorder.getBigDecimal("yem_offeramount");
        return PaymentControlUtil.getAdvancePayment(offeramount, procPreRapRate);
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_receiptdetail");
        DynamicObject dynamicObject = collection.get(0);
        String name = e.getEntryProp().getName();
        IFormView view = this.getView();
        IDataModel parentModel = view.getParentView().getModel();
        DynamicObject parentModelDataEntity = parentModel.getDataEntity(true);
        RowDataEntity[] rowDataEntities = e.getRowDataEntities();
        for (RowDataEntity rowDataEntitie : rowDataEntities) {
            int rowIndex = rowDataEntitie.getRowIndex();
            if ("yem_claimdetail".equals(name)) {
                model.setValue("yem_moneytype", dynamicObject.get("yem_moneytypetl_a"), rowIndex);
                model.setValue("yem_receiptuse", parentModelDataEntity.getDynamicObject("yem_receipttype"), rowIndex);
            }
            view.setEnable(false, rowIndex, new String[]{"yem_salcontractclaamt", "yem_moneytype", "yem_productclassify", "yem_receiptuse", "yem_operator_b", "yem_billtype_b", "yem_contractrelevcuy", "yem_salcontractamt", "yem_shipamt", "yem_conversionrate", "yem_department_b", "yem_shippingdetailsno"});
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        String operateKey = ((FormOperate) args.getSource()).getOperateKey();
        IDataModel model = this.getModel();
        int rowIndex = model.getEntryCurrentRowIndex("yem_claimdetail");
        if ("deleteentry".equals(operateKey)) {
            Object claimman = model.getValue("yem_claimman", rowIndex);
            if (claimman != null) {
                long id = ((DynamicObject) claimman).getLong("id");
                if (YEM.getCurrentUserId() != id) {
                    args.setCancel(true);
                    this.getView().showErrorNotification("只能删除自己的数据");
                }
            }
        }
    }
}
