package com.yem.wm.es.salesorder.from;

import com.yem.em.utils.BigDecimalUtils;
import com.yem.ensign.common.CommonUtils;
import com.yem.wm.es.contractamtlist.util.FunUtil;
import com.yem.wm.es.salesorder.dynamic.ShippingPlanEdit;
import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import com.yem.wm.im.clientdemand.utils.ClientUtils;
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.context.RequestContext;
import kd.bos.data.BusinessDataReader;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.botp.runtime.SourceBillReport;
import kd.bos.entity.datamodel.*;
import kd.bos.entity.datamodel.events.*;
import kd.bos.entity.operate.OperateOptionConst;
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.AttachmentPanel;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.ItemClickEvent;
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.BasedataEdit;
import kd.bos.form.field.ComboEdit;
import kd.bos.form.field.ComboItem;
import kd.bos.form.field.FieldEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
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.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.yem.wm.es.salesorder.utils.SalesOrderUtils.*;

/**
 * 外销合同 表单插件
 */
public class SalesOrderEdit extends AbstractBillPlugIn implements Plugin, BeforeF7SelectListener {


    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
    }

    @Override
    public void click(EventObject e) {
        super.click(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Control source = (Control) e.getSource();
        String key = source.getKey();
        if ("yem_color".equals(key)) {
            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);
            ListFilterParameter listFilterParameter = new ListFilterParameter();
            List<Long> colorIds = filterColor(model, "yem_es_materialinfo");
            listFilterParameter.setFilter(new QFilter("id", "in", colorIds));
            parameter.setListFilterParameter(listFilterParameter);
            parameter.setBillFormId("yem_em_color");
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_em_color"));
            view.showForm(parameter);
        }

        if ("yem_incomptext".equals(key)) {
            FormShowParameter fsp = view.getFormShowParameter();
            OperationStatus status = fsp.getStatus();
            if (OperationStatus.ADDNEW.equals(status)) {
                view.showMessage("请先保存合同后进行操作！");
            }
            FormShowParameter parameter = new FormShowParameter();
            parameter.setStatus(OperationStatus.ADDNEW);
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            parameter.setFormId("yem_es_incompline");
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_es_incompline"));
            view.showForm(parameter);
        }
    }

    @Override
    public void afterLoadData(EventObject e) {
        super.afterLoadData(e);
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        setLockIfSignBtn();
//        setLockExpenseInfo(view, model);
    }

    /**
     * 同费用信息中费用项目为 FYXM0023.2 时允许修改，其它不允许修改，不允许新增行，删除行
     */
    public static void setLockExpenseInfo(IFormView view, IDataModel model) {
        int rowCount = model.getEntryRowCount("yem_costinfor");
        String[] fields = {"yem_ticketprice", "yem_bigcabinetprice", "yem_mincabinetprice", "yem_costsumamount", "yem_cartfulamount", "yem_costsumamountcoin", "yem_cartfulamountcoin", "yem_whecountoffertotalsum"};
        for (int i = 0; i < rowCount; i++) {
            DynamicObject padexpense = (DynamicObject) model.getValue("yem_padexpense", i);
            if (YEM.isEmpty(padexpense)) {
                continue;
            }
            String number = padexpense.getString("number");
            if (!"FYXM0023.2".equals(number)) {
                view.setEnable(false, i, fields);
            } else {
                view.setEnable(true, i, fields);
            }
        }
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        setLockIfSignBtn();
        System.out.println();
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
//        String billno = dataEntity.getString("billno");
//        String customBillno = SalesOrderUtils.replaceSerialNumberWithLetters(billno, dataEntity.getDataEntityType().getName());
//        dataEntity.set("billno", customBillno);

        setUnQty();
//        genShipPortEnName(model, this.getView());
        String yemAccamtusetype = (String) model.getValue("yem_accamtusetype");
        extracted(yemAccamtusetype);
        boolean iscopied = (boolean) model.getValue("yem_iscopied");
        long id = (long) model.getValue("id");
        if (iscopied && YEM.isEmpty(id)) {
            int rowCount = model.getEntryRowCount("yem_es_materialinfo");
            for (int index = 0; index < rowCount; index++) {
                String businesssort = (String) model.getValue("yem_businesssort", index);
                if ("P".equals(businesssort)) {
                    model.setValue("yem_resourcenog", null, index);
                }
            }
        }
    }

    /**
     * @description 赋值未**数量
     * @author xwudd
     * return
     * @time 2023/10/8 15:30
     */

    public void setUnQty() {
        IDataModel model = this.getModel();
        FormShowParameter fsp = this.getView().getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        if (OperationStatus.ADDNEW == status) {
            int materialInfos = model.getEntryRowCount("yem_es_materialinfo");
            for (int i = 0; i < materialInfos; i++) {
                BigDecimal qty = (BigDecimal) model.getValue("yem_qty", i);
                model.setValue("yem_unshippingqty", qty, i);
                model.setValue("yem_unorderqty", qty, i);
                model.setValue("yem_shippingqty", BigDecimal.ZERO, i);
                model.setValue("yem_orderqty", BigDecimal.ZERO, i);
            }
        }
    }


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit products = this.getView().getControl("yem_salesmethod");
        if (products != null) {
            products.addBeforeF7SelectListener(this);
        }
        BasedataEdit classification = this.getView().getControl("yem_classification");
        if (classification != null) {
            classification.addBeforeF7SelectListener(this);
        }
        BasedataEdit yem_bd_products = this.getControl("yem_bd_products");
        if (yem_bd_products != null) {
            yem_bd_products.addBeforeF7SelectListener(this);
        }

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

        BasedataEdit yem_hscode = this.getControl("yem_hscode");
        if (yem_hscode != null) {
            yem_hscode.addBeforeF7SelectListener(this);
        }
        BasedataEdit yem_internationalrate = this.getControl("yem_internationalrate");
        if (yem_internationalrate != null) {
            yem_internationalrate.addBeforeF7SelectListener(this);
        }
        this.addClickListeners("yem_color", "yem_incomptext");
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        switch (name) {
            case "yem_productmodel"://基础机型切换 清除所有字段 除了（业务分类、基础机型、计量单位）
                Object yem_intauditbusaid = this.getModel().getValue("yem_intauditbusaid", rowIndex);
                if (yem_intauditbusaid instanceof Long && YEM.isNotEmpty(yem_intauditbusaid)) {
                    DynamicObject intauditbusa = BusinessDataServiceHelper.loadSingle(yem_intauditbusaid, "yem_im_intauditbusa");
                    if (intauditbusa != null) {
                        OperationResult unaudit = OperationServiceHelper.executeOperate("unaudit", intauditbusa.getDataEntityType().getName(), new Object[]{intauditbusa.getPkValue()}, OperateOption.create());
                        if (unaudit.isSuccess()) {
                            this.getView().updateView("attachmentpanel");
                        }

                    }

                }
                break;
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        DynamicObject dataEntity = model.getDataEntity(true);
        String yemCntype = (String) model.getValue("yem_cntypes");
        BigDecimal yemcommissionamtba = (BigDecimal) this.getModel().getValue("yem_commissionamtba");
        BigDecimal yemCnexrate = (BigDecimal) this.getModel().getValue("yem_cnexrate");
        DynamicObject org = (DynamicObject) this.getModel().getValue("org");
        DynamicObject cncurrency = (DynamicObject) this.getModel().getValue("yem_cncurrency");
        DynamicObject currencybase = (DynamicObject) this.getModel().getValue("yem_currencybase");
        DynamicObject exratetable = (DynamicObject) this.getModel().getValue("yem_exratetable");
        Date exratedate = (Date) this.getModel().getValue("yem_exratedate");
        switch (name) {
            case "yem_amount":
            case "yem_cnproportion":
            case "yem_cnexrate":
                //（3）佣金金额=财务信息的FOB金额*佣金比例/100
                if ("B".equals(yemCntype)) {
                    DynamicObject yemCurrency = (DynamicObject) this.getModel().getValue("yem_currency");
                    BigDecimal yemAmount = (BigDecimal) this.getModel().getValue("yem_amount");
                    BigDecimal yemCnproportion = (BigDecimal) this.getModel().getValue("yem_cnproportion");
                    BigDecimal temp = yemAmount.multiply(yemCnproportion).divide(new BigDecimal(100));
                    if (org != null && cncurrency != null && currencybase != null && exratetable != null) {
                        BigDecimal exchangeRate = CommonUtils.getExchangeRate(exratetable.getLong("id"), yemCurrency.getLong("id"), cncurrency.getLong("id"),
                                org.getLong("id"), exratedate);
                        if (exchangeRate != null) {
                            this.getModel().setValue("yem_commissionamt", temp.multiply(exchangeRate));
                        }
                    }
                }
                break;
            case "yem_ifgift":
            case "yem_commissionamt":
            case "yem_safobamount":
                if ("A".equals(yemCntype)) {
                    cnAmountMy(model, dataEntity);
                }
                if ("B".equals(yemCntype)) {
                    cnAmountMy(model, dataEntity);
                }
                break;
            case "yem_cntypes":
                model.setValue("yem_cnproportion", null);
                model.setValue("yem_commissionamt", null);
                model.setValue("yem_commissionamtba", null);
                DynamicObjectCollection dynamics = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
                int rows = 0;
                for (DynamicObject dc : dynamics) {
                    model.setValue("yem_commissionamten", null, rows);
                    model.setValue("yem_commissionamtbaen", null, rows);
                    model.setValue("yem_onecarcom", null, rows);
                    rows++;
                }

                String oldValue = (String) changeData.getOldValue();
                if ("C".equals(oldValue)) {
                    model.setValue("yem_commissionamt", null);
                }
                if ("A".equals(yemCntype)) {
                    cnAmountMy(model, dataEntity);

                }
                if ("B".equals(yemCntype)) {
                    cnAmountMy(model, dataEntity);
                }
                break;
            case "yem_commissionamten":
                String yemCntypes = (String) model.getValue("yem_cntypes");
                if ("C".equals(yemCntypes)) {
                    DynamicObjectCollection coll = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
                    BigDecimal sum = BigDecimal.ZERO;
                    for (DynamicObject dc : coll) {
                        BigDecimal yemCommissionamten = dc.getBigDecimal("yem_commissionamten");
                        sum = sum.add(yemCommissionamten);
                    }
                    model.setValue("yem_commissionamt", sum);
                }
                break;
            //计算佣金汇率
            case "yem_cncurrency":
                this.getModel().setValue("yem_cnexrate", null);
            case "yem_currencybase":
            case "org":
            case "yem_exratedate":
            case "yem_exratetable":
                if (org != null && cncurrency != null && currencybase != null && exratetable != null) {
                    BigDecimal exchangeRate = CommonUtils.getExchangeRate(exratetable.getLong("id"), cncurrency.getLong("id"), currencybase.getLong("id"),
                            org.getLong("id"), exratedate);
                    this.getModel().setValue("yem_cnexrate", exchangeRate);

                }
                break;
            case "yem_fundusetype":
                // 资金使用类型字段切换时，清空 配件客商/借记额度
                this.getModel().setValue("yem_debitamount", null);
                // 资金使用类型 为 信用时，设置预计发货时间为必录
                String fundusetype = dataEntity.getString("yem_fundusetype");
                if ("A".equals(fundusetype)) {
                    FieldEdit control = this.getView().getControl("yem_acshipdate");
                    control.setMustInput(true);
                } else {
                    FieldEdit control = this.getView().getControl("yem_acshipdate");
                    control.setMustInput(false);
                }
                if (fundusetype.isEmpty()) {
                    model.setValue("yem_fundpoolamt", BigDecimal.ZERO);
//                    ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex);//计算折扣金额
                    ClientUtils.countAmtDisAmt(model, "yem_es_materialinfo", view);
                }
                fundusetype(model);
                break;

            case "yem_impactprice1":
                setImpactPrice();
                break;
            case "yem_priceitem":
                carryPriceItem(this.getModel(), this.getView());
                genTradeTermsDestports(model, view);//贸易术语=价格条款+目的港.工厂
                genTradeTermsShipports(model, view);//贸易术语=价格条款+起运港.工厂
                genTradeTerms(model.getDataEntity(true), view);
                break;
            case "yem_clientcountry":
            case "yem_transportstyle":
                carryPriceItem(this.getModel(), this.getView());
                break;
            case "yem_tradeterms":

                break;
            case "yem_shipports":
                genShipPortEnName(this.getModel());
                genTradeTermsShipports(model, view);//贸易术语=价格条款+起运港.工厂
                genTradeTerms(model.getDataEntity(true), view);
                break;
            case "yem_destports":
                genDescPortEnName(this.getModel());
                genTradeTermsDestports(model, view);//贸易术语=价格条款+目的港.工厂
                genTradeTerms(model.getDataEntity(true), view);
                carryFinalDestination(model, view);
                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":
                bringCustomsClassification(this.getModel(), rowIndex);
                carryReportCategoryAndHsCode(this.getModel(), this.getView(), rowIndex, "yem_customclass");
            case "yem_materiel":
            case "yem_customclass":
                carryReportCategoryAndHsCode(this.getModel(), this.getView(), rowIndex, "yem_customclass");
                break;
            case "yem_signconfirmstatus":
            case "yem_attachmentcountfield":
                setLockIfSignBtn();
                break;
            case "yem_billbusstype":
                fundusetype(model);
                break;
            case "yem_accamtusetype":
                String newValue = (String) changeData.getNewValue();
                extracted(newValue);

                if (YEM.isNotEmpty(dataEntity.getString("yem_accamtusetype"))) {
                    model.setValue("yem_fundpoolamt", BigDecimal.ZERO);
//                    ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex);//计算折扣金额
                    ClientUtils.countAmtDisAmt(model, "yem_es_materialinfo", view);
                }
                break;
            case "yem_accessorytype":
                carryingDetailedAssociatedQuantity(rowIndex, model);
                break;
            default:
                break;
        }
    }

    /**
     * 随即资料页签手动新增行的时候  选择机型时  自动携带关联商品明细行的数量
     *
     * @param rowIndex
     * @param model
     */
    private void carryingDetailedAssociatedQuantity(int rowIndex, IDataModel model) {
        long materialentryid = (long) model.getValue("yem_materialentryid", rowIndex);
//        if (YEM.isEmpty(materialentryid)) {
//            DynamicObject accessorytype = (DynamicObject) model.getValue("yem_accessorytype");
//            if (accessorytype == null) return;
//            long existId = accessorytype.getLong("id");
//            int rowCount = model.getEntryRowCount("yem_es_materialinfo");
//            for (int i = 0; i < rowCount; i++) {
//                DynamicObject productmodel = (DynamicObject) model.getValue("yem_productmodel", i);
//                if (productmodel == null) continue;
//                DynamicObject products = productmodel.getDynamicObject("yem_products");
//                if (products == null) continue;
//                long id = products.getLong("id");
//                if (id == existId) {
//                    BigDecimal existQty = (BigDecimal) model.getValue("yem_pcstype", rowIndex);
//                    BigDecimal qty = (BigDecimal) model.getValue("yem_qty", i);
//                    model.setValue("yem_pcstype", existQty.add(qty), rowIndex);
//                }
//            }
//        }
    }

    /**
     * 配件资金使用方式   控制隐现
     *
     * @param newValue
     */
    private void extracted(String newValue) {
        if (newValue != null && !newValue.isEmpty()) {
            if ("C".equals(newValue)) {
                this.getView().setVisible(false, "yem_frontrateentry");//字段错误
                this.getView().setVisible(false, "yem_afterfrontdisprice");//字段错误
                this.getView().setVisible(false, "yem_afterfrontdisamt");//字段错误
                this.getView().setVisible(false, "yem_disamt");//字段错误
            } else {
                this.getView().setVisible(true, "yem_frontrateentry");//字段错误
                this.getView().setVisible(true, "yem_afterfrontdisprice");//字段错误
                this.getView().setVisible(true, "yem_afterfrontdisamt");//字段错误
                this.getView().setVisible(true, "yem_disamt");//字段错误
            }
        }
    }

    /**
     * 控制显示配件资金使用方式
     *
     * @param model
     */
    private void fundusetype(IDataModel model) {
        OperationStatus status = this.getView().getFormShowParameter().getStatus();
        DynamicObject yemBilltype = (DynamicObject) model.getValue("yem_billtype");//单据状态
        Map<String, Object> map = new HashMap<String, Object>();
        if (yemBilltype != null) {
            String number = yemBilltype.getString("number");
            if (number.equals("yem_es_salesorder_nmzj") || number.equals("yem_es_salesorder_ZJ")) {//整机
                map.put("按金额（折扣）", "A");
            } else if (number.equals("yem_es_salesorder_nmpj") || number.equals("yem_es_salesorder_PJ")) {//配件
                DynamicObject yemBillbusstype = (DynamicObject) model.getValue("yem_billbusstype");
                if (yemBillbusstype != null) {
                    String string = yemBillbusstype.getString("number");
                    if (string.equals("BBT-2")) {
                        map.put("按金额（折扣）", "A");
                        map.put("按比例（折扣）", "B");
                    }
                    if ("BBT-3".equals(string) || "BBT-5".equals(string) || "BBT-4".equals(string)) {
                        map.put("按金额（全额抵扣）", "C");
                    }
                }
            }
            fillEntityCombo(map);
        }
    }

    /**
     * @param map 下拉项值
     */
    private void fillEntityCombo(Map<String, Object> map) {
        ComboEdit mainentry = (ComboEdit) this.getView().getControl("yem_accamtusetype"); //协议类型
        if (map.size() > 0) {
            List<ComboItem> entryItems = this.buildEntryComboItems(map);
            mainentry.setComboItems(entryItems);
        } else {
            mainentry.setComboItems(null);
        }
    }

    /**
     * @param entitys
     * @return
     */
    private List<ComboItem> buildEntryComboItems(Map<String, Object> entitys) {
        ArrayList<ComboItem> entryItems = new ArrayList<>();
        ComboItem blankItem = new ComboItem();
        blankItem.setValue("");
        blankItem.setCaption(new LocaleString());
        entryItems.add(blankItem);
        if (null != entitys && entitys.size() > 0) {
            for (Map.Entry entry : entitys.entrySet()) {
                String mapKey = (String) entry.getKey();
                String mapValue = (String) entry.getValue();
                ComboItem entryItem = new ComboItem();
                entryItem.setValue(mapValue);
                entryItem.setCaption(new LocaleString(mapKey));
                entryItems.add(entryItem);
            }
        }
        return entryItems;
    }

    private void setImpactPrice() {
        IDataModel model = this.getModel();
        // 影响调拨价
        DynamicObjectCollection esMaterialinfo = model.getDataEntity().getDynamicObjectCollection("yem_es_materialinfo");
        for (int i = 0; i < esMaterialinfo.size(); i++) {
            DynamicObjectCollection multiconfig = esMaterialinfo.get(i).getDynamicObjectCollection("yem_multiconfig");
            Set<Boolean> set = new HashSet<>();

            if (multiconfig.isEmpty()) {
                model.setValue("yem_impactprice", "B", i);
                continue;
            }
            for (DynamicObject object : multiconfig) {
                // 影响调拨价
                String impactprice1 = object.getString("yem_impactprice1");
                set.add("A".equals(impactprice1));
                if ("A".equals(impactprice1)) {
                    model.setValue("yem_impactprice", "A", i);
                }
                if (!set.contains(true)) {
                    model.setValue("yem_impactprice", "B", i);
                }
            }
        }
    }

    public static 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, currentSelect);

        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);
                carryDeclaration(model, view, rowIndex, load, hscodebase);
            }
        }
    }

    public void openMultipleSelectionList(QFilter qFilter, String formId, String actionId) {
        IFormView view = this.getView();
        ListShowParameter parameter = new ListShowParameter();
        parameter.setBillFormId(formId);
        parameter.setMultiSelect(true);
        parameter.setParentPageId(this.getView().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);
        // 过滤条件
        ListFilterParameter listFilterParameter = new ListFilterParameter();
        listFilterParameter.setFilter(qFilter);
        parameter.setListFilterParameter(listFilterParameter);
        parameter.setCloseCallBack(new CloseCallBack(this, actionId));
        view.showForm(parameter);
    }

    /**
     * 佣金金额=佣金信息中的佣金金额/明细信息中非赠品行的销售FOB金额汇总值*明细信息当前行对应的销售FOB金额
     */
    public static void cnAmountMy(IDataModel model, DynamicObject dataEntity) {
        BigDecimal yemCommissionamt = (BigDecimal) model.getValue("yem_commissionamt");
        DynamicObjectCollection yemEsMaterialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal countSafo = BigDecimal.ZERO;
        for (DynamicObject temp : yemEsMaterialinfo) {
            boolean yemIfgift = temp.getBoolean("yem_ifgift");
            if (!yemIfgift) {
                BigDecimal yemSafobamounts = temp.getBigDecimal("yem_safobamount");
                countSafo = countSafo.add(yemSafobamounts);
            }
        }
        int row = 0;
        for (DynamicObject dt : yemEsMaterialinfo) {
            BigDecimal yemSafobamount1 = dt.getBigDecimal("yem_safobamount");
            boolean yemIfgift = dt.getBoolean("yem_ifgift");

            if (countSafo.compareTo(BigDecimal.ZERO) != 0 && (!yemIfgift)) {
                model.setValue("yem_commissionamten", yemCommissionamt.multiply(yemSafobamount1).divide(countSafo, BigDecimal.ROUND_HALF_UP), row);
            } else {
                model.setValue("yem_commissionamtbaen", null, row);
                model.setValue("yem_commissionamten", null, row);
            }
            row++;
        }
        // 尾款处理
        BigDecimal sum = BigDecimal.ZERO;
        for (DynamicObject dts : yemEsMaterialinfo) {
            BigDecimal yemCommissionamten = dts.getBigDecimal("yem_commissionamten");
            sum = sum.add(yemCommissionamten);
        }
        if (sum.compareTo(yemCommissionamt) != 0) {
            BigDecimal subtract = yemCommissionamt.subtract(sum);
            boolean flag = true;
            int rows = 0;
            for (DynamicObject dts : yemEsMaterialinfo) {
                boolean yemIfgift = dts.getBoolean("yem_ifgift");
                if (!yemIfgift && flag) {
                    BigDecimal yemCommissionamten = dts.getBigDecimal("yem_commissionamten");
                    model.setValue("yem_commissionamten", yemCommissionamten.add(subtract), rows);
                    flag = false;
                }
                rows++;
            }
        }
    }


    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        IDataModel model = this.getModel();
        String name = e.getEntryProp().getName();
        RowDataEntity[] rowDataEntities = e.getRowDataEntities();
        for (RowDataEntity rowDataEntitie : rowDataEntities) {
            int rowIndex = rowDataEntitie.getRowIndex();
            if ("yem_es_materialinfo".equals(name)) {
                setMaterialType(rowIndex);
                model.setValue("yem_impactprice", "B", rowIndex);
                Object frontrate = model.getValue("yem_frontrate");
                if (YEM.isNotEmpty(frontrate)) {
                    BigDecimal decimal = (BigDecimal) frontrate;
                    model.setValue("yem_frontrateentry", decimal, rowIndex);
                }
                yemShipports(rowIndex);
            }
        }
    }

    /**
     * 新增行  分录价格条款、港口默认等于表头
     *
     * @param rowIndex
     */
    private void yemShipports(int rowIndex) {
        DynamicObjectCollection yemShipports = (DynamicObjectCollection) this.getModel().getValue("yem_shipports");
        if (yemShipports != null) {
                this.getModel().setValue("yem_port", yemShipports, rowIndex);
        }
        DynamicObject yem_priceitem = (DynamicObject) this.getModel().getValue("yem_priceitem");
        if (yem_priceitem != null) {
            long yemPriceitemLong = yem_priceitem.getLong("id");
            this.getModel().setValue("yem_priceitemsp", yemPriceitemLong, rowIndex);
        }
    }

    private void setMaterialType(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        if (billType != null) {
            String number = billType.getString("number");
            if ("yem_es_salesorder_ZJ".equals(number) || "yem_es_salesorder_nmzj".equals(number)) {
//                QFilter qFilter = new QFilter("number", QCP.equals, "TAI");
                QFilter qFilter = new QFilter("name", QCP.equals, "台");
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_measureunits", qFilter.toArray());
                if (dynamicObject != null) {
                    model.setValue("yem_unit", dynamicObject, rowIndex);//台
                    model.setValue("yem_baseunit", dynamicObject, rowIndex);
                }
            }
            if ("yem_es_salesorder_PJ".equals(number) || "yem_es_salesorder_nmpj".equals(number)) {
//                QFilter qFilter = new QFilter("number", QCP.equals, "PCS");
                QFilter qFilter = new QFilter("name", QCP.equals, "件");
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_measureunits", qFilter.toArray());
                if (dynamicObject != null) {
                    model.setValue("yem_unit", dynamicObject, rowIndex);//个
                    model.setValue("yem_baseunit", dynamicObject, rowIndex);
                }
            }

        }
    }


    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getEntryProp().getName();
        int[] rowIndexs = e.getRowIndexs();
        if ("yem_es_materialinfo".equals(name)) {
            FunctionalCommon.deleteMaterialEntry(e, view, model, rowIndexs);
        }
    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        String name = e.getEntryProp().getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        String yemCntype = (String) model.getValue("yem_cntypes");
        if ("yem_es_materialinfo".equals(name)) {
            if ("A".equals(yemCntype)) {
                cnAmountMy(model, dataEntity);

            }
            if ("B".equals(yemCntype)) {
                cnAmountMy(model, dataEntity);
            }

            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");

            BigDecimal yem_amount = BigDecimal.ZERO;

            BigDecimal yem_offeramount = BigDecimal.ZERO;

            for (DynamicObject dynamicObject : collection) {
                yem_amount = yem_amount.add(yem_amount.add(dynamicObject.getBigDecimal("yem_safobamount")));
                yem_offeramount = yem_offeramount.add(dynamicObject.getBigDecimal("yem_saamtpriceclause"));
            }

            model.setValue("yem_amount", yem_amount);
            model.setValue("yem_offeramount", yem_offeramount);
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String formId = view.getFormShowParameter().getFormId();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        OperationResult operationResult = e.getOperationResult();

        if ("shippingplan".equals(key)) {
            if (hasDoubleSignContract()) {
                String status = (String) model.getValue("yem_signconfirmstatus");
                if ("A".equals(status)) {
                    shippingplan();
                } else {
                    view.showErrorNotification("当前合同回签未确认，不允许下达跟单任务！");
                }
            } else {
                view.showErrorNotification("当前合同没有进行回签，不允许下达跟单任务！");
            }
        }


        if (key.equals("revokeplan")) {
            revokeplan();
        }
        if (YEM.isNotEmpty(operationResult) && operationResult.isSuccess()) {
            if (key.equals("rowclose")) {
                rowClose();
            }
            if (key.equals("unrowclose")) {
                rowUnClose();
            }
            if (key.equals("billclose")) {
                billClose();
            }
            if (key.equals("unclose")) {
                billUnClose();
            }
        }
        if ("contractamtview".equals(key)) {
            FunUtil.viewForm("yem_contractamtlistrealit", null, view);
        }

        if ("batchcreate".equals(key) && operationResult.isSuccess()) {
            this.getModel().batchCreateNewEntryRow("yem_es_materialinfo", 10);
        }
        //回填海关编码
        if ("backcustomscode".equals(key) && operationResult.isSuccess()) {
            //回填海关编码
            FormShowParameter showParameter = new FormShowParameter();
            showParameter.setFormId("yem_es_backcustomscode");
            showParameter.setCloseCallBack(null);
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            this.getView().showForm(showParameter);
        }

        if ("save".equals(key)) {
            String name = dataEntity.getDataEntityType().getName();
            DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
            if (yem_billtype != null) {
                String billtypenumber = yem_billtype.getString("number");
                if (billtypenumber.equals("yem_es_salesorder_ZJ") || billtypenumber.equals("yem_es_salesorder_PJ")
                        || billtypenumber.equals("yem_es_salesorder_nmzj") || billtypenumber.equals("yem_es_salesorder_nmpj")) {
                    setCustomBillno(dataEntity, view);
                    view.updateView("billno");
                }
            }
            view.invokeOperation("refresh");
        }
        if ("printdata".equals(key)) {
            view.showSuccessNotification("上传经理签批附件成功！");
        }
        if ("submitatt".equals(key)) {
            view.showSuccessNotification("上传合同提交附件成功！");
        }

        if ("checkinventory".equals(key)) {
            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) {
                        model.setValue("yem_inventoryseva", getinventoryseva.get("yem_gmpjqty"), i);
                        model.setValue("yem_inventorydif", getinventoryseva.get("yem_qtysub"), i);
                    }
                }
            }
            view.invokeOperation("save");
        }

        if ("exportisvoid".equals(key) && operationResult.isSuccess()) {
            view.invokeOperation("refresh");
        }

        if ("signature".equals(key)) {
            view.invokeOperation("refresh");
        }

        if ("requestacdeclaration".equals(key)) {
            EntryGrid control = this.getControl("yem_es_materialinfo");
            int[] selectRows = control.getSelectRows();
            if (selectRows.length == 0) {
                view.showErrorNotification("请选择需要获取的行！！");
                return;
            }
            StringBuilder sb = new StringBuilder();
            for (int i : selectRows) {
                DynamicObject[] load = getDeclarationElementsUseCarry(model, i, null);
                if (load.length == 1) {
//                    DynamicObject hscode = (DynamicObject) model.getValue("yem_hscode", i);
//                    carryDeclaration(model, view, i, load[0], hscode);
                    carryReportCategoryAndHsCode(model, view, i, "");
                } else {
                    if (load.length == 0) {
                        sb.append(String.format("第 %s 行未获匹配申报要素！！", i + 1)).append("\r\n");
                    }
                    if (load.length > 1) {
                        sb.append(String.format("第 %s 行匹配到多条申报要素，请手动选择！！", i + 1)).append("\r\n");
                    }
                }
            }
            if (sb.length() > 0) {
                view.showErrorNotification(sb.toString());
            } else {
                view.showSuccessNotification("操作成功");
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        Object returnData = e.getReturnData();
        IDataModel model = this.getModel();
        if (returnData != null && "shippingplan".equals(actionId)) {
            DynamicObject dataEntity = model.getDataEntity(true);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            //跟单任务
            DynamicObjectCollection yem_shippingplan_entry_s = dataEntity.getDynamicObjectCollection("yem_shippingplan_entry");
            Map mapSum = (Map) returnData;
            Map map = new HashMap<>();
            map.put("H", mapSum.get("H"));
            Map BOTPmap = new HashMap<>();
            if (mapSum.containsKey("Z")) {
                BOTPmap.put("Z", mapSum.get("Z"));
            }
            if (mapSum.containsKey("P")) {
                BOTPmap.put("P", mapSum.get("P"));
            }
            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next().toString();
                DynamicObject yem_shippingplan_entry = yem_shippingplan_entry_s.addNew();
                Date now = new Date();
                yem_shippingplan_entry.set("yem_plan_date", now);
                if (mapSum.containsKey("yem_lotno")) {
                    yem_shippingplan_entry.set("yem_lotno", mapSum.get("yem_lotno"));
                }
                if (mapSum.containsKey("yem_thisqty")) {
                    yem_shippingplan_entry.set("yem_thisqty", mapSum.get("yem_thisqty"));
                }
                if (mapSum.containsKey("yem_placemark")) {
                    yem_shippingplan_entry.set("yem_placemark", mapSum.get("yem_placemark"));
                }
                if (mapSum.containsKey("yem_nameplatetypegd")) {
                    yem_shippingplan_entry.set("yem_nameplatetypegd", mapSum.get("yem_nameplatetypegd"));
                }
                if (mapSum.containsKey("yem_nameplatelogogd")) {
                    yem_shippingplan_entry.set("yem_nameplatelogogd", mapSum.get("yem_nameplatelogogd"));
                }
                if (mapSum.containsKey("yem_nameplateqtygd")) {
                    yem_shippingplan_entry.set("yem_nameplateqtygd", mapSum.get("yem_nameplateqtygd"));
                }
                if (mapSum.containsKey("yem_acshipdate1")) {
                    yem_shippingplan_entry.set("yem_acshipdate1", mapSum.get("yem_acshipdate1"));
                }
                DynamicObjectCollection yem_plandetail_entry_s = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");

                List values = (List) map.get(key);
                for (int i = 0; i < values.size(); i++) {
                    Map value = (Map) values.get(i);
                    DynamicObject yem_plandetail_entry = yem_plandetail_entry_s.addNew();
                    yem_plandetail_entry.set("yem_orderallocation1", value.get("yem_orderallocation"));
                    yem_plandetail_entry.set("yem_orderallocationen1", value.get("yem_orderallocationen"));
                    yem_plandetail_entry.set("yem_materialclass1", value.get("yem_materialclass"));
                    yem_plandetail_entry.set("yem_businesssort1", value.get("yem_businesssort"));
                    yem_plandetail_entry.set("yem_productmodel1", value.get("yem_productmodel"));
                    yem_plandetail_entry.set("yem_ifreformg1", value.get("yem_ifreformg"));
                    yem_plandetail_entry.set("yem_reformdesg1", value.get("yem_reformdesg"));
                    yem_plandetail_entry.set("yem_ifsupportg1", value.get("yem_ifsupportg"));
                    yem_plandetail_entry.set("yem_combofield81", value.get("yem_combofield8"));
                    yem_plandetail_entry.set("yem_materiel2", value.get("yem_materiel"));
                    yem_plandetail_entry.set("yem_resourcenog1", value.get("yem_resourcenog"));
                    yem_plandetail_entry.set("yem_materialname1", value.get("yem_materialname"));
                    yem_plandetail_entry.set("yem_materialenname1", value.get("yem_materialenname"));
                    yem_plandetail_entry.set("yem_specification1", value.get("yem_specification"));
                    yem_plandetail_entry.set("yem_needqty1", value.get("yem_needqty"));
                    yem_plandetail_entry.set("yem_unit2", value.get("yem_unit"));
                    yem_plandetail_entry.set("yem_qty2", value.get("yem_planqty"));
                    yem_plandetail_entry.set("yem_remarks11", value.get("yem_remarks1"));
                    yem_plandetail_entry.set("yem_baseunit1", value.get("yem_baseunit"));
                    yem_plandetail_entry.set("yem_baseqty1", value.get("yem_baseqty"));
                    yem_plandetail_entry.set("yem_isgift1", value.get("yem_isgift"));
                    yem_plandetail_entry.set("yem_srcentryid", value.get("yem_srcentryid"));
                    BigDecimal yem_exrate = dataEntity.getBigDecimal("yem_exrate");
                    yem_plandetail_entry.set("yem_price1", value.get("yem_price"));
                    BigDecimal yem_price = yem_plandetail_entry.getBigDecimal("yem_price1");
                    BigDecimal yem_qty = yem_plandetail_entry.getBigDecimal("yem_qty2");
                    BigDecimal yem_amount = BigDecimalUtils.multiply(yem_qty, yem_price, 2);
                    yem_plandetail_entry.set("yem_amount1", yem_amount);
                    yem_plandetail_entry.set("yem_amountloc", BigDecimalUtils.multiply(yem_amount, yem_exrate, 2));

                    yem_shippingplan_entry.set("yem_plan_businesssort", key);
                }
                // 生成跟单任务控制台(2023-09-28禁用)
                SalesOrderUtils.cal_yem_orderqty(dataEntity);
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                //逻辑修改为直接下推《下单审批》
                create_yem_placeexamine(yem_shippingplan_entry);
            }

//            SalesOrderUtils.cal_yem_orderqty(dataEntity);
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            //根据
            this.getView().updateView();
        }

        if ("yem_es_contractresign".equals(actionId)) {
            putAttachmentData((Map<String, Object>) returnData, model, this.getView());
        }

        if ("yem_em_color".equals(actionId)) {
            ListSelectedRowCollection returnDataColor = (ListSelectedRowCollection) e.getReturnData();
            if (returnDataColor != null && !returnDataColor.isEmpty()) {
                ListSelectedRow row = returnDataColor.get(0);
                String number = row.getNumber();
                int detailedinfor = model.getEntryCurrentRowIndex("yem_es_materialinfo");
                model.setValue("yem_color", number, detailedinfor);
            }
        }


    }

    /**
     * 是否有 双签（回签）附件
     */
    private boolean hasDoubleSignContract() {
        AttachmentPanel panel = this.getControl("yem_attachmentpanelap");
        List<Map<String, Object>> attachmentData = panel.getAttachmentData();
        return !attachmentData.isEmpty();
    }

    public void putAttachmentData(Map<String, Object> attachInfor, IDataModel modal, IFormView view) {
        String entityId = view.getEntityId();
        view.invokeOperation("refresh");
        if (attachInfor != null) {
            List<Map<String, Object>> retData = (List<Map<String, Object>>) attachInfor.get("attach");
            Long userId = (Long) attachInfor.get("user");
            Date date = (Date) attachInfor.get("date");
            DynamicObject dataEntity = modal.getDataEntity(true);
            dataEntity.set("yem_signbackerid", userId);
            dataEntity.set("yem_signbackdate", date);
            dataEntity.set("yem_checkboxfield", true);
            if (retData != null && !retData.isEmpty()) {
                for (Map<String, Object> map : retData) {
                    String url = (String) map.get("url");
                    String name = (String) map.get("name");
                    // 持久化附件到服务器
                    url = SalesOrderUtils.uploadTempfile(url, name);
                    map.put("url", url);
                    map.put("creator", UserServiceHelper.getCurrentUserId());
                    map.put("modifytime", new Date().getTime());
                }
                AttachmentServiceHelper.upload(entityId, dataEntity.getPkValue(), "yem_attachmentpanelap", retData);
            }
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(dataEntity.getDynamicObjectType().getName(), dataEntity.getPkValue(), "yem_attachmentpanelap");
            dataEntity.set("yem_attachmentcountfield", attachments.size());
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.invokeOperation("refresh");
        }
    }


    /**
     * 下达跟单任务
     *
     * @see ShippingPlanEdit
     */
    public void shippingplan() {
        //校验是还有可下单数量
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        BigDecimal yem_unorderqty = BigDecimal.ZERO;
        DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        if (yem_es_materialinfo != null) {
            for (int i = 0; i < yem_es_materialinfo.size(); i++) {
                DynamicObject materialinfo = yem_es_materialinfo.get(i);
                BigDecimal yem_qty = materialinfo.getBigDecimal("yem_qty");
                BigDecimal yem_orderqty = materialinfo.getBigDecimal("yem_orderqty");
                yem_unorderqty = yem_unorderqty.add(BigDecimalUtils.sub(yem_qty, yem_orderqty, 10));
            }
        }
        if (yem_unorderqty.compareTo(BigDecimal.ZERO) > 0) {
            IFormView view = this.getView();
            FormShowParameter fsp = new FormShowParameter();
            fsp.setStatus(OperationStatus.ADDNEW);
            fsp.getOpenStyle().setShowType(ShowType.Modal);
            Map<String, Object> entryInfo = new HashMap();
            String formId = this.getView().getFormShowParameter().getFormId();
            entryInfo.put("billId", dataEntity.getPkValue());
            fsp.setCustomParams(entryInfo);
            CloseCallBack callBack = new CloseCallBack(this, "shippingplan");
            fsp.setCloseCallBack(callBack);
            fsp.setFormId("yem_shipping_plan");
            view.showForm(fsp);
        } else {
            this.getView().showMessage("当前单据剩余下单数量为0，禁止下单！");
        }
    }

    /**
     * 取消跟单任务
     */
    public void revokeplan() {
        EntryGrid entryGrid = this.getControl("yem_shippingplan_entry");
        int[] rows = entryGrid.getSelectRows();
        SalesOrderUtils.revokeplan_placeexamine(rows, this.getModel().getDataEntity(true));
        this.getView().updateView("yem_shippingplan_entry");
    }

    /**
     * 生成下单审批
     *
     * @param yem_shippingplan_entry
     */
    public void create_yem_placeexamine(DynamicObject yem_shippingplan_entry) {
        IDataModel model = this.getModel();
        DynamicObject bill = model.getDataEntity(true);
        long bill_id = bill.getLong("id");
        String bill1 = "yem_es_salesorder";
        String bill2 = "yem_placeexamine";
        String ruleId = "1783991740068293632";
        PushArgs pushArgs = new PushArgs();
        pushArgs.setSourceEntityNumber(bill1);        // 必选，源单标识
        pushArgs.setTargetEntityNumber(bill2);      // 必选，目标单标识
        pushArgs.setHasRight(false);                // 可选，传入true，不检查目标单新增权
        pushArgs.setAppId("yem_es");                // 可选，传入目标单验权使用的应用编码
        pushArgs.setDefOrgId(0L);                    // 可选，传入目标单主组织默认值
        pushArgs.setRuleId(ruleId);                    // 可选，传入本次下推使用的转换规则id；传入空值，由系统自动寻找合适的转换规则
        pushArgs.setBuildConvReport(true);            // 是否输出详细错误报告

        List<ListSelectedRow> selectedRows = new ArrayList<>();
        ListSelectedRow srcBillRows = new ListSelectedRow(bill_id);
        selectedRows.add(srcBillRows);
        pushArgs.setSelectedRows(selectedRows);        // 必选，设置需要下推的源单及分录内码

        // 调用下推引擎，下推目标单
        ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);
        // 判断下推是否成功，如果失败，提炼失败消息输出
        if (!pushResult.isSuccess()) {
            String errMessage = pushResult.getMessage();    // 错误摘要
            for (SourceBillReport billReport : pushResult.getBillReports()) {
                // 演示如何提取各单错误报告
                if (!billReport.isSuccess()) {
                    String billMessage = billReport.getFailMessage();
                    errMessage = errMessage + ";" + billMessage;
                }
            }
            throw new KDBizException("下推失败:" + errMessage);
        }
        // 获取生成的目标单数据包
        MainEntityType targetMainType = EntityMetadataCache.getDataEntityType(bill2);
        List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
            @Override
            public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                BusinessDataReader.loadRefence(objs, dType);
            }
        }, targetMainType);

        DynamicObject newbill = targetBillObjs.get(0);

        initDataplaceexamine(yem_shippingplan_entry, newbill);

        OperateOption option = OperateOption.create();
        option.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true));    // 不执行警告级别校验器
        option.setVariableValue(OperateOptionConst.IGNOREINTERACTION, String.valueOf(true));    // 不显示交互提示，自动执行到底
        option.setVariableValue(OperateOptionConst.STRICTVALIDATION, String.valueOf(true));        // 全部校验通过才保存
        option.setVariableValue(OperateOptionConst.ISHASRIGHT, String.valueOf(true));
        newbill.set("yem_titles", saveyemtitle(newbill));
