package com.yem.wm.es.shippingdetails.form;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.druid.util.StringUtils;
import com.yem.wm.bc.companytitle.form.CompanyTitleEdit;
import com.yem.wm.es.contractamtlist.util.FunUtil;
import com.yem.wm.es.shippingdetails.util.PaymentControlUtil;
import com.yem.wm.utils.FunctionalCommon;
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.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

import static com.yem.wm.es.Util.TotalUtil.countBigCabinetQty;
import static com.yem.wm.es.Util.TotalUtil.countSmallCabinetQty;
import static com.yem.wm.es.contractamtlist.util.FunUtil.getPayBills;
import static com.yem.wm.es.contractamtlist.util.FunUtil.getShipBills;
import static com.yem.wm.es.salesorder.from.SalesOrderEdit.carryReportCategoryAndHsCode;
import static com.yem.wm.es.salesorder.utils.SalesOrderUtils.*;
import static com.yem.wm.es.shippingdetails.op.ShippingDetailsAuditOp.collect;
import static com.yem.wm.es.shippingdetails.util.PaymentControlUtil.calcIOUAmount;

/**
 * @author 张立攀
 * @version 1.0
 * @description 出运明细单
 * @date 2023-08-16 17:50
 */
public class ShippingDetailsFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {
    private static final Log log = LogFactory.getLog(CompanyTitleEdit.class);

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        FunctionalCommon.setBillType(this);//赋值对应视图单据类型
        OperationStatus status = this.getView().getFormShowParameter().getStatus();
        //复制时 给未储运数量赋值
        if (OperationStatus.ADDNEW == status) {
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection dynamicObjectCollection1 = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            int row = 0;
            for (DynamicObject temp : dynamicObjectCollection1) {
                int yemQty = temp.getInt("yem_qty");
                this.getModel().setValue("yem_qtyfield4", yemQty, row);
                row++;
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        IFormView view = this.getView();
        String key = e.getOperateKey();
        Map<String, Object> datas = new HashMap<String, Object>();
        if ("collectioninquiry".equals(key)) {
            BigDecimal yem_ctpreclaimat = BigDecimal.ZERO;
            DynamicObject customer = (DynamicObject) this.getModel().getValue("yem_customer");
            if (customer != null) {
                List<QFilter> customerlist = new ArrayList<QFilter>();
                customerlist.add(new QFilter("yem_comegoman", QCP.equals, customer.getPkValue()));
                customerlist.add(new QFilter("billstatus", QCP.equals, "C"));
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_gathering", "", customerlist.toArray(new QFilter[0]));
                if (dynamicObject != null) {
                    dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
                    datas.put("yem_unclaimamount", dynamicObject.getBigDecimal("yem_sumunclaimamt"));
                    yem_ctpreclaimat = dynamicObject.getBigDecimal("yem_sumreceivableamt");
                    datas.put("yem_ctpreclaimat", yem_ctpreclaimat);
                    datas.put("yem_contractclaimats", dynamicObject.getBigDecimal("yem_sumfundsreceived"));
                }

                //欠条金额
                List<QFilter> customerlist2 = new ArrayList<QFilter>();
                customerlist2.add(new QFilter("yem_client", QCP.equals, customer.getPkValue()));
                customerlist2.add(new QFilter("billstatus", QCP.equals, "C"));
                DynamicObject dy = BusinessDataServiceHelper.loadSingle("yem_im_tradeapp", "", customerlist2.toArray(new QFilter[0]));
                if (dy != null) {
                    dy = BusinessDataServiceHelper.loadSingle(dy.getPkValue(), dy.getDynamicObjectType().getName());
                    datas.put("yem_iouamount", dy.getBigDecimal("yem_noreceivedamt"));

                }
            }
            BigDecimal raprate = BigDecimal.ZERO;
            String sourcebillno = (String) this.getModel().getValue("yem_sourcebillno");
            List<QFilter> list = new ArrayList<QFilter>();
            list.add(new QFilter("billno", QCP.equals, sourcebillno));
            list.add(new QFilter("billstatus", QCP.equals, "C"));
            DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "", list.toArray(new QFilter[0]));
            BigDecimal offeramount = BigDecimal.ONE;
            if (dynamicObject != null) {
                dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
                offeramount = dynamicObject.getBigDecimal("yem_offeramount");
                datas.put("yem_contractamount", offeramount);
                DynamicObject reccondition = dynamicObject.getDynamicObject("yem_reccondition");
                if (reccondition != null) {
                    datas.put("yem_collectionterms", reccondition.getPkValue());
                }
                DynamicObjectCollection salescontrac = dynamicObject.getDynamicObjectCollection("yem_es_salescontrac_s");
                if (salescontrac.size() > 0) {
                    DynamicObject salescontracEntry = salescontrac.get(0);
                    if (salescontracEntry != null && salescontracEntry.getBoolean("yem_ispre")) {
                        raprate = salescontracEntry.getBigDecimal("yem_raprate");
                        datas.put("yem_proportionreceive", salescontracEntry.getBigDecimal("yem_raprate"));
                    }
                }
                datas.put("yem_amountreceivable", offeramount.multiply(raprate.divide(new BigDecimal(100), RoundingMode.HALF_UP)));
            }
            datas.put("yem_salenumber", sourcebillno);
            String billno = (String) this.getModel().getValue("billno");
            datas.put("yem_shipmentnumber", billno);
            BigDecimal yem_offeramount = (BigDecimal) this.getModel().getValue("yem_offeramount");
            datas.put("yem_shipmentat", yem_offeramount);
            datas.put("yem_shipmentpreat", yem_offeramount.multiply(raprate.divide(new BigDecimal(100), RoundingMode.HALF_UP)));
            if (offeramount.compareTo(BigDecimal.ZERO) != 0) {
                datas.put("yem_shipmentclaimat", yem_offeramount.divide(offeramount, RoundingMode.HALF_UP).multiply(yem_ctpreclaimat));
            }


            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setFormId("yem_collectioninquiry");
            formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            formShowParameter.setCustomParams(datas);
            this.getView().showForm(formShowParameter);
        }


        if (StringUtils.equals("audit", key)) {
            OperationResult opResult = e.getOperationResult();
            if (opResult != null && opResult.isSuccess()) {
                this.getView().invokeOperation("refresh");
            }
        }

        if (StringUtils.equals("unaudit", key)) {
            OperationResult opResult = e.getOperationResult();
            if (opResult != null && opResult.isSuccess()) {
                this.getView().invokeOperation("refresh");
            }
        }
        if (StringUtils.equals("contractamtviewreceipts", key)) {//合同资金一览（实际收款）
            Map<String, Object> map = new HashMap();
            map.put("flag", "A");
            FunUtil.viewForm("yem_contractamtlistrealit", map, view);
        }
        if (StringUtils.equals("contractamtviewoccupy", key)) {//合同资金一览（款项占用）
            Map<String, Object> map = new HashMap();
            map.put("flag", "B");
            FunUtil.viewForm("yem_contractamtlistoccupy", map, view);
        }

        //回填海关编码
        if ("backcustomscode".equals(key) && e.getOperationResult().isSuccess()) {
            //回填海关编码
            FormShowParameter showParameter = new FormShowParameter();
            showParameter.setFormId("yem_es_backcustomscode");
            showParameter.setCloseCallBack(null);
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(showParameter);
        }

        if ("checkinventory".equals(key)) {

            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObject yem_bd_products = dataEntity.getDynamicObject("yem_bd_products");
            DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (int i = 0; i < yem_es_materialinfo.size(); i++) {
                DynamicObject object = yem_es_materialinfo.get(i);
                DynamicObject yem_materiel = object.getDynamicObject("yem_materiel");
                if (yem_materiel != null) {
                    long materielid = yem_materiel.getLong("id");
                    String materienumber = yem_materiel.getString("number");
                    Map getinventoryseva = getinventoryseva(materielid, materienumber, yem_bd_products);
                    if (getinventoryseva.size() > 0) {
                        this.getModel().setValue("yem_inventoryseva", getinventoryseva.get("yem_gmpjqty"), i);
                        this.getModel().setValue("yem_inventorydif", getinventoryseva.get("yem_qtysub"), i);
                        BigDecimal inventoryseva = (BigDecimal) getModel().getValue("yem_inventoryseva", i);
                        BigDecimal tolreqqty = (BigDecimal) getinventoryseva.get("tolreqqty");
                        BigDecimal qty = object.getBigDecimal("yem_qty");
                        this.getModel().setValue("yem_currinventorydif", inventoryseva.subtract(qty), i);
                    }
                }
            }
            DynamicObjectCollection sumCollection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_total");
            DynamicObjectCollection detailCollection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject sum : sumCollection) {
                for (DynamicObject detail : detailCollection) {
                    long sumId = sum.getLong("yem_constractioid_tl");
                    long detailId = detail.getLong("id");
                    if (sumId == detailId) {
                        sum.set("yem_inventoryseva_s", detail.getBigDecimal("yem_inventoryseva"));
                        sum.set("yem_inventorydif_s", detail.getBigDecimal("yem_inventorydif"));
                        sum.set("yem_currinventorydif_s", detail.getBigDecimal("yem_currinventorydif"));
                    }
                }

                BigDecimal inventoryseva = sum.getBigDecimal("yem_inventoryseva_s");
                if (YEM.isEmpty(inventoryseva)) {
                    sum.set("yem_inventoryseva_s", BigDecimal.ZERO);
                }
                BigDecimal inventorydif = sum.getBigDecimal("yem_inventorydif_s");
                if (YEM.isEmpty(inventorydif)) {
                    sum.set("yem_inventorydif_s", BigDecimal.ZERO);
                }
                BigDecimal currinventorydif = sum.getBigDecimal("yem_currinventorydif_s");
                if (YEM.isEmpty(currinventorydif)) {
                    sum.set("yem_currinventorydif_s", BigDecimal.ZERO);
                }
            }
//            view.invokeOperation("save");
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.showMessage("查询成功");
            view.invokeOperation("refresh");
        }

