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

import com.google.common.collect.Maps;
import com.yem.em.utils.BigDecimalUtils;
import com.yem.wm.es.Util.ZJUtils;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.StringUtils;
import org.apache.commons.compress.utils.Lists;

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

import static com.yem.wm.es.salesorder.utils.SalesOrderUtils.*;
import static com.yem.wm.es.storagetrans.form.StorageTransEdit.calculateExportAmount;

/**
 * @author xwudd
 * @date 9:52
 * @Description
 **/
public class DeclareDocxEdit extends AbstractBillPlugIn implements BeforeF7SelectListener {


    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        FormShowParameter fsp = this.getView().getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        if (OperationStatus.ADDNEW == status) {
            ZJUtils.totalContractNo(model);
            Getbilltype();
        }
//        genTradeTerms(model);
//        genPortEnName(this.getModel(), this.getView());
    }

    /**
     * 海运费=商品明细的销售金额合计值/财务信息的金额（价格条款）*储运托单的海运费；
     * * 注：如果一张储运托单生成了多张报关单，需要在最后一次生成报关单时处理尾差。每次生成报关单时，判断该报关单是否由储运全部下推生成，
     * * 如果不是，那么按照公式计算海运费，如果是，需要判断该报关单的海运费+其他报关单的海运费是否完全等于上游储运的海运费，
     * * 如果相等不需特殊处理，如果不相等需要将尾差在该报关进行处理。
     */
    private static void setOutForm(IDataModel model) {
        DynamicObject dt = model.getDataEntity(true);
        //确定本次为 最后一次生成报关单
        boolean flag = true;
        //储运托单 海运费
        BigDecimal decimal = BigDecimal.ZERO;
        long aLong = dt.getLong("yem_sourcebillid");
        if (YEM.isNotEmpty(aLong)) {
            DynamicObject object2 = BusinessDataServiceHelper.loadSingle(aLong, "yem_es_storagetrans");
            if (object2 != null) {
                DynamicObject object = BusinessDataServiceHelper.loadSingle(object2.getPkValue(), object2.getDynamicObjectType().getName());
                if (object != null) {
                    decimal = object.getBigDecimal("yem_freightamt");
                    DynamicObjectCollection dynamicObjectCollection1 = object.getDynamicObjectCollection("yem_es_materialinfo");
                    DynamicObjectCollection dynamicObjectCollectionNow = dt.getDynamicObjectCollection("yem_es_materialinfo");
                    int row = 0;
                    //报关单总数量
                    BigDecimal sonCount = BigDecimal.ZERO;
                    //储运未报关总数量
                    BigDecimal faCount = BigDecimal.ZERO;
                    //子父分录行数相同
                    if (dynamicObjectCollection1 != null && dynamicObjectCollectionNow != null && dynamicObjectCollectionNow.size() == dynamicObjectCollection1.size()) {
                        for (DynamicObject dc : dynamicObjectCollection1) {
                            BigDecimal yemUnassdeclaqty = dc.getBigDecimal("yem_unassdeclaqty");
                            if (BigDecimal.ZERO.compareTo(yemUnassdeclaqty) != 0) {
                                if (dynamicObjectCollectionNow != null && dynamicObjectCollectionNow.size() > row) {
                                    DynamicObject object1 = dynamicObjectCollectionNow.get(row);
                                    if (object1 != null) {
                                        //来源分录id等于父明细内码时
                                        Object pkValue = dc.getPkValue();
                                        long sourceentryid = object1.getLong("yem_sourceentryid");
                                        if (pkValue != null && pkValue.equals(sourceentryid)) {
                                            BigDecimal yemQty = object1.getBigDecimal("yem_qty");
                                            if (YEM.isNotEmpty(yemUnassdeclaqty) && yemUnassdeclaqty.compareTo(yemQty) != 0) {
                                                flag = false;
                                            }
                                        }
                                    }
                                }

                            }
                            row++;
                        }
                    } else {

                        int rowCount = 0;
                        for (DynamicObject dts : dynamicObjectCollection1) {
                            BigDecimal yemUnassdeclaqty = dts.getBigDecimal("yem_unassdeclaqty");
                            if (YEM.isNotEmpty(yemUnassdeclaqty)) {
                                rowCount++;
                            }
                        }
                        //子父分录行数不同
                        //父分录 未报关数量不为0的行数要不等于子分类行数
                        if (dynamicObjectCollectionNow != null && dynamicObjectCollectionNow.size() != rowCount) {
                            flag = false;
                        } else {
                            //  //父分录 未报关数量不为0的行数要等于子分类行数 且数量之和要等于父分录 未报关数量之和
                            for (DynamicObject dynamicObject : dynamicObjectCollectionNow) {
                                BigDecimal yemQty = dynamicObject.getBigDecimal("yem_qty");
                                sonCount = sonCount.add(yemQty);
                            }
                            for (DynamicObject dc : dynamicObjectCollection1) {
                                BigDecimal yemUnassdeclaqty = dc.getBigDecimal("yem_unassdeclaqty");
                                faCount = faCount.add(yemUnassdeclaqty);
                            }
                            if (faCount.compareTo(sonCount) != 0) {
                                flag = false;
                            }

                        }
                    }


                }
            }


        }
        //处理海运费尾零
        if (flag) {
            DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_declaredocx", "yem_reightamt",
                    new QFilter[]{
                            //new QFilter("billstatus", QCP.equals, "C"),
                            new QFilter("yem_sourcebillid", QCP.equals, aLong)
                    });
            if (load.length > 1) {
                BigDecimal count = BigDecimal.ZERO;
                for (DynamicObject dc : load) {
                    BigDecimal yemReightamt = dc.getBigDecimal("yem_reightamt");
                    count = count.add(yemReightamt);
                }
                BigDecimal yemReightamt = dt.getBigDecimal("yem_reightamt");
                yemReightamt = count.add(yemReightamt);
                if (yemReightamt.compareTo(decimal) != 0) {
//                        BigDecimal subtract = decimal.subtract(yemReightamt);
//                        BigDecimal yemReightamt1 = dt.getBigDecimal("yem_reightamt");
                    //     dt.set("yem_reightamt",decimal.subtract(count));
                    model.setValue("yem_reightamt", decimal.subtract(count));
                }
            }
        }
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        IDataModel model = this.getModel();
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        switch (name) {

        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        IDataModel model = this.getModel();
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        switch (name) {
            case "yem_contractnumbers_m"://合同号
                ZJUtils.totalContractNo(model);
                break;
            case "yem_reightamt"://海运费尾零处理
                this.getModel().beginInit();
                setOutForm(model);
                this.getModel().endInit();

                BigDecimal reightamt = (BigDecimal) model.getValue("yem_reightamt");
                //yem_reightamtbase = yem_reightamtrate * yem_reightamt
                //海运费（本位币） = 海运费汇率 * 海运费（原币）
                BigDecimal reightamtrate = (BigDecimal) model.getValue("yem_reightamtrate");
                BigDecimal base = reightamtrate.multiply(reightamt);
                model.setValue("yem_reightamtbase", base);
                //yem_reightamtend = yem_reightamtbase / yem_exrate
                //海运费（结算币别） = 海运费（本位币） / 汇率
                BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
                model.setValue("yem_reightamtend", BigDecimalUtils.div(base, exrate, 2));
                this.getView().updateView("yem_reightamt");
                this.getView().updateView("yem_reightamtbase");
                this.getView().updateView("yem_reightamtend");

                break;
            case "yem_cusqty":
//            case "yem_cusamount":
//            case "yem_cusgrossweight":
//            case "yem_cusnetweight":
            case "yem_cusdecpiecesum":
            case "yem_cusgrossweightsum":
            case "yem_cusvolm3sum":
            case "yem_cusnetweightsum":
//            case "yem_cusvolm3":
                reCalcAmount(rowIndex);
                break;
            case "yem_shipports":
                genShipPortEnName(this.getModel());
                genTradeTermsShipports(this.getModel(), this.getView());
                genTradeTerms(this.getModel().getDataEntity(), this.getView());
                break;
            case "yem_destports":
                genDescPortEnName(this.getModel());
                genTradeTermsDestports(this.getModel(), this.getView());
                genTradeTerms(this.getModel().getDataEntity(), this.getView());
                break;
            case "yem_priceitem":
                genTradeTerms(this.getModel().getDataEntity(), this.getView());
                genTradeTermsDestports(this.getModel(), this.getView());
                genTradeTermsShipports(this.getModel(), this.getView());
                break;
            case "yem_cyreightamt":
                DynamicObject exratetable = (DynamicObject) model.getValue("yem_exratetable");
                DynamicObject cyreightamt = (DynamicObject) model.getValue("yem_cyreightamt");
                DynamicObject currencybase = (DynamicObject) model.getValue("yem_currencybase");
                Date exratedate = (Date) model.getValue("yem_exratedate");
                BigDecimal rate = YEM.getExchangeRate(exratetable, cyreightamt, currencybase, exratedate);
                model.setValue("yem_reightamtrate", rate);
                break;
        }
    }

    /**
     * 数量和金额手动修改时，反算单价
     *
     * @param rowIndex
     */
    private void reCalcAmount(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_declare_ec");
        DynamicObject dynamicObject = collection.get(rowIndex);
        // 数量
        BigDecimal cusqty = dynamicObject.getBigDecimal("yem_cusqty");
        // 金额
        BigDecimal cusamount = dynamicObject.getBigDecimal("yem_cusamount");
        if (YEM.isNotEmpty(cusqty) && YEM.isNotEmpty(cusamount)) {
//            model.setValue("yem_cusconsalesprice", cusamount.divide(cusqty, 4, RoundingMode.HALF_UP), rowIndex);
            model.setValue("yem_cusconsalesprice", BigDecimalUtils.div(cusamount, cusqty, 4), rowIndex);
        }
        // 毛重
//        BigDecimal cusgrossweight = dynamicObject.getBigDecimal("yem_cusgrossweight");
        // 件数
        BigDecimal cusdecpiecesum = dynamicObject.getBigDecimal("yem_cusdecpiecesum");
        // 总毛重
        BigDecimal cusgrossweightsum = dynamicObject.getBigDecimal("yem_cusgrossweightsum");
        if (YEM.isNotEmpty(cusgrossweightsum) && YEM.isNotEmpty(cusdecpiecesum)) {
            model.setValue("yem_cusgrossweight", BigDecimalUtils.div(cusgrossweightsum, cusdecpiecesum, 4), rowIndex);
        }
        // 体积M3
        BigDecimal cusvolm3 = dynamicObject.getBigDecimal("yem_cusvolm3");
        // 总体积M3
        BigDecimal cusvolm3sum = dynamicObject.getBigDecimal("yem_cusvolm3sum");

        if (YEM.isNotEmpty(cusvolm3) && YEM.isNotEmpty(cusdecpiecesum)) {
//            model.setValue("yem_cusvolm3", cusvolm3sum.divide(cusdecpiecesum, 4, RoundingMode.HALF_UP), rowIndex);
            model.setValue("yem_cusvolm3", BigDecimalUtils.div(cusvolm3sum, cusdecpiecesum, 4), rowIndex);
        }

        // 净重
        BigDecimal cusnetweight = dynamicObject.getBigDecimal("yem_cusnetweight");
        // 总净重
        BigDecimal cusnetweightsum = dynamicObject.getBigDecimal("yem_cusnetweightsum");
        if (YEM.isNotEmpty(cusnetweight)) {
//            model.setValue("yem_cusnetweight", cusnetweightsum.divide(cusdecpiecesum, 4, RoundingMode.HALF_UP), rowIndex);
            model.setValue("yem_cusnetweight", BigDecimalUtils.div(cusnetweightsum, cusdecpiecesum, 4), rowIndex);
        }

    }


    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        super.afterDeleteRow(e);
        IDataModel model = this.getModel();
        String name = e.getEntryProp().getName();
        switch (name) {
            case "yem_es_materialinfo"://商品分录
                ZJUtils.totalContractNo(model);
                break;
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("save".equals(operateKey)) {
//            genTradeTermsDestports(model, this.getView());
//            genTradeTermsShipports(model, this.getView());

            calculateExportAmount(dataEntity);
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        boolean isSuccess = false;
        if (e.getOperationResult() != null) {
            isSuccess = e.getOperationResult().isSuccess();
        }//报关分类 海关编码
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        String operateKey = e.getOperateKey();
//        if (StringUtils.isNotEmpty(operateKey) && isSuccess) {
        if (operateKey.equals("cocudeclaration_s") || operateKey.equals("cocudeclaration")) {
            model.deleteEntryData("yem_es_declare_ec");
            model.deleteEntryData("yem_es_declare_ecd");
            //报关合并
            DynamicObjectCollection entryRows = model.getEntryEntity("yem_es_materialinfo");//商品明细
            List<DynamicObject> compListZ = Lists.newArrayList();
            List<DynamicObject> compListP = Lists.newArrayList();

            List<Long> pjrows = new ArrayList<>();//存放配件类型的序号
            Map<String, DynamicObjectCollection> jiCollection = new HashMap<>();
            for (DynamicObject entryRow : entryRows) {
                String yemContractnumbersM = entryRow.getString("yem_contractnumbers_m");//获取分录外销合同号
                QFilter qFilter = new QFilter("billno", QCP.equals, yemContractnumbersM);//
                DynamicObject[] yem_em_substitution = BusinessDataServiceHelper.load("yem_es_salesorder", "yem_billtype.name"
                        , new QFilter[]{qFilter}, null);
                if (yem_em_substitution.length > 0) {
                    //1、【商品明细】的明细行关联的外销合同号如果是外贸整机合同，那么将明细行直接获取到【报关商品】页签，除【已开票数量】字段外，其他字段一一对应；
                    if ("外贸整机合同".equals(yem_em_substitution[0].getString("yem_billtype.name"))) {
                        if ("cocudeclaration_s".equals(operateKey)) {
                            String businesssort = entryRow.getString("yem_businesssort");
                            if ("Z".equals(businesssort)) {
                                compListZ.add(entryRow);
                            }
                            if ("P".equals(businesssort)) {
                                compListP.add(entryRow);
                            }
//                                continue;
                        }
                        // 旧合并规则
                        if ("cocudeclaration".equals(operateKey)) {
                            int row = model.createNewEntryRow("yem_es_declare_ec");//新增报关商品

                            model.setValue("yem_cusboxgoods", entryRow.get("yem_materiel"), row);//商品编码
                            model.setValue("yem_decmatericalname", entryRow.get("yem_customclass.name"), row);//报关名称
                            model.setValue("yem_decmatericalenname", entryRow.get("yem_declareproducten"), row);//英文名称
                            model.setValue("yem_cushscode", entryRow.get("yem_hscode"), row);//海关编码
                            model.setValue("yem_cusunit", entryRow.get("yem_unit"), row);//计量单位
                            BigDecimal qty = (BigDecimal) entryRow.get("yem_qty");//数量
                            model.setValue("yem_cusqty", qty, row);//数量
                            model.setValue("yem_cusconsalesprice", entryRow.get("yem_sellprice"), row);//单价
                            model.setValue("yem_cusamount", entryRow.get("yem_sellamt"), row);//金额
                            model.setValue("yem_cusdecpiecesum", entryRow.get("yem_gdecpiecesum"), row);//件数
                            model.setValue("yem_cusweightunit", entryRow.get("yem_weightunit"), row);//重量单位
                            BigDecimal grossweightsum = (BigDecimal) entryRow.get("yem_grossweightsum");//总毛重
                            model.setValue("yem_cusgrossweight", BigDecimalUtils.div(grossweightsum, qty, 4), row);//毛重
                            model.setValue("yem_cusvolm3", entryRow.get("yem_volm3"), row);//体积M3
                            model.setValue("yem_cusgrossweightsum", grossweightsum, row);//总毛重
                            model.setValue("yem_cusvolm3sum", entryRow.get("yem_volm3sum"), row);//总体积M3
                            model.setValue("yem_cuscontent", entryRow.get("yem_mxcontent"), row);//备注
                            model.setValue("yem_documenttypes", entryRow.get("yem_documenttype"), row);//单据类型
                            model.setValue("yem_taxrefundrates", entryRow.get("yem_degrate"), row);//退税率%
                            BigDecimal netweightsuma = (BigDecimal) entryRow.get("yem_netweightsuma");//总净重
                            model.setValue("yem_cusnetweight", BigDecimalUtils.div(netweightsuma, qty, 4), row);//净重
                            model.setValue("yem_cusnetweightsum", netweightsuma, row);//总净重
                            model.setValue("yem_declarationelee", entryRow.get("yem_declarationeleb"), row);//申报要素（文本）
                            model.setValue("yem_declareunit_e", entryRow.get("yem_declareunit"), row);//报关单位
                            // 产品机型
                            DynamicObject productmodel = (DynamicObject) entryRow.get("yem_productmodel");
                            if (productmodel != null) {
                                model.setValue("yem_proctype", productmodel.get("yem_products.id"), row);
                            }
                            SetEntryValue(entryRow.getLong("seq"), entryRow.getLong("id"), entryRow.getDynamicObject("yem_materiel"),
                                    row + 1, entryRow.getString("yem_customclass.name"));
                        }
                    }
                    //2、【商品明细】的明细行关联的外销合同号如果是外贸配件合同，根据【商品明细】的报关分类+海关编码作为分组依据，合并数据到【报关商品】页签：
                    //（1）数量、金额、件数、总毛重、总体积M3：【商品明细】行汇总生成；
                    //（2）单价（保留4位小数）=金额/数量，毛重=总毛重/件数，体积=总体积M3/件数；
                    //（3）除上述字段外的其他字段，默认取明细行分组后的第一行数据。
                    //（4）【已开票数量】不做处理。
                    if ("外贸配件合同".equals(yem_em_substitution[0].getString("yem_billtype.name"))) {
                        pjrows.add(entryRow.getLong("seq"));
                    }
                }
            }
//                if (pjrows.size() > 0) {
            for (long pjrow : pjrows) {
                DynamicObject yemEsDeclaredocs = model.getEntryRowEntity("yem_es_materialinfo", ((int) pjrow - 1));
                DynamicObjectCollection mapDynamicObject = new DynamicObjectCollection();
                String yemCustomclass = yemEsDeclaredocs.getString("yem_customclass");
                String yem_hscode = yemEsDeclaredocs.getString("yem_hscode");
                //cocudeclaration
                String sellprice = yemEsDeclaredocs.getBigDecimal("yem_sellprice").stripTrailingZeros().toPlainString();
                //cocudeclaration
                String keystring = yemCustomclass + "," + yem_hscode;
//                if ("cocudeclaration_s".equals(operateKey)) {
//                    keystring = yemCustomclass + "," + yem_hscode + "," + sellprice;
//                }
//                if ("cocudeclaration".equals(operateKey)) {
//                }

//                if (!jiCollection.containsKey(keystring)) {
                for (long pjrow_S : pjrows) {
                    DynamicObject yemEsDeclaredoc_S = model.getEntryRowEntity("yem_es_materialinfo", ((int) pjrow_S - 1));
                    String yemCustomclass_2 = yemEsDeclaredoc_S.getString("yem_customclass");
                    String yem_hscode_2 = yemEsDeclaredoc_S.getString("yem_hscode");
                    //cocudeclaration
                    String sellprice_2 = yemEsDeclaredoc_S.getBigDecimal("yem_sellprice").stripTrailingZeros().toPlainString();
                    //cocudeclaration
                    String keystring_2 = null;
//                    if ("cocudeclaration_s".equals(operateKey)) {
//                        keystring_2 = yemCustomclass_2 + "," + yem_hscode_2 + "," + sellprice_2;
//                    }
//                    if ("cocudeclaration".equals(operateKey)) {
//                    }
                    keystring_2 = yemCustomclass_2 + "," + yem_hscode_2;
                    if (keystring.equals(keystring_2)) {
                        mapDynamicObject.add(yemEsDeclaredoc_S);
                    }
                }
                jiCollection.put(keystring, mapDynamicObject);
//                }
//                    }
//                    if (jiCollection.size() > 0) {
            }

            for (String key : jiCollection.keySet()) {
                DynamicObjectCollection value = jiCollection.get(key);
                if (value.isEmpty()) continue;
                DynamicObject dynamicObject = value.get(0);
                int row = model.createNewEntryRow("yem_es_declare_ec");//新增报关商品
                model.setValue("yem_cusboxgoods", dynamicObject.get("yem_materiel"), row);//商品编码
                model.setValue("yem_decmatericalname", dynamicObject.get("yem_customclass.name"), row);//报关名称
                model.setValue("yem_decmatericalenname", dynamicObject.get("yem_declareproducten"), row);//英文名称
                model.setValue("yem_cushscode", dynamicObject.get("yem_hscode"), row);//海关编码
                model.setValue("yem_cusunit", dynamicObject.get("yem_unit"), row);//计量单位
                model.setValue("yem_cusweightunit", dynamicObject.get("yem_weightunit"), row);//重量单位
                model.setValue("yem_cuscontent", dynamicObject.get("yem_mxcontent"), row);//备注
                model.setValue("yem_documenttypes", dynamicObject.get("yem_documenttype"), row);//单据类型
                model.setValue("yem_taxrefundrates", dynamicObject.get("yem_degrate"), row);//退税率%
                model.setValue("yem_declarationelee", value.get(value.size() - 1).get("yem_declarationeleb"), row);//申报要素（文本）
                model.setValue("yem_declareunit_e", dynamicObject.get("yem_declareunit"), row);//报关单位
                // 产品机型
                DynamicObject productmodel = (DynamicObject) dynamicObject.get("yem_productmodel");
                if (productmodel != null) {
                    model.setValue("yem_proctype", productmodel.get("yem_products.id"), row);
                }
                BigDecimal yem_qty = new BigDecimal(0);
                BigDecimal yem_sellamt = new BigDecimal(0);
                BigDecimal yem_grossweightsum = new BigDecimal(0);
                BigDecimal yem_cusnetweightsum = new BigDecimal(0);
                BigDecimal yem_volm3sum = new BigDecimal(0);
                BigDecimal yem_gdecpiecesum = new BigDecimal(0);
                for (DynamicObject values : value) {
                    yem_qty = yem_qty.add(values.getBigDecimal("yem_qty"));
                    yem_sellamt = yem_sellamt.add(values.getBigDecimal("yem_sellamt"));
                    yem_gdecpiecesum = yem_gdecpiecesum.add(values.getBigDecimal("yem_gdecpiecesum"));
                    yem_grossweightsum = yem_grossweightsum.add(values.getBigDecimal("yem_grossweightsum"));
                    yem_volm3sum = yem_volm3sum.add(values.getBigDecimal("yem_volm3sum"));
                    yem_cusnetweightsum = yem_cusnetweightsum.add(values.getBigDecimal("yem_netweightsuma"));
                    SetEntryValue(values.getLong("seq"), values.getLong("id"), values.getDynamicObject("yem_materiel"),
                            row + 1, values.getString("yem_customclass.name"));

                }
                model.setValue("yem_cusqty", yem_qty, row);//数量
                model.setValue("yem_cusamount", yem_sellamt, row);//金额
                model.setValue("yem_cusdecpiecesum", yem_gdecpiecesum, row);//件数
                model.setValue("yem_cusgrossweightsum", yem_grossweightsum, row);//总毛重
                model.setValue("yem_cusvolm3sum", yem_volm3sum, row);//总体积M3
                model.setValue("yem_cusconsalesprice", BigDecimalUtils.div(yem_sellamt, yem_qty, 4), row);//单价
                model.setValue("yem_cusgrossweight", BigDecimalUtils.div(yem_grossweightsum, yem_gdecpiecesum, 4), row);//毛重
                model.setValue("yem_cusvolm3", BigDecimalUtils.div(yem_volm3sum, yem_gdecpiecesum, 4), row);//体积M3
                model.setValue("yem_cusnetweightsum", yem_cusnetweightsum, row);
                model.setValue("yem_cusnetweight", BigDecimalUtils.div(yem_cusnetweightsum, yem_gdecpiecesum, 4), row);//净重
//                        }
//                SetEntryValue(dynamicObject.getLong("seq"), dynamicObject.getLong("id"), dynamicObject.getDynamicObject("yem_materiel"),
//                        row + 1, dynamicObject.getString("yem_customclass.name"));
            }

            //新合并规则
            HashMap<String, List<DynamicObject>> compMapZ = Maps.newHashMap();
            HashMap<String, List<DynamicObject>> compMapP = Maps.newHashMap();

            for (DynamicObject dynamicObject : compListZ) {
                DynamicObject productmodel = dynamicObject.getDynamicObject("yem_productmodel");
                long productId = 0L;
                if (YEM.isNotEmpty(productmodel)) {
                    DynamicObject products = productmodel.getDynamicObject("yem_products");
                    if (YEM.isNotEmpty(products)) {
                        productId = products.getLong("id");
                    }
                }
                long customclass = dynamicObject.getLong("yem_customclass.id");
                long hscode = dynamicObject.getLong("yem_hscode.id");
                String sellprices = dynamicObject.getBigDecimal("yem_sellprice").stripTrailingZeros().toPlainString();
                // 产品机型+报关分类+海关编码+销售单价
                String key = productId + "_" + customclass + "_" + hscode + "_" + sellprices;
                if (compMapZ.containsKey(key)) {
                    List<DynamicObject> list = compMapZ.get(key);
                    list.add(dynamicObject);
                    compMapZ.put(key, list);
                } else {
                    ArrayList<DynamicObject> list = Lists.newArrayList();
                    list.add(dynamicObject);
                    compMapZ.put(key, list);
                }
            }

            for (DynamicObject dynamicObject : compListP) {
                long customclass = dynamicObject.getLong("yem_customclass.id");
                long hscode = dynamicObject.getLong("yem_hscode.id");
                String sellprices = dynamicObject.getBigDecimal("yem_sellprice").stripTrailingZeros().toPlainString();
                // 产品机型+报关分类+海关编码+销售单价
                String key = customclass + "_" + hscode + "_" + sellprices;
                if (compMapP.containsKey(key)) {
                    List<DynamicObject> list = compMapP.get(key);
                    list.add(dynamicObject);
                    compMapP.put(key, list);
                } else {
                    ArrayList<DynamicObject> list = Lists.newArrayList();
                    list.add(dynamicObject);
                    compMapP.put(key, list);
                }
            }

            for (Map.Entry<String, List<DynamicObject>> entry : compMapP.entrySet()) {
                List<DynamicObject> value = entry.getValue();
                int row = model.createNewEntryRow("yem_es_declare_ec");//新增报关商品

                BigDecimal qty = BigDecimal.ZERO;
                BigDecimal grossweightsum = BigDecimal.ZERO;
                BigDecimal netweightsuma = BigDecimal.ZERO;
                BigDecimal volm3sum = BigDecimal.ZERO;
                BigDecimal gdecpiecesum = BigDecimal.ZERO;
                for (DynamicObject dynamicObject : value) {
                    qty = qty.add(dynamicObject.getBigDecimal("yem_qty"));
                    grossweightsum = grossweightsum.add(dynamicObject.getBigDecimal("yem_grossweightsum"));
                    netweightsuma = netweightsuma.add(dynamicObject.getBigDecimal("yem_netweightsuma"));
                    volm3sum = volm3sum.add(dynamicObject.getBigDecimal("yem_volm3sum"));
                    gdecpiecesum = gdecpiecesum.add(dynamicObject.getBigDecimal("yem_gdecpiecesum"));
                    SetEntryValue(dynamicObject.getLong("seq"), dynamicObject.getLong("id"), dynamicObject.getDynamicObject("yem_materiel"),
                            row + 1, dynamicObject.getString("yem_customclass.name"));

                }

                if (value.isEmpty()) continue;

                DynamicObject entryRow = value.get(0);

                model.setValue("yem_cusboxgoods", entryRow.get("yem_materiel"), row);//商品编码
                model.setValue("yem_decmatericalname", entryRow.get("yem_customclass.name"), row);//报关名称
                model.setValue("yem_decmatericalenname", entryRow.get("yem_declareproducten"), row);//英文名称
                model.setValue("yem_cushscode", entryRow.get("yem_hscode"), row);//海关编码
                model.setValue("yem_cusunit", entryRow.get("yem_unit"), row);//计量单位
//                        BigDecimal qty = (BigDecimal) entryRow.get("yem_qty");//数量
                model.setValue("yem_cusqty", qty, row);//数量
                BigDecimal price = entryRow.getBigDecimal("yem_sellprice");
                model.setValue("yem_cusconsalesprice", price, row);//单价
                model.setValue("yem_cusamount", qty.multiply(price), row);//金额
                model.setValue("yem_cusdecpiecesum", gdecpiecesum, row);//件数
                model.setValue("yem_cusweightunit", entryRow.get("yem_weightunit"), row);//重量单位
//                        BigDecimal grossweightsum = (BigDecimal) entryRow.get("yem_grossweightsum");//总毛重
                model.setValue("yem_cusgrossweight", BigDecimalUtils.div(grossweightsum, gdecpiecesum, 4), row);//毛重
                model.setValue("yem_cusvolm3", BigDecimalUtils.div(volm3sum, gdecpiecesum, 4), row);//体积M3
                model.setValue("yem_cusgrossweightsum", grossweightsum, row);//总毛重
                model.setValue("yem_cusvolm3sum", volm3sum, row);//总体积M3
                model.setValue("yem_cuscontent", entryRow.get("yem_mxcontent"), row);//备注
                model.setValue("yem_documenttypes", entryRow.get("yem_documenttype"), row);//单据类型
                model.setValue("yem_taxrefundrates", entryRow.get("yem_degrate"), row);//退税率%
//                        BigDecimal netweightsuma = (BigDecimal) entryRow.get("yem_netweightsuma");//总净重
                model.setValue("yem_cusnetweight", BigDecimalUtils.div(netweightsuma, gdecpiecesum, 4), row);//净重
                model.setValue("yem_cusnetweightsum", netweightsuma, row);//总净重
                model.setValue("yem_declarationelee", entryRow.get("yem_declarationeleb"), row);//申报要素（文本）
                model.setValue("yem_declareunit_e", entryRow.get("yem_declareunit"), row);//报关单位
                // 产品机型
                DynamicObject productmodel = (DynamicObject) entryRow.get("yem_productmodel");
                if (productmodel != null) {
                    model.setValue("yem_proctype", productmodel.get("yem_products.id"), row);
                }
            }

            for (Map.Entry<String, List<DynamicObject>> entry : compMapZ.entrySet()) {
                List<DynamicObject> value = entry.getValue();
                int row = model.createNewEntryRow("yem_es_declare_ec");//新增报关商品

                BigDecimal qty = BigDecimal.ZERO;
                BigDecimal grossweightsum = BigDecimal.ZERO;
                BigDecimal netweightsuma = BigDecimal.ZERO;
                BigDecimal volm3sum = BigDecimal.ZERO;
                BigDecimal gdecpiecesum = BigDecimal.ZERO;
                for (DynamicObject dynamicObject : value) {
                    qty = qty.add(dynamicObject.getBigDecimal("yem_qty"));
                    grossweightsum = grossweightsum.add(dynamicObject.getBigDecimal("yem_grossweightsum"));
                    netweightsuma = netweightsuma.add(dynamicObject.getBigDecimal("yem_netweightsuma"));
                    volm3sum = volm3sum.add(dynamicObject.getBigDecimal("yem_volm3sum"));
                    gdecpiecesum = gdecpiecesum.add(dynamicObject.getBigDecimal("yem_gdecpiecesum"));
                    SetEntryValue(dynamicObject.getLong("seq"), dynamicObject.getLong("id"), dynamicObject.getDynamicObject("yem_materiel"),
                            row + 1, dynamicObject.getString("yem_customclass.name"));

                }

                if (value.isEmpty()) continue;

                DynamicObject entryRow = value.get(0);

                model.setValue("yem_cusboxgoods", entryRow.get("yem_materiel"), row);//商品编码
                model.setValue("yem_decmatericalname", entryRow.get("yem_customclass.name"), row);//报关名称
                model.setValue("yem_decmatericalenname", entryRow.get("yem_declareproducten"), row);//英文名称
                model.setValue("yem_cushscode", entryRow.get("yem_hscode"), row);//海关编码
                model.setValue("yem_cusunit", entryRow.get("yem_unit"), row);//计量单位
//                        BigDecimal qty = (BigDecimal) entryRow.get("yem_qty");//数量
                model.setValue("yem_cusqty", qty, row);//数量
                BigDecimal price = entryRow.getBigDecimal("yem_sellprice");
                model.setValue("yem_cusconsalesprice", price, row);//单价
                model.setValue("yem_cusamount", qty.multiply(price), row);//金额
                model.setValue("yem_cusdecpiecesum", gdecpiecesum, row);//件数
                model.setValue("yem_cusweightunit", entryRow.get("yem_weightunit"), row);//重量单位
//                        BigDecimal grossweightsum = (BigDecimal) entryRow.get("yem_grossweightsum");//总毛重
                model.setValue("yem_cusgrossweight", BigDecimalUtils.div(grossweightsum, gdecpiecesum, 4), row);//毛重
                model.setValue("yem_cusvolm3", BigDecimalUtils.div(volm3sum, gdecpiecesum, 4), row);//体积M3
                model.setValue("yem_cusgrossweightsum", grossweightsum, row);//总毛重
                model.setValue("yem_cusvolm3sum", volm3sum, row);//总体积M3
                model.setValue("yem_cuscontent", entryRow.get("yem_mxcontent"), row);//备注
                model.setValue("yem_documenttypes", entryRow.get("yem_documenttype"), row);//单据类型
                model.setValue("yem_taxrefundrates", entryRow.get("yem_degrate"), row);//退税率%
//                        BigDecimal netweightsuma = (BigDecimal) entryRow.get("yem_netweightsuma");//总净重
                model.setValue("yem_cusnetweight", BigDecimalUtils.div(netweightsuma, gdecpiecesum, 4), row);//净重
                model.setValue("yem_cusnetweightsum", netweightsuma, row);//总净重
                model.setValue("yem_declarationelee", entryRow.get("yem_declarationeleb"), row);//申报要素（文本）
                model.setValue("yem_declareunit_e", entryRow.get("yem_declareunit"), row);//报关单位
                // 产品机型
                DynamicObject productmodel = (DynamicObject) entryRow.get("yem_productmodel");
                if (productmodel != null) {
                    model.setValue("yem_proctype", productmodel.get("yem_products.id"), row);
                }
            }
        }
//        }

        if (StringUtils.isNotEmpty(operateKey) && isSuccess) {
            if ("save".equals(operateKey)) {
                this.getView().updateView("yem_reightamt");
                view.invokeOperation("refresh");
            }
        }

        if ("mergedata".equals(operateKey)) {
            mergeDeclareData();
        }

        DynamicObject dataEntity = model.getDataEntity(true);

        if ("logrepbackfill".equals(operateKey)) {
            FormShowParameter parameter = new FormShowParameter();
            parameter.setStatus(OperationStatus.ADDNEW);
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            parameter.setFormId("yem_es_declaredocx_bkfill");
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_es_declaredocx_bkfill"));

            HashMap<String, Object> map = new HashMap<>();

            map.put("yem_bringbillno", dataEntity.getString("yem_bringbillno"));
            map.put("yem_realbringbillno", dataEntity.getString("yem_realbringbillno"));
            map.put("yem_realdeclarationnum", dataEntity.getString("yem_realdeclarationnum"));
            map.put("yem_realdeclarationdate", dataEntity.getDate("yem_realdeclarationdate"));
            map.put("yem_cyreightamt", dataEntity.getLong("yem_cyreightamt.id"));
            map.put("yem_reightamt", dataEntity.getBigDecimal("yem_reightamt"));

            parameter.setCustomParams(map);

            view.showForm(parameter);
        }

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

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        Object returnData = e.getReturnData();
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        if ("yem_es_declaredocx_bkfill".equals(actionId) && returnData != null) {
            Map<String, Object> params = (Map<String, Object>) returnData;
            long cyreightamt = (Long) params.get("yem_cyreightamt");
            model.setValue("yem_cyreightamt", cyreightamt);
            DynamicObject dataEntity = model.getDataEntity(true);
            dataEntity.set("yem_bringbillno", params.get("yem_bringbillno"));
            dataEntity.set("yem_realbringbillno", params.get("yem_realbringbillno"));
            dataEntity.set("yem_realdeclarationnum", params.get("yem_realdeclarationnum"));
            dataEntity.set("yem_realdeclarationdate", params.get("yem_realdeclarationdate"));
            dataEntity.set("yem_logisticsbackfiller", params.get("yem_logisticsbackfiller"));
            dataEntity.set("yem_logbackfilltime", params.get("yem_logbackfilltime"));
            BigDecimal reightamt = (BigDecimal) params.get("yem_reightamt");
            dataEntity.set("yem_reightamt", reightamt);
            //yem_reightamtbase = yem_reightamtrate * yem_reightamt
            //海运费（本位币） = 海运费汇率 * 海运费（原币）
            BigDecimal reightamtrate = dataEntity.getBigDecimal("yem_reightamtrate");
            BigDecimal base = reightamtrate.multiply(reightamt);
            dataEntity.set("yem_reightamtbase", base);
            //yem_reightamtend = yem_reightamtbase / yem_exrate
            //海运费（结算币别） = 海运费（本位币） / 汇率
            BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
            dataEntity.set("yem_reightamtend", BigDecimalUtils.div(base, exrate, 2));
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            this.getView().invokeOperation("refresh");
        }
    }

    /**
     * 根据合并规则将商品明细的数据生成到报关商品页签
     */
    private void mergeDeclareData() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");

        LinkedHashMap<String, List<Integer>> map = new LinkedHashMap<>();

        Map<Integer, Long> billtypeStore = new HashMap<>();

        model.deleteEntryData("yem_es_declare_ec");
        for (DynamicObject dynamicObject : collection) {

            int index = collection.indexOf(dynamicObject);

            // 合同号
            String contractNum = dynamicObject.getString("yem_contractnumbers_m");

            String billtype = dynamicObject.getString("yem_documenttype.number");

            billtypeStore.put(index, dynamicObject.getLong("yem_documenttype.id"));
            // 报关分类
            String customclass = dynamicObject.getString("yem_customclass.number");
            // 海关编码
            String hscode = dynamicObject.getString("yem_hscode.number");

            if (YEM.isNotEmpty(contractNum) && YEM.isNotEmpty(customclass) && YEM.isNotEmpty(hscode)) {
                String key = contractNum + "_" + customclass + "_" + hscode;
                if ("yem_es_salesorder_ZJ".equals(billtype)) {
                    List<Integer> indexArray;
                    if (map.containsKey(key)) {
                        indexArray = map.get(key);
                    } else {
                        indexArray = new ArrayList<>();
                    }
                    indexArray.add(index);
                    map.put(key, indexArray);
                }
            }
            if (YEM.isNotEmpty(customclass) && YEM.isNotEmpty(hscode)) {
                String key = customclass + "_" + hscode;
                if ("yem_es_salesorder_PJ".equals(billtype)) {
                    List<Integer> indexArray;
                    if (map.containsKey(key)) {
                        indexArray = map.get(key);
                    } else {
                        indexArray = new ArrayList<>();
                    }
                    indexArray.add(index);
                    map.put(key, indexArray);
                }
            }

        }

        for (Map.Entry<String, List<Integer>> entry : map.entrySet()) {
            List<Integer> v = entry.getValue();
            Integer lastLineIdx = v.get(v.size() - 1);
            Integer firstLineIdx = v.get(0);
            DynamicObject lastRowObject = collection.get(lastLineIdx);
            DynamicObject firstRowObject = collection.get(firstLineIdx);
            int rowIndex = model.createNewEntryRow("yem_es_declare_ec");

            // 数量
            BigDecimal cuqty = BigDecimal.ZERO;
            // 金额
            BigDecimal cusamount = BigDecimal.ZERO;
            // 件数
            BigDecimal cusdecpiecesum = BigDecimal.ZERO;
            // 总毛重
            BigDecimal cusgrossweightsum = BigDecimal.ZERO;
            // 总体积M3
            BigDecimal cusvolm3sum = BigDecimal.ZERO;
            // 总净重
            BigDecimal cusnetweightsum = BigDecimal.ZERO;
            // 合并计算
            for (Integer val : v) {
                DynamicObject object = collection.get(val);
                cuqty = cuqty.add(object.getBigDecimal("yem_qty"));
                cusamount = cusamount.add(object.getBigDecimal("yem_sellamt"));
                cusdecpiecesum = cusdecpiecesum.add(object.getBigDecimal("yem_gdecpiecesum"));
                cusgrossweightsum = cusgrossweightsum.add(object.getBigDecimal("yem_grossweightsum"));
                cusvolm3sum = cusvolm3sum.add(object.getBigDecimal("yem_volm3sum"));
                cusnetweightsum = cusnetweightsum.add(object.getBigDecimal("yem_netweightsuma"));
                SetEntryValue(object.getLong("seq"), object.getLong("id"), object.getDynamicObject("yem_materiel"),
                        val + 1, object.getString("yem_customclass.name"));
            }

            // 单据类型(取最后一行的单据类型)
            model.setValue("yem_documenttypes", billtypeStore.get(lastLineIdx), rowIndex);
            // 商品编码
            model.setValue("yem_cusboxgoods", lastRowObject.getLong("yem_materiel.id"), rowIndex);
            // 报关名称
            model.setValue("yem_decmatericalname", lastRowObject.getString("yem_customclass.name"), rowIndex);
            // 英文名称
            model.setValue("yem_decmatericalenname", lastRowObject.getString("yem_declareproducten"), rowIndex);
            // 规格型号
            // 商品描述
            // 海关编码
            model.setValue("yem_cushscode", lastRowObject.getLong("yem_hscode.id"), rowIndex);
            // 申报要素（文本）
            model.setValue("yem_declarationelee", firstRowObject.getString("yem_declarationeleb"), rowIndex);
            // 计量单位
            model.setValue("yem_cusunit", lastRowObject.getLong("yem_unit.id"), rowIndex);
            // 数量 h
            model.setValue("yem_cusqty", cuqty, rowIndex);
            // 单价 calc
            model.setValue("yem_cusconsalesprice", cusamount.divide(cuqty, 4, RoundingMode.HALF_UP), rowIndex);
            // 金额 h
            model.setValue("yem_cusamount", cusamount, rowIndex);
            // 件数 h
            model.setValue("yem_cusdecpiecesum", cusdecpiecesum, rowIndex);
            // 重量单位
            model.setValue("yem_cusweightunit", lastRowObject.getLong("yem_weightunit.id"), rowIndex);
            if (cusdecpiecesum.compareTo(BigDecimal.ZERO) == 0) {
                // 净重
                model.setValue("yem_cusnetweight", BigDecimal.ZERO, rowIndex);
                // 毛重
                model.setValue("yem_cusgrossweight", BigDecimal.ZERO, rowIndex);
                // 毛重
                model.setValue("yem_cusgrossweight", BigDecimal.ZERO, rowIndex);
            } else {
                // 净重
                model.setValue("yem_cusnetweight", cusnetweightsum.divide(cusdecpiecesum, 4, RoundingMode.HALF_UP), rowIndex);
                // 毛重
                model.setValue("yem_cusgrossweight", cusgrossweightsum.divide(cusdecpiecesum, 4, RoundingMode.HALF_UP), rowIndex);
                // 体积M3
                model.setValue("yem_cusvolm3", cusvolm3sum.divide(cusdecpiecesum, 4, RoundingMode.HALF_UP), rowIndex);
            }
            // 总净重
            model.setValue("yem_cusnetweightsum", cusnetweightsum, rowIndex);
            // 总毛重 h
            model.setValue("yem_cusgrossweightsum", cusgrossweightsum, rowIndex);
            // 总体积M3 h
            model.setValue("yem_cusvolm3sum", cusvolm3sum, rowIndex);
            // 退税率%
            model.setValue("yem_taxrefundrates", lastRowObject.getBigDecimal("yem_degrate"), rowIndex);
            // 备注
            model.setValue("yem_cuscontent", lastRowObject.getString("yem_mxcontent"), rowIndex);
            // 已开票数量
            // 源单类型
            model.setValue("yem_sourcebilltype_ec", lastRowObject.getString("yem_sourcebilltype_e"), rowIndex);
            // 源单id
            model.setValue("yem_sourcebillid_ec", lastRowObject.getLong("yem_sourcebillid_d"), rowIndex);
            // 源单分录id
            model.setValue("yem_sourcebillentryid", lastRowObject.getLong("yem_sourceentryid"), rowIndex);
            // 报关单位
            model.setValue("yem_declareunit_e", firstRowObject.get("yem_declareunit"), rowIndex);
            // 产品机型
            DynamicObject productmodel = (DynamicObject) firstRowObject.get("yem_productmodel");
            if (productmodel != null) {
                model.setValue("yem_proctype", productmodel.get("yem_products.id"), rowIndex);
            }
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit declarationEle = this.getControl("yem_declarationele");
        declarationEle.addBeforeF7SelectListener(this);
        BasedataEdit hsCode = this.getControl("yem_hscode");
        hsCode.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        int row = e.getRow();
        //海关编码和申报要素修改时，过滤逻辑同储运托单。
        switch (name) {
            case "yem_declarationele":
                selectF7DeclarationEle(e);
                break;
            case "yem_hscode":
                selectF7HsCode(e);
                break;
        }
    }

    public void selectF7DeclarationEle(BeforeF7SelectEvent e) {
        int row = e.getRow();
        IDataModel model = this.getModel();
        DynamicObject yem_hscode = (DynamicObject) model.getValue("yem_hscode", row);
        if (YEM.isNotEmpty(yem_hscode)) {
            e.addCustomQFilter(new QFilter("yem_hscodebase", QCP.equals, yem_hscode.getPkValue()));
        }
        DynamicObject yem_customclass = (DynamicObject) model.getValue("yem_customclass", row);
        if (YEM.isNotEmpty(yem_customclass)) {
            e.addCustomQFilter(new QFilter("yem_customclass", QCP.equals, yem_customclass.getPkValue()));
        }
    }


    public void selectF7HsCode(BeforeF7SelectEvent e) {
        int row = e.getRow();
        List<Long> ids = new ArrayList();
        IDataModel model = this.getModel();
        DynamicObject yem_customclass = (DynamicObject) model.getValue("yem_customclass", row);
        if (YEM.isNotEmpty(yem_customclass)) {
            DynamicObject[] declarationEles = BusinessDataServiceHelper.load("yem_bd_declarationele", "id,yem_hscodebase",
                    new QFilter[]{new QFilter("yem_customclass", QCP.equals, yem_customclass.getPkValue())});
            for (DynamicObject declarationEle : declarationEles) {
                DynamicObject hsCodebase = declarationEle.getDynamicObject("yem_hscodebase");
                if (YEM.isNotEmpty(hsCodebase)) {
                    ids.add(hsCodebase.getLong("id"));
                }
            }
        }
        e.addCustomQFilter(new QFilter("id", QCP.in, ids));
    }

    public void Getbilltype() {
        DynamicObjectCollection entryRows = this.getModel().getEntryEntity("yem_es_materialinfo");//商品明细
        for (DynamicObject entryRow : entryRows) {
            String yemContractnumbersM = entryRow.getString("yem_contractnumbers_m");//获取分录外销合同号
            QFilter qFilter = new QFilter("billno", QCP.equals, yemContractnumbersM);//
            DynamicObject[] yem_em_substitution = BusinessDataServiceHelper.load("yem_es_salesorder", "yem_billtype"
                    , new QFilter[]{qFilter}, null);
            if (yem_em_substitution.length > 0) {
                this.getModel().setValue("yem_documenttype", yem_em_substitution[0].get("yem_billtype"), entryRow.getInt("seq") - 1);//单据类型
            }
        }

    }


    public void SetEntryValue(long detailSeq, long detailId, DynamicObject detailMat, long mergedSeq, String mergerAnt) {
        int row = this.getModel().createNewEntryRow("yem_es_declare_ecd");//报关商品对照表
        this.getModel().setValue("yem_fgseq", detailSeq, row);//商品明细序数
        this.getModel().setValue("yem_decsourceentryidtext", detailId, row);//商品明细行ID
        this.getModel().setValue("yem_fdecnewgoodsname", detailMat, row);//报关商品

        this.getModel().setValue("yem_decgoodsseq", mergedSeq, row);//报关商品序号
        this.getModel().setValue("yem_decname", mergerAnt, row);//报关商品名称
    }


}