//        OperationResult result_save = SaveServiceHelper.saveOperate(bill2, new DynamicObject[]{newbill}, option);
        OperationResult result_save = OperationServiceHelper.executeOperate("save", newbill.getDynamicObjectType().getName(),
                new DynamicObject[]{newbill}, OperateOption.create());
        // 判断保存结果
        if (!result_save.isSuccess()) {
            String errMessage = result_save.getMessage();
            List<IOperateInfo> operateInfo = result_save.getAllErrorOrValidateInfo();
            for (IOperateInfo tempOperateInfo : operateInfo) {
                errMessage = errMessage + ";" + tempOperateInfo.getMessage();
            }
            throw new KDBizException("生成下单审批保存失败：" + errMessage);
        } else {
            this.getView().showSuccessNotification("下单成功，请到《下单审批》列表查看详情！");
            long id = (long) result_save.getSuccessPkIds().get(0);
            DynamicObject yem_tracktaskconsole = BusinessDataServiceHelper.loadSingle(id, "yem_placeexamine");
            yem_shippingplan_entry.set("yem_placeexamine", yem_tracktaskconsole);
            //
            SalesOrderUtils.OpenFrom(this.getView(), id, "yem_placeexamine");

        }
    }

    /**
     * 拼接下单审批标题
     *
     * @param bill
     */
    public String saveyemtitle(DynamicObject bill) {
        DynamicObject yemOperator = bill.getDynamicObject("yem_operator");
        String yem_title = "";
        if (yemOperator != null) {
            String name = yemOperator.getString("name");
            yem_title = yem_title + name + " ";
        }
        DynamicObject yemClientcountry = bill.getDynamicObject("yem_clientcountry");
        if (yemClientcountry != null) {
            String name = yemClientcountry.getString("name");
            yem_title = yem_title + name + " ";
        }
        String yemContractnumber = bill.getString("yem_contractnumber");
        if (!yemContractnumber.equals("")) {
            yem_title = yem_title + yemContractnumber + " ";
        }
        DynamicObject yemBdProducts = bill.getDynamicObject("yem_bd_products");
        if (yemBdProducts != null) {
            String name = yemBdProducts.getString("name");
            yem_title = yem_title + name + " ";
        }
        DynamicObject yemBilltype = bill.getDynamicObject("yem_billtype");
        if (yemBilltype != null) {
            String name = yemBilltype.getString("name");
            yem_title = yem_title + name + " ";
        }
        String billno = bill.getString("billno");
        if (!"".equals(billno)) {
            yem_title = yem_title + billno + " ";
        }
        return yem_title;
    }

    /**
     * 设置下单审批数据
     *
     * @param yem_shippingplan_entry 跟单任务分录
     * @param newbill                跟单任务控制台
     */
    public void initDataplaceexamine(DynamicObject yem_shippingplan_entry, DynamicObject newbill) {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        Map yem_plandetail_entry_map = new HashMap();
        Map productsList = new HashMap();
        BigDecimal qty_s = BigDecimal.ZERO;
        //跟单任务明细子分录
        //获取跟单任务明细中的基础机型
        Map yem_productmodelmap = new HashMap();
        DynamicObjectCollection yem_plandetail_entry_s = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");//外销合同跟单任务明细子单据体
        for (int i = 0; i < yem_plandetail_entry_s.size(); i++) {
            DynamicObject yem_plandetail_entry = yem_plandetail_entry_s.get(i);
            long yem_srcentryid = yem_plandetail_entry.getLong("yem_srcentryid");
            if (yem_plandetail_entry.getString("yem_businesssort1").equals("Z")) {//业务分类-整机，获取整机台数

            }
            yem_plandetail_entry_map.put(yem_srcentryid, yem_plandetail_entry);
            DynamicObject yem_productmodel1 = yem_plandetail_entry.getDynamicObject("yem_productmodel1");//基础机型
            if (yem_productmodel1 != null) {
                long productid = yem_productmodel1.getLong("id");
                if (yem_productmodelmap.containsKey(productid)) {
                    yem_productmodelmap.put(productid, yem_productmodel1);
                }
            }
        }
        DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");
        if (yemBilltype != null) {
            String BilltypeNumber = yemBilltype.getString("number");
            newbill.set("yem_salesordertype", BilltypeNumber);
        }
        newbill.set("yem_nameplatetype", yem_shippingplan_entry.getString("yem_nameplatetypegd"));
        newbill.set("yem_nameplatelogo", yem_shippingplan_entry.getDynamicObject("yem_nameplatelogogd"));
        newbill.set("yem_nameplateqty", yem_shippingplan_entry.getInt("yem_nameplateqtygd"));
        newbill.set("yem_placemark", yem_shippingplan_entry.getString("yem_placemark"));
        newbill.set("yem_acshipdate", yem_shippingplan_entry.getString("yem_acshipdate1"));
        newbill.set("yem_lotno", yem_shippingplan_entry.getString("yem_lotno"));
        newbill.set("billno", dataEntity.getString("billno") + "-" + yem_shippingplan_entry.getString("yem_lotno"));
        //商品明细
        DynamicObjectCollection yem_es_salesorder_r = newbill.getDynamicObjectCollection("yem_es_salesorder_r");
        yem_es_salesorder_r.clear();
        DynamicObjectCollection yem_es_materialinfo_s = newbill.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal yem_thisqty = BigDecimal.ZERO;
        for (int i = 0; i < yem_es_materialinfo_s.size(); i++) {
            DynamicObject yem_es_materialinfo = yem_es_materialinfo_s.get(i);
            long yem_sourceentryid = yem_es_materialinfo.getLong("yem_sourceentryid");
            DynamicObject yem_plandetail_entry = (DynamicObject) yem_plandetail_entry_map.get(yem_sourceentryid);
            if (yem_plandetail_entry != null) {
                yem_thisqty = yem_thisqty.add(yem_plandetail_entry.getBigDecimal("yem_qty2"));
                BigDecimal yem_qty = yem_plandetail_entry.getBigDecimal("yem_qty2");//数量
                BigDecimal yem_baseqty = yem_plandetail_entry.getBigDecimal("yem_baseqty1");//基本数量
                yem_es_materialinfo.set("yem_tracktaskentrryid", yem_plandetail_entry.getLong("id"));//合同跟单明细字单据体id
                yem_es_materialinfo.set("yem_qty", yem_qty);
                yem_es_materialinfo.set("yem_baseqty", yem_baseqty);
                yem_es_materialinfo.set("yem_nqty", yem_qty);
                BigDecimal yem_amt = yem_qty.multiply(yem_es_materialinfo.getBigDecimal("yem_price"));
                yem_es_materialinfo.set("yem_amt", yem_amt);
                yem_es_materialinfo.set("yem_locamt", yem_amt.multiply(newbill.getBigDecimal("yem_exrate")));
                qty_s = BigDecimalUtils.add(qty_s, yem_qty, 10);
                DynamicObject yem_productmodel = yem_es_materialinfo.getDynamicObject("yem_productmodel");
                if (yem_productmodel != null) {
                    DynamicObject yem_products = yem_productmodel.getDynamicObject("yem_products");
                    if (yem_products != null) {
                        long yem_productsid = yem_products.getLong("id");
                        if (!productsList.containsKey(yem_productsid)) {
                            productsList.put(yem_productsid, yem_qty);
                        } else {
                            productsList.replace(yem_productsid, BigDecimalUtils.add(productsList.get(yem_productsid), yem_qty, 10));
                        }
                    }

                }

//                if ("Z".equals(key)) {
                DynamicObjectCollection yem_multiconfig_s = yem_es_materialinfo.getDynamicObjectCollection("yem_multiconfig");
                for (int j = 0; j < yem_multiconfig_s.size(); j++) {
                    DynamicObject yem_multiconfig = yem_multiconfig_s.get(j);
                    yem_multiconfig.set("yem_unitset", yem_qty);//台数
                }
                DynamicObjectCollection yem_retrofitting_s = yem_es_materialinfo.getDynamicObjectCollection("yem_retrofitting");
                for (int j = 0; j < yem_retrofitting_s.size(); j++) {
                    DynamicObject yem_retrofitting = yem_retrofitting_s.get(j);
                    BigDecimal yem_singleqty = yem_retrofitting.getBigDecimal("yem_singleqty");//单台数量
                    BigDecimal yem_qtyamt = BigDecimalUtils.multiply(yem_singleqty, yem_qty, 10);//总数量
                    yem_retrofitting.set("yem_qty1", yem_qty);
                    yem_retrofitting.set("yem_qtyamt", yem_qtyamt);
                }
//                }
            } else {
                yem_es_materialinfo_s.remove(i--);
            }
        }
        newbill.set("yem_thisqty", yem_thisqty);
//        if ("Z".equals(key)) {
        //随机资料及配件工具包
        DynamicObjectCollection yem_es_salesorder_p_s = newbill.getDynamicObjectCollection("yem_es_salesorder_p");
        for (int i = 0; i < yem_es_salesorder_p_s.size(); i++) {
            BigDecimal pcstype = BigDecimal.ZERO;
            DynamicObject yem_es_salesorder_p = yem_es_salesorder_p_s.get(i);
            BigDecimal yem_bicycleqty = yem_es_salesorder_p.getBigDecimal("yem_bicycleqty");//单车数量
            DynamicObject yem_accessorytype = yem_es_salesorder_p.getDynamicObject("yem_accessorytype");
            if (yem_accessorytype != null) {
                long accessorytype = yem_accessorytype.getLong("id");
                if (productsList.containsKey(accessorytype)) {
                    pcstype = (BigDecimal) productsList.get(accessorytype);
                } else {
                    yem_es_salesorder_p_s.remove(i--);
                }
            }
            BigDecimal yem_acallqty = BigDecimalUtils.multiply(yem_bicycleqty, pcstype, 10);//总数量
            yem_es_salesorder_p.set("yem_acallqty", yem_acallqty);
            yem_es_salesorder_p.set("yem_pcstype", pcstype);//机型台式
        }
//        }
    }

    /**
     * 生成跟单任务控制台
     *
     * @param
     * @param key
     */
    public void create_yem_tracktaskconsole(DynamicObject yem_shippingplan_entry, String key) {
        IDataModel model = this.getModel();
        DynamicObject bill = model.getDataEntity(true);
        long bill_id = bill.getLong("id");
        String bill1 = "yem_es_salesorder";
        String bill2 = "yem_tracktaskconsole";
        String ruleId = "";
        if ("Z".equals(key)) {
            ruleId = "1746461370783643648";
        } else if ("P".equals(key)) {
            ruleId = "1746467553313569792";
        }

        PushArgs pushArgs = new PushArgs();
        pushArgs.setSourceEntityNumber(bill1);        // 必选，源单标识
        pushArgs.setTargetEntityNumber(bill2);      // 必选，目标单标识
        pushArgs.setHasRight(false);                // 可选，传入true，不检查目标单新增权
        pushArgs.setAppId("yem_es");                // 可选，传入目标单验权使用的应用编码
        pushArgs.setDefOrgId(0L);                    // 可选，传入目标单主组织默认值
        pushArgs.setRuleId(ruleId);                    // 可选，传入本次下推使用的转换规则id；传入空值，由系统自动寻找合适的转换规则
        pushArgs.setBuildConvReport(true);            // 是否输出详细错误报告

        List<ListSelectedRow> selectedRows = new ArrayList<>();
        ListSelectedRow srcBillRows = new ListSelectedRow(bill_id);
        selectedRows.add(srcBillRows);
        pushArgs.setSelectedRows(selectedRows);        // 必选，设置需要下推的源单及分录内码

        // 调用下推引擎，下推目标单
        ConvertOperationResult pushResult = ConvertServiceHelper.push(pushArgs);

        // 判断下推是否成功，如果失败，提炼失败消息输出
        if (!pushResult.isSuccess()) {
            String errMessage = pushResult.getMessage();    // 错误摘要
            for (SourceBillReport billReport : pushResult.getBillReports()) {
                // 演示如何提取各单错误报告
                if (!billReport.isSuccess()) {
                    String billMessage = billReport.getFailMessage();
                    errMessage = errMessage + ";" + billMessage;
                }
            }
            throw new KDBizException("下推失败:" + errMessage);
        }

        // 获取生成的目标单数据包
        MainEntityType targetMainType = EntityMetadataCache.getDataEntityType(bill2);
        List<DynamicObject> targetBillObjs = pushResult.loadTargetDataObjects(new IRefrencedataProvider() {
            @Override
            public void fillReferenceData(Object[] objs, IDataEntityType dType) {
                BusinessDataReader.loadRefence(objs, dType);
            }
        }, targetMainType);

        DynamicObject newbill = targetBillObjs.get(0);

        initData(yem_shippingplan_entry, newbill, key);

        OperateOption option = OperateOption.create();
        option.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true));    // 不执行警告级别校验器
        option.setVariableValue(OperateOptionConst.IGNOREINTERACTION, String.valueOf(true));    // 不显示交互提示，自动执行到底
        option.setVariableValue(OperateOptionConst.STRICTVALIDATION, String.valueOf(true));        // 全部校验通过才保存
        option.setVariableValue(OperateOptionConst.ISHASRIGHT, String.valueOf(true));

        OperationResult result_save = SaveServiceHelper.saveOperate(bill2, new DynamicObject[]{newbill}, option);
        // 判断保存结果
        if (!result_save.isSuccess()) {
            String errMessage = result_save.getMessage();
            List<IOperateInfo> operateInfo = result_save.getAllErrorOrValidateInfo();
            for (IOperateInfo tempOperateInfo : operateInfo) {
                errMessage = errMessage + ";" + tempOperateInfo.getMessage();
            }
            throw new KDBizException("生成跟单任务控制台时保存失败：" + errMessage);
        } else {
            //跟单任务控制台
            long id = (long) result_save.getSuccessPkIds().get(0);
            DynamicObject yem_tracktaskconsole = BusinessDataServiceHelper.loadSingle(id, "yem_tracktaskconsole");
            DynamicObject yem_billtype = yem_tracktaskconsole.getDynamicObject("yem_billtype");//跟单任务控制台单据类型
            DynamicObjectCollection yem_es_materialinfo = yem_tracktaskconsole.getDynamicObjectCollection("yem_es_materialinfo");
            //外销合同子单据体
            DynamicObjectCollection yem_plandetail_entry = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");
            for (int i = 0; i < yem_plandetail_entry.size(); i++) {//外销合同子单据体
                DynamicObject plandetail = yem_plandetail_entry.get(i);
                for (int k = 0; k < yem_es_materialinfo.size(); k++) {//跟单任务控制台
                    DynamicObject aterialinfo = yem_es_materialinfo.get(k);//跟单子分录
                    String yem_businesssort1 = plandetail.getString("yem_businesssort1");
                    if (yem_businesssort1.equals("Z") && yem_billtype.getString("number").equals("yem_tracktaskconsole_zj")) {//整机
                        plandetail.set("yem_tracktaskconsole", yem_tracktaskconsole);
                        plandetail.set("yem_tracktaskconsoleid", id);
                    }
                    if (yem_businesssort1.equals("P") && yem_billtype.getString("number").equals("yem_tracktaskconsole_pj")) {//配件
                        plandetail.set("yem_tracktaskconsole", yem_tracktaskconsole);
                        plandetail.set("yem_tracktaskconsoleid", id);
                    }
                }
            }
        }
    }

    /**
     * 设置跟单任务控制台信息
     *
     * @param yem_shippingplan_entry 跟单任务分录
     * @param newbill                跟单任务控制台
     * @param key                    业务分类：整机(Z)、配件(P)
     */
    public void initData(DynamicObject yem_shippingplan_entry, DynamicObject newbill, String key) {
        Map yem_plandetail_entry_map = new HashMap();
        Map productsList = new HashMap();
        BigDecimal qty_s = BigDecimal.ZERO;
        //跟单任务明细子分录
        //获取跟单任务明细中的基础机型
        Map yem_productmodelmap = new HashMap();

        DynamicObjectCollection yem_plandetail_entry_s = yem_shippingplan_entry.getDynamicObjectCollection("yem_plandetail_entry");
        for (int i = 0; i < yem_plandetail_entry_s.size(); i++) {
            DynamicObject yem_plandetail_entry = yem_plandetail_entry_s.get(i);
            long yem_srcentryid = yem_plandetail_entry.getLong("yem_srcentryid");
            if (yem_plandetail_entry.getString("yem_businesssort1").equals(key)) {
                yem_plandetail_entry_map.put(yem_srcentryid, yem_plandetail_entry);
            }
            DynamicObject yem_productmodel1 = yem_plandetail_entry.getDynamicObject("yem_productmodel1");
            if (yem_productmodel1 != null) {
                long productid = yem_productmodel1.getLong("id");
                if (yem_productmodelmap.containsKey(productid)) {
                    yem_productmodelmap.put(productid, yem_productmodel1);
                }
            }
        }
        newbill.set("yem_nameplatetype", yem_shippingplan_entry.getString("yem_nameplatetypegd"));
        newbill.set("yem_nameplatelogo", yem_shippingplan_entry.getDynamicObject("yem_nameplatelogogd"));
        newbill.set("yem_nameplateqty", yem_shippingplan_entry.getInt("yem_nameplateqtygd"));
        newbill.set("yem_placemark", yem_shippingplan_entry.getString("yem_placemark"));
        newbill.set("yem_acshipdate", yem_shippingplan_entry.getString("yem_acshipdate1"));

        //商品明细

        DynamicObjectCollection yem_es_materialinfo_s = newbill.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal yem_thisqty = BigDecimal.ZERO;
        for (int i = 0; i < yem_es_materialinfo_s.size(); i++) {
            DynamicObject yem_es_materialinfo = yem_es_materialinfo_s.get(i);
            long yem_sourceentryid = yem_es_materialinfo.getLong("yem_sourceentryid");
            DynamicObject yem_plandetail_entry = (DynamicObject) yem_plandetail_entry_map.get(yem_sourceentryid);
            if (yem_plandetail_entry != null) {
                yem_thisqty = yem_thisqty.add(yem_plandetail_entry.getBigDecimal("yem_qty2"));
                BigDecimal yem_qty = yem_plandetail_entry.getBigDecimal("yem_qty2");//数量
                BigDecimal yem_baseqty = yem_plandetail_entry.getBigDecimal("yem_baseqty1");//基本数量
                yem_es_materialinfo.set("yem_qty", yem_qty);
                yem_es_materialinfo.set("yem_baseqty", yem_baseqty);
                yem_es_materialinfo.set("yem_nqty", yem_qty);
                BigDecimal yem_amt = yem_qty.multiply(yem_es_materialinfo.getBigDecimal("yem_price"));
                yem_es_materialinfo.set("yem_amt", yem_amt);
                yem_es_materialinfo.set("yem_locamt", yem_amt.multiply(newbill.getBigDecimal("yem_exrate")));
                qty_s = BigDecimalUtils.add(qty_s, yem_qty, 10);
                DynamicObject yem_productmodel = yem_es_materialinfo.getDynamicObject("yem_productmodel");
                if (yem_productmodel != null) {
                    DynamicObject yem_products = yem_productmodel.getDynamicObject("yem_products");
                    if (yem_products != null) {
                        long yem_productsid = yem_products.getLong("id");
                        if (!productsList.containsKey(yem_productsid)) {
                            productsList.put(yem_productsid, yem_qty);
                        } else {
                            productsList.replace(yem_productsid, BigDecimalUtils.add(productsList.get(yem_productsid), yem_qty, 10));
                        }
                    }

                }

                if ("Z".equals(key)) {
                    DynamicObjectCollection yem_multiconfig_s = yem_es_materialinfo.getDynamicObjectCollection("yem_multiconfig");
                    for (int j = 0; j < yem_multiconfig_s.size(); j++) {
                        DynamicObject yem_multiconfig = yem_multiconfig_s.get(j);
                        yem_multiconfig.set("yem_unitset", yem_qty);//台数
                    }
                    DynamicObjectCollection yem_retrofitting_s = yem_es_materialinfo.getDynamicObjectCollection("yem_retrofitting");
                    for (int j = 0; j < yem_retrofitting_s.size(); j++) {
                        DynamicObject yem_retrofitting = yem_retrofitting_s.get(j);
                        BigDecimal yem_singleqty = yem_retrofitting.getBigDecimal("yem_singleqty");//单台数量
                        BigDecimal yem_qtyamt = BigDecimalUtils.multiply(yem_singleqty, yem_qty, 10);//总数量
                        yem_retrofitting.set("yem_qty1", yem_qty);
                        yem_retrofitting.set("yem_qtyamt", yem_qtyamt);
                    }
                }
            } else {
                yem_es_materialinfo_s.remove(i--);
            }
        }
        newbill.set("yem_thisqty", yem_thisqty);
        if ("Z".equals(key)) {
            //随机资料及配件工具包
            DynamicObjectCollection yem_es_salesorder_p_s = newbill.getDynamicObjectCollection("yem_es_salesorder_p");
            for (int i = 0; i < yem_es_salesorder_p_s.size(); i++) {
                BigDecimal pcstype = BigDecimal.ZERO;
                DynamicObject yem_es_salesorder_p = yem_es_salesorder_p_s.get(i);
                BigDecimal yem_bicycleqty = yem_es_salesorder_p.getBigDecimal("yem_bicycleqty");//单车数量
                DynamicObject yem_accessorytype = yem_es_salesorder_p.getDynamicObject("yem_accessorytype");
                if (yem_accessorytype != null) {
                    long accessorytype = yem_accessorytype.getLong("id");
                    if (productsList.containsKey(accessorytype)) {
                        pcstype = (BigDecimal) productsList.get(accessorytype);
                    } else {
                        yem_es_salesorder_p_s.remove(i--);
                    }
                }
                BigDecimal yem_acallqty = BigDecimalUtils.multiply(yem_bicycleqty, pcstype, 10);//总数量
                yem_es_salesorder_p.set("yem_acallqty", yem_acallqty);
                yem_es_salesorder_p.set("yem_pcstype", pcstype);//机型台式
            }
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject datas = model.getDataEntity(true);
        String key = e.getProperty().getName();
        int rowIndex = e.getRow();
        QFilter qFilter = null;
        String businesssort = (String) model.getValue("yem_businesssort", rowIndex);
        switch (key) {
            //过滤产品销售类型
            case "yem_salesmethod":
                DynamicObject types = datas.getDynamicObject("yem_billtype");
                if (types == null) {
                    this.getView().showMessage("请选择单据类型");
                    e.setCancel(true);
                } else {
                    qFilter = new QFilter("yem_businessclassify", QCP.equals,
                            types.getString("number").equals("yem_es_salesorder_ZJ") ||
                                    types.getString("number").equals("yem_es_salesorder_nmzj") ? "zj" : "pj");
                    e.addCustomQFilter(qFilter);
                }
                break;
            case "yem_classification":
                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_bd_products":
                DynamicObject billtype = datas.getDynamicObject("yem_billtype");
                if (billtype == null) return;
                String billtypeString = billtype.getString("number");
                if ("yem_es_salesorder_ZJ".equals(billtypeString) || "yem_es_salesorder_nmzj".equals(billtypeString)) {
                    e.addCustomQFilter(new QFilter("yem_businesssort", QCP.equals, "Z"));
                }
                if ("yem_es_salesorder_PJ".equals(billtypeString) || "yem_es_salesorder_nmpj".equals(billtypeString)) {
                    e.addCustomQFilter(new QFilter("yem_businesssort", 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;
            case "yem_internationalrate":
                DynamicObject yem_currency = datas.getDynamicObject("yem_currency");
                if (yem_currency != null) {
                    qFilter = new QFilter("yem_currency.number", QCP.equals, yem_currency.getString("number"));
                    qFilter.and(new QFilter("enable", QCP.equals, "1"));
                    e.addCustomQFilter(qFilter);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 选择基础机型 携带报关分类
     *
     * @param model
     * @param rowIndex
     */
    private void bringCustomsClassification(IDataModel model, int rowIndex) {
        IFormView view = this.getView();

        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        if (products != null) {
            QFilter qFilter = filterCustomClass(rowIndex);
            DynamicObject[] collection = BusinessDataServiceHelper.load("yem_classification", "id", qFilter.toArray());
            if (collection.length == 1) {
                model.setValue("yem_customclass", collection[0].getPkValue(), rowIndex);
            }
        } else {
            view.showMessage("请先维护基本信息-产品分类字段!");
        }
    }

    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 beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        String operateKey = ((FormOperate) e.getSource()).getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView view = this.getView();

        // 双签附件回填
        if ("contractresigning".equals(operateKey)) {
            String billstatus = dataEntity.getString("billstatus");
            if ("C".equals(billstatus)) {
                FormShowParameter parameter = new FormShowParameter();
                parameter.setStatus(OperationStatus.ADDNEW);
                parameter.getOpenStyle().setShowType(ShowType.Modal);
                parameter.setFormId("yem_es_contractresign");
                parameter.setCloseCallBack(new CloseCallBack(this, "yem_es_contractresign"));
                view.showForm(parameter);
            } else {
                this.getView().showErrorNotification("当前合同还未审核，不允许回签！");
            }
        }


        if ("contractdelsigning".equals(operateKey)) {
            AttachmentPanel panel = getControl("yem_attachmentpanelap");
            List<Map<String, Object>> attachmentData = panel.getAttachmentData();
            if (!attachmentData.isEmpty()) {
                attachmentData.forEach(panel::remove);
                List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(dataEntity.getDynamicObjectType().getName(), dataEntity.getPkValue(), "yem_attachmentpanelap");
                dataEntity.set("yem_attachmentcountfield", attachments.size());
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                view.invokeOperation("refresh");
            }
        }

        if ("signconfirm".equals(operateKey)) {
            model.setValue("yem_signconfirmstatus", "A");
            setLockIfSignBtn();
            view.invokeOperation("save");
        }

        if ("signcancel".equals(operateKey)) {
            model.setValue("yem_signconfirmstatus", "B");
            setLockIfSignBtn();
            view.invokeOperation("save");
        }

        if ("submit".equals(operateKey)) {
            setNewpPrice(dataEntity, view);
            checkGiftsGivenNumber(dataEntity, e);
        }

        if ("save".equals(operateKey)) {
            setImpactPrice();
        }
    }

    /**
     * 如果明细行该机型的的汇总数量和配件赠送中不一致，提示
     *
     * @param dataEntity
     * @param e
     */
    private void checkGiftsGivenNumber(DynamicObject dataEntity, BeforeDoOperationEventArgs e) {
        String billtype = dataEntity.getString("yem_billtype.number");
        if ("yem_es_salesorder_ZJ".equals(billtype) || "yem_es_salesorder_nmzj".equals(billtype)) {
            // 是否配件赠送
            String isgiftgiveparts = dataEntity.getString("yem_isgiftgiveparts");
            if (!"A".equals(isgiftgiveparts)) return;
            DynamicObjectCollection giftCollection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_zp");
            DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            Map<Long, BigDecimal> map = new HashMap<>();
            for (DynamicObject dynamicObject : materialinfo) {
                String businesssort = dynamicObject.getString("yem_businesssort");
                boolean ifgift = dynamicObject.getBoolean("yem_ifgift");
                if ("Z".equals(businesssort) && !ifgift) {
                    DynamicObject productmodel = dynamicObject.getDynamicObject("yem_productmodel");
                    if (productmodel == null) continue;
                    productmodel = BusinessDataServiceHelper.loadSingle(productmodel.getPkValue(), productmodel.getDynamicObjectType().getName());
                    if (productmodel == null) continue;
                    DynamicObject products = productmodel.getDynamicObject("yem_products");
                    if (products == null) continue;
                    long id = products.getLong("id");
                    BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                    if (map.containsKey(id)) {
                        map.put(id, map.get(id).add(qty));
                    } else {
                        map.put(id, qty);
                    }
                }
            }

            StringBuilder sb = new StringBuilder();
            for (DynamicObject dynamicObject : giftCollection) {
                int index = giftCollection.indexOf(dynamicObject);
                DynamicObject giveproactype = dynamicObject.getDynamicObject("yem_giveproactype");
                if (giveproactype == null) continue;
                long id = giveproactype.getLong("id");
                if (map.containsKey(id)) {
                    BigDecimal qty = map.get(id);
                    BigDecimal qtyint = dynamicObject.getBigDecimal("yem_qtyint");
                    if (qtyint.compareTo(qty) != 0) {
                        sb.append(String.format("配件赠送明细第 [ %s ] 行，赠送的数量和明细信息中相关机型数量不一致！\n", index + 1));
                    }
                } else {
                    sb.append(String.format("配件赠送明细第 [ %s ] 行，赠送的数量和明细信息中相关机型数量不一致！\n", index + 1));
                }
            }
            if (sb.length() > 0) {
                ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("checkGiftsGivenNumber", this);
                this.getView().showConfirm(sb.toString(), MessageBoxOptions.OKCancel, confirmCallBackListener);
//                this.getView().showTipNotification(sb.toString());
                e.setCancel(true);
            }
//            DynamicObject productmodel = (DynamicObject) model.getValue("yem_productmodel", rowIndex);
//            if (productmodel == null) return;
//            productmodel = BusinessDataServiceHelper.loadSingle(productmodel.getPkValue(), productmodel.getDynamicObjectType().getName());
//            DynamicObject products = productmodel.getDynamicObject("yem_products");
//            if (products == null) return;
//            Long detailId = (Long) products.getPkValue();
//            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_zp");
//            for (DynamicObject object : collection) {
//                int index = collection.indexOf(object);
//                DynamicObject giftproactype = object.getDynamicObject("yem_giveproactype");
//                if (giftproactype == null) continue;
//                Long giftId = (Long) giftproactype.getPkValue();
//                if (Objects.equals(giftId, detailId)) {
//
//                }
//            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        super.confirmCallBack(e);
        String callBackId = e.getCallBackId();
        if ("checkGiftsGivenNumber".equals(callBackId)) {
            if (MessageBoxResult.Yes.equals(e.getResult())) {
                DynamicObject dataEntity = this.getModel().getDataEntity(true);
                OperationResult result = OperationServiceHelper.executeOperate("submit",
                        dataEntity.getDynamicObjectType().getName(),
                        new DynamicObject[]{dataEntity}, OperateOption.create());
                if (!result.isSuccess()) {
                    throw new KDBizException(result.getMessage());
                } else {
                    this.getView().invokeOperation("refresh");
                }
            }
        }
    }

    public void setLockIfSignBtn() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        // 回签确认状态 A 已确认 B 未确认
        String signconfirmstatus = dataEntity.getString("yem_signconfirmstatus");
        // 双签合同附件数
        int attchcount = dataEntity.getInt("yem_attachmentcountfield");

        // 已确认
        if ("A".equals(signconfirmstatus)) {
            view.setEnable(false, "yem_contractreturn");
            view.setEnable(false, "yem_contractrereturn");
        } else {
            view.setEnable(true, "yem_contractreturn");
            view.setEnable(true, "yem_contractrereturn");
        }

        // 已回签
        if (attchcount > 0) {
            // 已回签 已确认
            if ("A".equals(signconfirmstatus)) {
                view.setVisible(true, "yem_baritemap4");
                view.setEnable(false, "yem_baritemap4");
                view.setVisible(true, "signcancel");

                view.setEnable(false, "yem_contractreturn");
                view.setEnable(false, "yem_contractrereturn");
            } else {
                // 已回签 未确认
                view.setVisible(true, "yem_baritemap4");
                view.setVisible(false, "signcancel");
                view.setEnable(true, "yem_baritemap4");
                view.setEnable(true, "yem_contractreturn");
                view.setEnable(true, "yem_contractrereturn");
            }
        } else {
            // 未回签
            view.setVisible(false, "yem_baritemap4");
            view.setVisible(false, "signcancel");
        }
    }

    /**
     * @description 行关闭
     * @author xwudd
     * return
     * @time 2023/11/8 15:24
     */

    public void rowClose() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Boolean flag = true;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            String lineClossTaTe = (String) model.getValue("yem_lineclosstate", i);
            if ("A".equals(lineClossTaTe)) {
                flag = false;
            }
        }
        if (flag) {
            model.setValue("yem_closestatus", "B");
            model.setValue("yem_billcloseuser", 1L);
            model.setValue("yem_billclosedate", new Date());
            view.invokeOperation("save");
        }
    }

    /**
     * @description 行反关闭
     * @author xwudd
     * return
     * @time 2023/11/8 15:24
     */

    public void rowUnClose() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        model.setValue("yem_closestatus", "A");
        model.setValue("yem_billcloseuser", null);
        model.setValue("yem_billclosedate", null);
        view.invokeOperation("save");
    }

    /**
     * @description 订单关闭
     * @author xwudd
     * return
     * @time 2023/11/8 15:23
     */

    public void billClose() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            model.setValue("yem_lineclosstate", "B", i);
            model.setValue("yem_closeuser", RequestContext.get().getCurrUserId(), i);
            model.setValue("yem_closedate", new Date(), i);
        }
        view.invokeOperation("save");
    }

    /**
     * @description 订单反关闭
     * @author xwudd
     * return
     * @time 2023/11/8 15:23
     */

    public void billUnClose() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            model.setValue("yem_lineclosstate", "A", i);
            model.setValue("yem_closeuser", null, i);
            model.setValue("yem_closedate", null, i);
        }
        view.invokeOperation("save");
    }


}