        if ("test_gen".equals(key)) {
            DynamicObject dataEntity = this.getModel().getDataEntity(true);
            DynamicObjectCollection collects = dataEntity.getDynamicObjectCollection("yem_es_salesorder_total");
            collects.clear();
            collect(dataEntity);
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
        }
    }


    @Override
    public void registerListener(EventObject e) {
        TextEdit textEdit = this.getControl("yem_vehicleno");
        textEdit.addClickListener(this);
        BasedataEdit classification = this.getView().getControl("yem_classification");
        if (classification != null) {
            classification.addBeforeF7SelectListener(this);
        }

        BasedataEdit customclass = this.getControl("yem_customclass");
        if (customclass != null) {
            customclass.addBeforeF7SelectListener(this);
        }
        BasedataEdit hscode = this.getControl("yem_hscode");

        if (hscode != null) {
            hscode.addBeforeF7SelectListener(this);
        }
        this.addItemClickListeners("yem_baritemap");
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {

        String name = e.getEntryProp().getName();
        if ("yem_es_salesorder_z".equals(name)) {
            int currentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("yem_es_materialinfo");
            DynamicObjectCollection entryEntityZ = this.getModel().getEntryEntity("yem_es_salesorder_z");
            if (entryEntity != null && entryEntity.size() > 0) {
                DynamicObject dynamicObject = entryEntity.get(currentRowIndex);
                if (dynamicObject != null) {
                    DynamicObject yemResourcenog = dynamicObject.getDynamicObject("yem_resourcenog");
                    DynamicObject yemProductmodel = dynamicObject.getDynamicObject("yem_productmodel");
                    if (yemResourcenog != null) {
                        this.getModel().setValue("yem_resourcescode", yemResourcenog.getPkValue(), entryEntityZ.size() - 1);
                    }
                    if (yemProductmodel != null) {
                        DynamicObject yemProducts = yemProductmodel.getDynamicObject("yem_products");
                        this.getModel().setValue("yem_milltype", yemProducts, entryEntityZ.size() - 1);
                    }
                }

            }
        }
        super.afterAddRow(e);
    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        String name = e.getEntryProp().getName();
        int[] rowIndexs = e.getRowIndexs();
        if ("yem_es_salesorder_z".equals(name)) {
            int rowIndex = rowIndexs[0];
            int currentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            String yemsourcebillno = (String) this.getModel().getValue("yem_sourcebillno");
            if (YEM.isNotEmpty(yemsourcebillno)) {
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "", new QFilter[]{
                        new QFilter("billno", QCP.equals, yemsourcebillno),
                        new QFilter("billstatus", QCP.equals, "C")
                });
                if (dynamicObject != null) {
                    dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
                    DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
                    if (dynamicObjectCollection != null && dynamicObjectCollection.size() > 0) {
                        DynamicObject dynamicObject1 = dynamicObjectCollection.get(currentRowIndex);
                        if (dynamicObject1 != null) {
                            DynamicObjectCollection yem_es_salesorder_z = dynamicObject1.getDynamicObjectCollection("yem_es_salesorder_z");
                            boolean b = yem_es_salesorder_z.size() > rowIndex;
                            if (yem_es_salesorder_z != null && b) {
                                DynamicObject dynamicObje = yem_es_salesorder_z.get(rowIndex);
                                dynamicObje.set("yem_ifdelivered", false);
                                yem_es_salesorder_z.set(rowIndex, dynamicObje);
                                OperationResult operationResult1 = OperationServiceHelper.executeOperate("save", "yem_es_salesorder", new DynamicObject[]{dynamicObject}, OperateOption.create());
                                if (operationResult1.isSuccess()) {
//                                    log.error("保存成功-"+operationResult1.getMessage());
                                } else {
                                    log.error("保存失败-" + operationResult1.getMessage());
                                }

                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void click(EventObject evt) {
        Control source = (Control) evt.getSource();
        String key = source.getKey();
        if ("yem_vehicleno".equals(key)) {
            FormShowParameter parameter = new FormShowParameter();
            parameter.setFormId("yem_shippingdetails_dy");
            int currentRowIndex = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            String yemsourcebilltype = (String) this.getModel().getValue("yem_sourcebilltype");
            if ("yem_es_salesorder".equals(yemsourcebilltype)) {
                String yemsourcebillno = (String) this.getModel().getValue("yem_sourcebillno");
                if (YEM.isNotEmpty(yemsourcebillno)) {
                    DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "", new QFilter[]{
                            new QFilter("billno", QCP.equals, yemsourcebillno),
                            new QFilter("billstatus", QCP.equals, "C")
                    });
                    if (dynamicObject != null) {
                        dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), dynamicObject.getDynamicObjectType().getName());
                        DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
                        if (dynamicObjectCollection != null && dynamicObjectCollection.size() > 0) {
                            DynamicObject dynamicObject1 = dynamicObjectCollection.get(currentRowIndex);
                            if (dynamicObject1 != null) {
                                DynamicObjectCollection yem_es_salesorder_z = dynamicObject1.getDynamicObjectCollection("yem_es_salesorder_z");
                                Map<String, Object> datas = new HashMap();
                                List<DynamicObject> zjNumberList = new ArrayList();
                                for (DynamicObject temp : yem_es_salesorder_z) {
                                    boolean yemIfdelivered = temp.getBoolean("yem_ifdelivered");
                                    if (!yemIfdelivered) {
                                        zjNumberList.add(temp);
                                    }
                                }
                                datas.put("yem_vehicleno", zjNumberList);
                                parameter.setCustomParams(datas);
                            }
                        }
                    }

                }

            }

            parameter.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(parameter);
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        DynamicObject datas = this.getModel().getDataEntity(true);
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        int rowIndex = e.getRow();
        switch (key) {
            case "yem_classification":
                String businesssort = (String) this.getModel().getValue("yem_businesssort", rowIndex);
                if (businesssort == null) {
                    e.addCustomQFilter(new QFilter("yem_businessclassify", QCP.equals, null));
                }
                if ("Z".equals(businesssort)) {
                    e.addCustomQFilter(new QFilter("yem_businessclassify", QCP.equals, "Z"));
                }
                if ("P".equals(businesssort)) {
                    e.addCustomQFilter(new QFilter("yem_businessclassify", QCP.equals, "P"));
                }
                break;
            case "yem_customclass":
                QFilter filter = filterCustomClass(rowIndex);
                e.addCustomQFilter(filter);
                break;
            case "yem_hscode":
                QFilter hsCodeFilter = filterHsCode(rowIndex);
                e.addCustomQFilter(hsCodeFilter);
                break;
            default:
                break;
        }
    }
//    public void carryReportCategoryAndHsCode(IDataModel model, IFormView view, int rowIndex, String currentSelect)
//    {
//        Object currentCustomclass = model.getValue("yem_customclass", rowIndex);
//        if (YEM.isEmpty(currentCustomclass)) {
//            model.setValue("yem_hscode", null, rowIndex);
//            model.setValue("yem_declarationele", null, rowIndex);
//            model.setValue("yem_actualfilingele", null, rowIndex);
//            model.setValue("yem_declareunit", null, rowIndex);
//            return;
//        }
//
//        if ("yem_customclass".equals(currentSelect)) {
//            model.setValue("yem_hscode", null, rowIndex);
//            model.setValue("yem_declarationele", null, rowIndex);
//            model.setValue("yem_actualfilingele", null, rowIndex);
//            model.setValue("yem_declareunit", null, rowIndex);
//        }
//
//        if ("yem_hscode".equals(currentSelect)) {
//            model.setValue("yem_declarationele", null, rowIndex);
//            model.setValue("yem_actualfilingele", null, rowIndex);
//            model.setValue("yem_declareunit", null, rowIndex);
//        }
//        // 申报要素
//        DynamicObject[] loads = getDeclarationElementsUseCarry(model, rowIndex, "yem_hscode");
//
//        if (loads.length == 1) {
//            DynamicObject load = loads[0];
//            load = BusinessDataServiceHelper.loadSingle(load.getPkValue(), load.getDynamicObjectType().getName());
//            DynamicObject customclass = load.getDynamicObject("yem_customclass");
//            if (YEM.isNotEmpty(customclass)) {
//                model.setValue("yem_customclass", customclass.getLong("id"), rowIndex);
//            }
//            DynamicObject hscodebase = load.getDynamicObject("yem_hscodebase");
//            if (YEM.isNotEmpty(hscodebase)) {
//                hscodebase = BusinessDataServiceHelper.loadSingle(hscodebase.getPkValue(), hscodebase.getDynamicObjectType().getName());
//                model.setValue("yem_hscode", hscodebase.getLong("id"), rowIndex);
//                model.setValue("yem_declarationele", load, rowIndex);
//                model.setValue("yem_actualfilingele", load.getString("name"), rowIndex);
//                model.setValue("yem_declareunit", hscodebase.getDynamicObject("yem_legalfirst"), rowIndex);
//            }
//        }
//    }

    private QFilter filterCustomClass(int index) {
        IDataModel model = this.getModel();
        DynamicObject[] loads = getDeclarationElementsUseF7Select(model, index, "yem_customclass");

        Set<Long> ids = new HashSet<>();

        for (DynamicObject dynamicObject : loads) {
            DynamicObject customclass = dynamicObject.getDynamicObject("yem_customclass");
            if (customclass != null) {
                ids.add(customclass.getLong("id"));
            }
        }
        return new QFilter("id", QCP.in, ids);
    }

    private QFilter filterHsCode(int index) {
        IDataModel model = this.getModel();
        DynamicObject[] loads = getDeclarationElementsUseF7Select(model, index, "yem_hscode");

        Set<Long> ids = new HashSet<>();

        for (DynamicObject dynamicObject : loads) {
            DynamicObject hscodebase = dynamicObject.getDynamicObject("yem_hscodebase");
            if (hscodebase != null) {
                ids.add(hscodebase.getLong("id"));
            }
        }
        return new QFilter("id", QCP.in, ids);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        Object newValue = e.getChangeSet()[0].getNewValue();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        switch (name) {
            // 是否随车配件修改时，清空随车配件单号
            case "yem_iswithaccessories":
                model.setValue("yem_accompanynum", null);
                break;
//            case "yem_customclass":
////                carryDeclaration(model, this.getView(), rowIndex);
//                carryReportCategoryAndHsCode(model, this.getView(), rowIndex, "yem_customclass");
//                break;
//            case "yem_hscode":
//                carryReportCategoryAndHsCode(model, this.getView(), rowIndex, "yem_hscode");
//                if (newValue instanceof DynamicObject) {
//                    DynamicObject yem_hscode = (DynamicObject) newValue;
//                    if (yem_hscode != null) {
//                        String yemUnit = yem_hscode.getString("yem_unit");
//                        DynamicObject bdMeasureunits = BusinessDataServiceHelper.loadSingle("bd_measureunits", "id,number,name"
//                                , new QFilter[]{new QFilter("name", QCP.equals, yemUnit)});
//                        if (bdMeasureunits != null) {
//                            this.getModel().setValue("yem_declareunit",bdMeasureunits,rowIndex);
//                        }else {
//                            this.getModel().setValue("yem_declareunit",null,rowIndex);
//                        }
//                    }else {
//                        this.getModel().setValue("yem_declareunit",null,rowIndex);
//                    }
//                }else {
//                    this.getModel().setValue("yem_declareunit",null,rowIndex);
//                }
//                break;
            case "yem_hscode":
                carryReportCategoryAndHsCode(this.getModel(), this.getView(), rowIndex, "yem_hscode");
//                carryDeclaration(this.getModel(), this.getView(), rowIndex);
                carryTaxRefundRate(this.getModel(), rowIndex);
                break;

            case "yem_productmodel":
            case "yem_materiel":
            case "yem_customclass":
                carryReportCategoryAndHsCode(this.getModel(), this.getView(), rowIndex, "yem_customclass");
                break;
            case "yem_qty":
            case "yem_offeramount":
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salescontrac_s");
                for (DynamicObject dynamicObject : collection) {
                    BigDecimal raprate = dynamicObject.getBigDecimal("yem_raprate");
                    BigDecimal offeramount = dataEntity.getBigDecimal("yem_offeramount");
                    dynamicObject.set("yem_rapamt", PaymentControlUtil.getAdvancePayment(offeramount, raprate));
                    this.getView().updateView("yem_es_salescontrac_s");
                }
                break;
            case "yem_bigcabinetnumbers":
                countBigCabinetQty(model);//汇总表头大柜数量
                break;
            case "yem_mincabinetnumbers":
                countSmallCabinetQty(model);//汇总表头小柜数量
                break;
        }
    }


    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate source = (FormOperate) args.getSource();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        String operateKey = source.getOperateKey();
        if ("push".equals(operateKey)) {
            String saleorderno = dataEntity.getString("yem_saleorderno");
            if (YEM.isEmpty(saleorderno)) return;
            DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, saleorderno)});
            if (saleOrder == null) return;
            DynamicObject[] shipBills = getShipBills(saleOrder, dataEntity, "A");//出运
            DynamicObject[] payBills = getPayBills(saleOrder, dataEntity, "B");//收款单
            BigDecimal thisRealityAmt = PaymentControlUtil.getThisRealityAmt(saleOrder, shipBills, payBills, dataEntity);
            dataEntity.set("yem_arrearsamt", thisRealityAmt);//本次发运欠款金额
            dataEntity.set("yem_arrearsamtapply", FunUtil.getAbs(thisRealityAmt));//本次发运应申请欠条金额

            BigDecimal decimal = calcIOUAmount(dataEntity);
            dataEntity.set("yem_iouamount", decimal);

            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.invokeOperation("refresh");
        }
    }
}
