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

import com.yem.or.utils.OrderApiUtils;
import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.es.contactbook.op.ContactBookSaveOp;
import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import com.yem.wm.utils.CalendarUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.OrmLocaleValue;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.*;
import kd.bos.entity.property.EntryProp;
import kd.bos.exception.KDBizException;
import kd.bos.form.*;
import kd.bos.form.control.AttachmentPanel;
import kd.bos.form.control.events.UploadListener;
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.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.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.bos.util.StringUtils;

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

import static com.yem.wm.es.contactbook.op.ContactBookSaveOp.uploadAttachmentPanel;
import static com.yem.wm.es.salesorder.from.SalesOrderEdit.carryReportCategoryAndHsCode;
import static com.yem.wm.es.salesorder.utils.SalesOrderUtils.*;
import static com.yem.wm.im.csrCreditLine.form.CsrCreditLineEdit.updateRecentLapseUseDataEntity;

/**
 * @author xwudd
 * @date 11:09
 * @Description
 **/
public class StorageTransEdit extends AbstractBillPlugIn implements BeforeF7SelectListener, UploadListener {

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        FunctionalCommon.setBillType(this);//赋值对应视图单据类型
        showconcealGiftGiving();
        setUnQty();
        setGiftGiving();
        visGiftGive();
//        genShipPortEnName(this.getModel(), this.getView());

        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        for (DynamicObject dynamicObject : collection) {
            // 投保回款金额美元（实际收汇金额）
            BigDecimal actualsinkamt_cd = dynamicObject.getBigDecimal("yem_actualsinkamt_cd");
            // 应收款金额1
            BigDecimal paymentamt1Cd = dynamicObject.getBigDecimal("yem_paymentamt1_cd");
            BigDecimal amountowed = paymentamt1Cd.subtract(actualsinkamt_cd);
            dynamicObject.set("yem_amountowed", amountowed);
        }
        this.getView().updateView("yem_creditdetail");
        Businesssort();
        calcPremium();
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        EntryProp entryProp = e.getEntryProp();
        int[] rowIndexs = e.getRowIndexs();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        if ("yem_es_materialinfo".equals(entryProp.toString())) {
            for (int row : rowIndexs) {
                boolean flag = true;
                DynamicObject[] encasement = BusinessDataServiceHelper.load("yem_im_encasement", "" +
                        "yem_im_materialinfo_mi.yem_sourceentryid,yem_im_materialinfo_mi.yem_packingqty", new QFilter[]{
                        new QFilter("yem_sourcebillid", QCP.equals, dataEntity.getPkValue())
                });
                if (materialinfo != null && materialinfo.size() > row) {
                    DynamicObject dynamicObject = materialinfo.get(row);
                    for (DynamicObject enSon : encasement) {
                        DynamicObjectCollection materialinfo_mi = enSon.getDynamicObjectCollection("yem_im_materialinfo_mi");
                        for (DynamicObject miSon : materialinfo_mi) {
                            long aLong = miSon.getLong("yem_sourceentryid");
                            if (((long) dynamicObject.getPkValue()) == aLong) {
                                BigDecimal yemPackingqty = miSon.getBigDecimal("yem_packingqty");
                                if (BigDecimal.ZERO.compareTo(yemPackingqty) < 0) {
                                    flag = false;
                                    break;
                                }
                            }
                        }
                    }
                }
                if (!flag) {
                    this.getView().showErrorNotification("当前明细信息第" + (row + 1) + "行,对应的装箱单存在已包装数量，无法删除");
                    e.setCancel(true);
                }

            }
        }
    }

    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_unassdeclaqty", qty, i);
                model.setValue("yem_unpackingqty", qty, i);
                model.setValue("yem_assdeclaqty", BigDecimal.ZERO, i);
                model.setValue("yem_packingqty", BigDecimal.ZERO, i);
            }
        }
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        showconcealGiftGiving();
    }

    @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 = this.getModel().getDataEntity();
        DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        switch (name) {
            case "yem_qty":
                setGiftGiving();
                break;
            case "yem_isgiftgive":
                visGiftGive();
                break;
            case "yem_iswithaccessories":
                // 是否随车配件修改时，清空随车配件单号
                this.getModel().setValue("yem_accompanynum", null);
                break;
            case "yem_grossweightsum":
                BigDecimal weightsum = BigDecimal.ZERO;
                for (DynamicObject info : yem_es_materialinfo) {
                    weightsum = weightsum.add(info.getBigDecimal("yem_grossweightsum"));
                }
                this.getModel().setValue("yem_boxgwsum", weightsum);
                break;
            case "yem_netweightsum":
                BigDecimal nweightsum = BigDecimal.ZERO;
                for (DynamicObject info : yem_es_materialinfo) {
                    nweightsum = nweightsum.add(info.getBigDecimal("yem_netweightsum"));
                }
                this.getModel().setValue("yem_boxnwsum", nweightsum);
                break;
            case "yem_volm3sum":
                BigDecimal volm3sum = BigDecimal.ZERO;
                for (DynamicObject info : yem_es_materialinfo) {
                    volm3sum = volm3sum.add(info.getBigDecimal("yem_volm3sum"));
                }
                this.getModel().setValue("yem_boxvolsum", volm3sum);
                break;
            case "yem_shipports":
                genShipPortEnName(this.getModel());
                break;
            case "yem_destports":
                genDescPortEnName(this.getModel());
                break;
            case "yem_paydate1":
                calcCountPayback(rowIndex);
                break;
            case "yem_actualsinkamt_cd":
            case "yem_paymentamt1_cd":
                calcAmountOwed(rowIndex);
                break;
            case "yem_ladingdate":
            case "yem_creditdate1_cd":
                calcReceivableDate(rowIndex);
                break;
            case "yem_creditquotation":
            case "yem_clientcountry":
            case "yem_term_cd":
                carryCreditInsuranceRate(rowIndex);
                break;
            case "yem_businesssort":
                Businesssort();
                break;
            case "yem_hscode":
                carryReportCategoryAndHsCode(this.getModel(), this.getView(), rowIndex, "yem_hscode");
//                carryDeclaration(this.getModel(), this.getView(), rowIndex);
                break;

            case "yem_productmodel":
            case "yem_materiel":
            case "yem_customclass":
                carryReportCategoryAndHsCode(this.getModel(), this.getView(), rowIndex, "yem_customclass");
                break;
//            case "yem_hscode":
//                customclass(changeData);
//                break;
        }
    }

    private void customclass(ChangeData changeData) {
        Object newValue = changeData.getNewValue();
        int rowIndex = changeData.getRowIndex();
        if (newValue instanceof DynamicObject) {
            DynamicObject yem_customclass = (DynamicObject) newValue;
            if (yem_customclass != null) {
                String yemUnit = yem_customclass.getString("yem_unit");
                DynamicObject bdMeasureunits = BusinessDataServiceHelper.loadSingle("bd_measureunits", "id,number,name"
                        , new QFilter[]{new QFilter("name", QCP.equals, yemUnit)});
                if (bdMeasureunits != null) {
//                    long aLong = bdMeasureunits.getLong("id");
                    this.getModel().setValue("yem_declareunit",bdMeasureunits,rowIndex);
                }else {
                    this.getModel().setValue("yem_declareunit",null,rowIndex);
                }
            }else {
                this.getModel().setValue("yem_declareunit",null,rowIndex);
            }
        }else {
            this.getModel().setValue("yem_declareunit",null,rowIndex);
        }
    }

    private void Businesssort() {
        DynamicObjectCollection yemEsMaterialinfo = (DynamicObjectCollection) this.getModel().getValue("yem_es_materialinfo");
        if (yemEsMaterialinfo.size() > 0) {
            String yem_combo = "P";
            for (DynamicObject dynamicObject : yemEsMaterialinfo) {
                String yemBusinesssort = dynamicObject.getString("yem_businesssort");
                if ("Z".equals(yemBusinesssort)) {
                    yem_combo = "Z";
                }
            }
            this.getModel().setValue("yem_combo", yem_combo);
        }
    }

    private void carryCreditInsuranceRate(int rowIndex) {
        IDataModel model = this.getModel();
        // 信报结算方式
        DynamicObject rapstyle = (DynamicObject) model.getValue("yem_creditquotation", rowIndex);
        // 贸易国别
        DynamicObject clientcountry = (DynamicObject) model.getValue("yem_clientcountry");
        // 信用期限
        DynamicObject term = (DynamicObject) model.getValue("yem_term_cd", rowIndex);

        if (rapstyle == null || clientcountry == null || term == null) return;

        Long pkValue = (Long) clientcountry.getPkValue();
        QFilter qFilter = new QFilter("yem_countryinfo.yem_nation.id", QCP.equals, pkValue);
        DynamicObject[] load = BusinessDataServiceHelper.load("yem_bd_signals", "id, billno, yem_countryinfo.yem_nation", qFilter.toArray());
        if (YEM.isEmpty(load)) return;

        for (DynamicObject dynamicObject : load) {
            dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getLong("id"), "yem_bd_signals");
            DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_bd_signals_em");
            for (DynamicObject object : collection) {
                DynamicObject payment = object.getDynamicObject("yem_payment");
                DynamicObject yem_term = object.getDynamicObject("yem_term");
                if (YEM.isEmpty(payment) || YEM.isEmpty(yem_term)) continue;
                if (rapstyle.getLong("id") == payment.getLong("id") && term.getLong("id") == yem_term.getLong("id")) {
                    model.setValue("yem_sinosurerate_cd", object.getBigDecimal("yem_rate"), rowIndex);
                    return;
                }
            }
        }
    }

    private void calcPremium() {
        IDataModel model = this.getModel();
        Object priceitem = model.getValue("yem_priceitem");
        if (YEM.isNotEmpty(priceitem)) {
            DynamicObject priceitemObj = (DynamicObject) priceitem;
            String name = priceitemObj.getString("name");
            if (!"CIF".equals(name)) {
                model.setValue("yem_premiumamt", BigDecimal.ZERO);
                model.setValue("yem_premiumamtbase", BigDecimal.ZERO);
                model.setValue("yem_premiumamtend", BigDecimal.ZERO);
            }
        }
    }

    /**
     * @param rowIndex
     * @description 计算应收款日期
     */
    private void calcReceivableDate(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        DynamicObject dynamicObject = collection.get(rowIndex);
        // 信用起始日（提单日期）
        Date ladingdate = dynamicObject.getDate("yem_ladingdate");
        // 信保天数
        int creditdate1_cd = dynamicObject.getInt("yem_creditdate1_cd");
        if (YEM.isNotEmpty(ladingdate) && creditdate1_cd > 0) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(ladingdate);
            calendar.add(Calendar.DATE, creditdate1_cd);
            Date receivableDate = calendar.getTime();
            dynamicObject.set("yem_paydate1", receivableDate);
        }
        this.getView().updateView("yem_creditdetail");
    }

    /**
     * @description 计算欠款金额
     */
    private void calcAmountOwed(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        DynamicObject dynamicObject = collection.get(rowIndex);
        // 投保回款金额美元（实际收汇金额）
        BigDecimal actualsinkamt_cd = dynamicObject.getBigDecimal("yem_actualsinkamt_cd");
        // 应收款金额1
        BigDecimal paymentamt1Cd = dynamicObject.getBigDecimal("yem_paymentamt1_cd");
        BigDecimal amountowed = paymentamt1Cd.subtract(actualsinkamt_cd);
        dynamicObject.set("yem_amountowed", amountowed);
        this.getView().updateView("yem_creditdetail");
    }

    /**
     * @description 计算应回款日期
     */
    private void calcCountPayback(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        DynamicObject dynamicObject = collection.get(rowIndex);
        Date receivableDate = dynamicObject.getDate("yem_paydate1");
        if (receivableDate != null) {
            dynamicObject.set("yem_countpayback", CalendarUtils.calcPayBackCount(receivableDate));
        }
        this.getView().updateView("yem_creditdetail");
    }

    @Override
    public void afterDeleteEntry(AfterDeleteEntryEventArgs e) {
//        this.getView().getModel().deleteEntryData("yem_es_salesorder_l");
//        setGiftGiving();
    }


    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        this.getView().getModel().deleteEntryData("yem_es_salesorder_l");
        setGiftGiving();
    }

    @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("backcustomscode")) {
                //回填海关编码
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId("yem_es_backcustomscode");
                showParameter.setCloseCallBack(null);
                showParameter.getOpenStyle().setShowType(ShowType.Modal);
                this.getView().showForm(showParameter);
            }
            if (operateKey.equals("draw")) {
                int yem_es_materialinfo = model.getEntryRowCount("yem_es_materialinfo");
            }
        }

        DynamicObject dataEntity = model.getDataEntity(true);

        if ("save".equals(operateKey)) {
//            syncAccessoryPanel(dataEntity);
        }

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

        if ("test_islastship".equals(operateKey)) {
            view.showSuccessNotification(String.valueOf(isLastShip(dataEntity)));
        }
    }


    /**
     * @description 根据明细信息的 是否礼品赠送 存在是的情况下隐藏 礼品信息控件 与礼品赠送分录
     * @author power
     * return
     * @time 2023/9/28
     */
    private void showconcealGiftGiving() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection goodsEntities = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        String isgiftgive = "B";
        for (DynamicObject entryObj : goodsEntities) {
            if ("A".equals(entryObj.getString("yem_isgiftgive"))) {
                isgiftgive = entryObj.getString("yem_isgiftgive");
                break;
            }
        }
        if ("A".equals(isgiftgive)) {
            this.getView().setVisible(true, "yem_flexpanelap511");
            this.getView().setVisible(true, "yem_tabpageap6");
        } else {
            this.getView().setVisible(false, "yem_flexpanelap511");
            this.getView().setVisible(false, "yem_tabpageap6");
        }
    }


    /**
     * @description 根据明细信息的 是否礼品赠送 产品分类 基础机型的产品机型 重量 带出礼品赠送分录
     * @author power
     * return
     * @time 2023/9/28
     */
    private void setGiftGiving() {
        IDataModel model = this.getModel();
        DynamicObjectCollection materialinfos = model.getEntryEntity("yem_es_materialinfo");
        Map<String, BigDecimal> maps = new HashMap<>();
        Map<String, BigDecimal> mapx = new HashMap<>();
        BigDecimal qty = BigDecimal.ZERO;


        model.deleteEntryData("yem_es_salesorder_l");

        for (DynamicObject materialinfo : materialinfos) {

            qty = BigDecimal.ZERO;
            String isgiftgive = materialinfo.getString("yem_isgiftgive");
            if (materialinfo.getDynamicObject("yem_productmodel") != null) {
                Long productmodels = materialinfo.getLong("yem_productmodel.yem_products.id");
                if (materialinfo.getDynamicObject("yem_products") != null) {
                    Long products = materialinfo.getLong("yem_products.id");

                    if ("A".equals(isgiftgive)) {
                        String conBillno = materialinfo.getString("yem_contractnumbers_m");
                        String shiBillno = materialinfo.getString("yem_shipmentnumbers_m");
                        String productss = String.valueOf(materialinfo.getLong("yem_products.id"));

                        DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "yem_isnewagent",
                                new QFilter[]{new QFilter("billno", QCP.equals, conBillno),});
                        if (data != null) {
                            if (StringUtils.isNotEmpty(data.getString("yem_isnewagent"))) {
                                String isnewagent = data.getString("yem_isnewagent");
                                DynamicObject data2 = BusinessDataServiceHelper.loadSingle("yem_bd_giftrules",
                                        "yem_bd_giftrules_a",
                                        new QFilter[]{new QFilter("yem_bd_giftrules_a.yem_producttype", QCP.equals, productmodels),
                                                new QFilter("yem_classify", QCP.equals, products),
                                                new QFilter("yem_ynnewdealer", QCP.equals, isnewagent)});
                                //是经销商
                                String productmodel = String.valueOf(productmodels);
                                if ("A".equals(isnewagent)) {
                                    String value = conBillno + "%" + shiBillno + "%" + productmodel + "%" + productss;
                                    qty = qty.add(materialinfo.getBigDecimal("yem_qty"));
                                    maps.put(value, qty);
                                }
                                //否新经销商
                                if ("B".equals(isnewagent)) {
                                    String value = conBillno + "%" + shiBillno + "%" + productmodel + "%" + productss;
                                    qty = qty.add(materialinfo.getBigDecimal("yem_qty"));
                                    mapx.put(value, qty);
                                }
                            }
                        }
                    }
                }
            }
        }
        BigDecimal exrate = (BigDecimal) model.getValue("yem_giftdecimal");
        for (String values : maps.keySet()) {
            String[] value = values.split("%");
            String conBillno = value[0];
            String shiBillno = value[1];
            Long productmodel = Long.valueOf(value[2]);
            Long productss = Long.valueOf(value[3]);

            DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "yem_bd_products",
                    new QFilter[]{new QFilter("billno", QCP.equals, conBillno),});
            Long yem_bd_products = data.getLong("yem_bd_products.id");

            DynamicObject[] giftRules = BusinessDataServiceHelper.load("yem_bd_giftrules", "id,yem_bd_giftrules_a.yem_producttype,yem_bd_giftrules_a.yem_qty,yem_bd_giftrules_a.yem_giveamo,yem_bd_giftrules_a.yem_remarka",
                    new QFilter[]{new QFilter("yem_bd_giftrules_a.yem_producttype", QCP.equals, productmodel),
                            new QFilter("yem_classify", QCP.equals, yem_bd_products),
                            new QFilter("yem_ynnewdealer", QCP.equals, "A")});
            for (DynamicObject giftRule : giftRules) {
                DynamicObjectCollection giftRules_as = giftRule.getDynamicObjectCollection("yem_bd_giftrules_a");
                for (DynamicObject giftRules_a : giftRules_as) {
                    DynamicObject productType = giftRules_a.getDynamicObject("yem_producttype");
                    if (YEM.isNotEmpty(productType)) {
                        Long id = productType.getLong("id");
                        if (productmodel.equals(id)) {
                            int entryRow = model.createNewEntryRow("yem_es_salesorder_l");
                            BigDecimal tsagerQty = maps.get(values);
                            BigDecimal giveAmoBase = giftRules_a.getBigDecimal("yem_giveamo");
                            BigDecimal giveAmo = BigDecimal.ZERO;
                            if (exrate.compareTo(BigDecimal.ZERO) != 0) {
                                giveAmo = giveAmoBase.divide(exrate, RoundingMode.HALF_DOWN);
                            }
                            model.setValue("yem_contractnumbers", conBillno, entryRow);//合同号
                            model.setValue("yem_shipmentnumbers", shiBillno, entryRow);//出运明细单号
                            model.setValue("yem_giftproactype", productType, entryRow);//产品机型

                            model.setValue("yem_bd_products", productss, entryRow);//产品分类
                            model.setValue("yem_tsagerqty", tsagerQty, entryRow);//台数
                            model.setValue("yem_singlegiftamt", giveAmo, entryRow);//单台礼品金额
                            model.setValue("yem_singlegiftamtloc", giveAmoBase, entryRow);//单台礼品金额本位币
                            model.setValue("yem_giftamt", tsagerQty.multiply(giveAmo), entryRow);//礼品金额
                            model.setValue("yem_giftamtbase", tsagerQty.multiply(giveAmoBase), entryRow);//礼品金额本位币
                        }
                    }
                }

            }

        }

        for (String values : mapx.keySet()) {
            String[] value = values.split("%");
            String conBillno = value[0];
            String shiBillno = value[1];
            Long productmodel = Long.valueOf(value[2]);
            Long productss = Long.valueOf(value[3]);

            DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "yem_bd_products",
                    new QFilter[]{new QFilter("billno", QCP.equals, conBillno),});
            if (data.getDynamicObject("yem_bd_products") != null) {
                Long yem_bd_products = data.getLong("yem_bd_products.id");

                DynamicObject[] giftRules = BusinessDataServiceHelper.load("yem_bd_giftrules", "id,yem_bd_giftrules_a.yem_producttype,yem_bd_giftrules_a.yem_qty,yem_bd_giftrules_a.yem_giveamo,yem_bd_giftrules_a.yem_remarka",
                        new QFilter[]{new QFilter("yem_bd_giftrules_a.yem_producttype", QCP.equals, productmodel),
                                new QFilter("yem_classify", QCP.equals, yem_bd_products),
                                new QFilter("yem_ynnewdealer", QCP.equals, "B")});

                for (DynamicObject giftRule : giftRules) {
                    DynamicObjectCollection giftRules_as = giftRule.getDynamicObjectCollection("yem_bd_giftrules_a");
                    for (DynamicObject giftRules_a : giftRules_as) {
                        DynamicObject productType = giftRules_a.getDynamicObject("yem_producttype");
                        if (YEM.isNotEmpty(productType)) {
                            Long id = productType.getLong("id");
                            if (productmodel.equals(id)) {
                                int entryRow = model.createNewEntryRow("yem_es_salesorder_l");
                                BigDecimal tsagerQty = mapx.get(values);
                                BigDecimal giveAmoBase = giftRules_a.getBigDecimal("yem_giveamo");
                                BigDecimal giveAmo = giveAmoBase.divide(exrate, RoundingMode.HALF_DOWN);
                                model.setValue("yem_contractnumbers", conBillno, entryRow);//合同号
                                model.setValue("yem_shipmentnumbers", shiBillno, entryRow);//出运明细单号
                                model.setValue("yem_giftproactype", productType, entryRow);//产品机型

                                model.setValue("yem_bd_products", productss, entryRow);//产品分类
                                model.setValue("yem_tsagerqty", tsagerQty, entryRow);//台数
                                model.setValue("yem_singlegiftamt", giveAmo, entryRow);//单台礼品金额
                                model.setValue("yem_singlegiftamtloc", giveAmoBase, entryRow);//单台礼品金额本位币
                                model.setValue("yem_giftamt", tsagerQty.multiply(giveAmo), entryRow);//礼品金额
                                model.setValue("yem_giftamtbase", tsagerQty.multiply(giveAmoBase), entryRow);//礼品金额本位币
                            }
                        }
                    }

                }
            }
        }
    }

    public void visGiftGive() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Boolean flag = false;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            String isGiftGive = (String) model.getValue("yem_isgiftgive", i);
            if ("A".equals(isGiftGive)) {
                flag = true;
                break;
            }
        }
        if (flag) {
            view.setVisible(true, "yem_tabpageap6");
        } else {
            view.setVisible(false, "yem_tabpageap6");
        }

    }


    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate formOperate = (FormOperate) e.getSource();
        IDataModel model = this.getModel();
        String operateKey = formOperate.getOperateKey();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView view = this.getView();
        if ("draw".equals(operateKey)) {
            String creditbackstatus = dataEntity.getString("yem_creditbackstatus");
            if ("A".equals(creditbackstatus)) {
                view.showErrorNotification("当前单据已进行信保确认，不允许选单！");
                e.setCancel(true);
            }
            //公司+客户过滤
            //公司
            DynamicObject org = (DynamicObject) model.getValue("org");
            //客户
            DynamicObject customer = (DynamicObject) model.getValue("yem_customer");
            formOperate.getOption().setVariableValue("org", String.valueOf(org.getLong("id")));
            formOperate.getOption().setVariableValue("customer", String.valueOf(customer.getLong("id")));
        }

        if ("creditconfirm".equals(operateKey)) {
//            DynamicObjectCollection dynamicObjectCollection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
//            if (dynamicObjectCollection.size()>0){
//                Map<Long,BigDecimal> map = new HashMap<>();
//                for (DynamicObject dynamicObject : dynamicObjectCollection) {
//                    DynamicObject yemSalecontractno = dynamicObject.getDynamicObject("yem_salecontractno");
//                    BigDecimal yemCreditamtCd = dynamicObject.getBigDecimal("yem_creditamt_cd");
//                    if (yemSalecontractno!=null){
//                        long aLong = yemSalecontractno.getLong("id");
//                        if (map.get(aLong)!=null){
//                            BigDecimal bigDecimal = map.get(aLong);
//                            map.put(aLong, yemCreditamtCd.add(bigDecimal));
//                        }else {
//                            map.put(aLong, yemCreditamtCd);
//                        }
//                    }
//                }
//                for (DynamicObject dynamicObject : dynamicObjectCollection) {
//                    DynamicObject yemSalecontractno = dynamicObject.getDynamicObject("yem_salecontractno");
//                    if (yemSalecontractno!=null){
//                        long aLong = yemSalecontractno.getLong("id");
//                        BigDecimal bigDecimal = map.get(aLong);
//                        String selectfield = DynamicObjectUtil.getSelectfields("yem_es_salesorder", false);
//                        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_es_salesorder", "yem_es_salescontrac_s", false);
//                        DynamicObject yemEsSalesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", selectfields
//                                , new QFilter[]{new QFilter("id", QCP.equals, aLong)});
//                        if (yemEsSalesorder != null) {
//                            DynamicObjectCollection yemEsMaterialinfo = yemEsSalesorder.getDynamicObjectCollection("yem_es_salescontrac_s");
//                            if (yemEsMaterialinfo.size()>0){
//                                BigDecimal salescontrac = BigDecimal.ZERO;
//                                for (DynamicObject object : yemEsMaterialinfo) {
//                                    boolean yemIspre = object.getBoolean("yem_ispre");
//                                    if (!yemIspre){
//                                        salescontrac =  salescontrac.add(object.getBigDecimal("yem_rapamt"));
//                                    }
//                                }
//                                if (salescontrac.compareTo(bigDecimal)<0){
//                                    view.showTipNotification(yemEsSalesorder.getString("billno")+"非预收收汇金额不足，请修改金额！！！");
//                                    return;
//                                }
//                            }
//                        }
//                    }
//                }
//            }

            BigDecimal attcount = dataEntity.getBigDecimal("yem_attcount");
            if (attcount.compareTo(BigDecimal.ZERO) == 0) {
                throw new KDBizException("未上传客户汇款水单附件，不能进行信保确认!");
            }

            DynamicObject customer = dataEntity.getDynamicObject("yem_customer");
            DynamicObject method = TotalUtil.getSettlementMethod(dataEntity);
            DynamicObject company = dataEntity.getDynamicObject("yem_company.yem_erporg");
            String swiftCode = TotalUtil.getSwiftCode(dataEntity);
            DynamicObject csrCreditLine = TotalUtil.getCsrCreditLine(customer, method, company, swiftCode);
            if (csrCreditLine != null && customer != null) {
                // 信保金额（美元）
                BigDecimal usacreditamt = dataEntity.getBigDecimal("yem_usacreditamt");
                // 剩余限额
                BigDecimal balance = csrCreditLine.getBigDecimal("yem_balance");
                if (usacreditamt.compareTo(balance) > 0) {
//                    ConfirmCallBackListener confirmCallBackListener = new ConfirmCallBackListener("creditInsuranceConfirms", this);
                    String message = String.format("当前客户：[ %s ] 本次订舱投保总额为 [ %s ] ，剩余限额为 [ %s ] ，已超额，不允许进行信保确认！",
                            customer.getString("name"),
                            usacreditamt.setScale(2, RoundingMode.HALF_UP),
                            balance.setScale(2, RoundingMode.HALF_UP));
//                    this.getView().showConfirm(message, MessageBoxOptions.YesNo, confirmCallBackListener);
                    this.getView().showErrorNotification(message);
                    e.setCancel(true);
                } else {
                    dataEntity.set("yem_creditbackstatus", "A");
                    view.showSuccessNotification("信保确认成功");
                    SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                }
            } else {
                view.showErrorNotification("当前客户不存在信保额度申请，不允许进行信保确认");
            }

        }

        if ("creditunconfirm".equals(operateKey)) {
            String billstatus = (String) model.getValue("billstatus");
            if ("A".equals(billstatus)) {
                dataEntity.set("yem_creditbackstatus", "B");
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                this.getView().invokeOperation("refresh");
                view.showSuccessNotification("信保反确认成功");
            } else {
                view.showTipNotification("单据已提交或已审核，不能进行信保反确认");
                e.setCancel(true);
            }
        }

        if ("bldatebackfilled".equals(operateKey)) {
            FormShowParameter parameter = new FormShowParameter();
            parameter.setStatus(OperationStatus.ADDNEW);
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            parameter.setFormId("yem_es_bldatebackfill");
            parameter.setCloseCallBack(new CloseCallBack(this, "bldatebackfilled"));
            this.getView().showForm(parameter);
        }

        if ("save".equals(operateKey)) {
            String dataEntityType = dataEntity.getDynamicObjectType().getName();
            if (!"yem_es_storagetrans".equals(dataEntityType)) return;
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                DynamicObject unit = dynamicObject.getDynamicObject("yem_unit");
                int precision = unit.getInt("precision");
                OrmLocaleValue name = (OrmLocaleValue) unit.get("name");
                String localName = name.getLocaleValue();
                BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                dynamicObject.set("yem_qtytext", qty.setScale(YEM.isNotEmpty(precision) ? precision : 2, RoundingMode.HALF_UP).toString());
                dynamicObject.set("yem_unittext", localName);

                DynamicObjectCollection completeInfos = dynamicObject.getDynamicObjectCollection("yem_es_salesorder_z");
                StringBuilder sb = new StringBuilder();
                for (DynamicObject completeInfo : completeInfos) {
                    String vehicleno = completeInfo.getString("yem_vehicleno");
                    sb.append(vehicleno).append("；");
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                }
                dynamicObject.set("yem_comptext", sb.toString());
            }
            calculateExportAmount(dataEntity);
            view.updateView("yem_es_materialinfo");
            view.updateView("yem_es_salesorder_z");
        }

        if ("upload_sigle_file".equals(operateKey)) {
            AttachmentPanel control = this.getControl("yem_attachmentpanelap1");
            List<Map<String, Object>> attachmentData = control.getAttachmentData();
            FormShowParameter parameter = new FormShowParameter();
            parameter.setStatus(OperationStatus.ADDNEW);
            parameter.getOpenStyle().setShowType(ShowType.Modal);
            parameter.setFormId("yem_es_storagetrans_sfile");
            parameter.setCustomParam("attach", attachmentData);
            parameter.setCloseCallBack(new CloseCallBack(this, "yem_es_storagetrans_sfile"));
            view.showForm(parameter);
        }
    }

    /**
     * 订舱通知单和订舱通知单信保回填之间同步附件
     * @param dataEntity
     * @see ContactBookSaveOp#uploadAttachmentPanel(DynamicObject, DynamicObject)
     */
    public static void syncAccessoryPanel(DynamicObject dataEntity) {
        String name = dataEntity.getDynamicObjectType().getName();
        long pkValue = (long) dataEntity.getPkValue();
        if ("yem_es_storagetrans".equals(name)) {
            AttachmentServiceHelper.remove("yem_es_storagetrans_xbs", pkValue);
            DynamicObject from = BusinessDataServiceHelper.loadSingle(pkValue, "yem_es_storagetrans");
            DynamicObject to = BusinessDataServiceHelper.loadSingle(pkValue, "yem_es_storagetrans_xbs");
            uploadAttachmentPanel(from, to);
        }

        if ("yem_es_storagetrans_xbs".equals(name)) {
            AttachmentServiceHelper.remove("yem_es_storagetrans", pkValue);
            DynamicObject from = BusinessDataServiceHelper.loadSingle(pkValue, "yem_es_storagetrans_xbs");
            DynamicObject to = BusinessDataServiceHelper.loadSingle(pkValue, "yem_es_storagetrans");
            uploadAttachmentPanel(from, to);
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        String actionId = e.getActionId();
        Object returnData = e.getReturnData();
        if ("bldatebackfilled".equals(actionId) && returnData != null) {
            Map<String, Object> map = (Map) returnData;
            Date yem_tddate = (Date) map.get("yem_tddate");
            if (isLastShip(dataEntity)) {
                // 同步下单平台状态
                syncOrderStatus();
            }
            // 跟新客户信保额度申请
            updateCsrCredit(yem_tddate);
            // 更新订舱通知单
            updateStoragetrans(yem_tddate);
            dataEntity.set("yem_tddate", yem_tddate);
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            IFormView view = this.getView();
            view.updateView("yem_tddate");
        }

        if ("yem_es_storagetrans_sfile".equals(actionId) && returnData != null) {
            putAttachmentData((Map < String, Object > ) returnData, model, this.getView());
//            syncAccessoryPanel(dataEntity);
        }
    }

    /**
     * 是否是最后一次发运（订舱）
     * 是否是最后一批发货
     * @return
     */
    public static boolean isLastShip(DynamicObject dataEntity) {
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        Set<String> set = new HashSet<>();
        for (DynamicObject dynamicObject : collection) {
            String contractnumbersM = dynamicObject.getString("yem_contractnumbers_m");
            set.add(contractnumbersM);
        }
        Map<String, String> order_lastShip = new HashMap<>();
        for (String order_num : set) {
            DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", "=", order_num)});
            DynamicObjectCollection materialinfo = single.getDynamicObjectCollection("yem_es_materialinfo");
            Map<Long, BigDecimal> sales_qty = new HashMap<>();
            for (DynamicObject dynamicObject : materialinfo) {
                long id = dynamicObject.getLong("id");
                BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                sales_qty.put(id, qty);
            }
            long sales_id = single.getLong("id");
            String selectfields = DynamicObjectUtil.getSelectfields("yem_shippingdetails");
            String entrySelectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_shippingdetails", "yem_es_materialinfo");
            DynamicObject[] ships = BusinessDataServiceHelper.load("yem_shippingdetails", entrySelectfields, new QFilter[]{new QFilter("yem_sourcebillid", "=", sales_id)}, "auditdate ASC");
            for (DynamicObject ship : ships) {
                String shipBillno = ship.getString("billno");
                DynamicObjectCollection shipDetail = ship.getDynamicObjectCollection("yem_es_materialinfo");
                for (DynamicObject dynamicObject : shipDetail) {
                    long sourceentryid = dynamicObject.getLong("yem_sourceentryid");
                    BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                    if (sales_qty.containsKey(sourceentryid)) {
                        BigDecimal decimal = sales_qty.get(sourceentryid);
                        decimal = decimal.subtract(qty);
                        sales_qty.put(sourceentryid, decimal);
                    }
                }

                BigDecimal total = BigDecimal.ZERO;
                for (BigDecimal value : sales_qty.values()) {
                    total = total.add(value);
                }

                if (total.compareTo(BigDecimal.ZERO) == 0) {
                    order_lastShip.put(order_num, shipBillno);
                }
            }
        }

        for (DynamicObject dynamicObject : collection) {
            String contractnumbersM = dynamicObject.getString("yem_contractnumbers_m");
            String shipmentnumbersM = dynamicObject.getString("yem_shipmentnumbers_m");
            if (order_lastShip.containsKey(contractnumbersM)
                    && YEM.isNotEmpty(order_lastShip.get(contractnumbersM))
                    && order_lastShip.get(contractnumbersM).equals(shipmentnumbersM)
            )  {
                return true;
            }
        }
        return false;
    }

    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);
            // ...
            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_attachmentpanelap1", retData);
            }
            SaveServiceHelper.save(new DynamicObject[]
                    {
                            dataEntity
                    });
            view.invokeOperation("refresh");
        }
    }

    private void updateStoragetrans(Date yem_tddate) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        String yem_billno = dataEntity.getString("billno");
        DynamicObject yem_es_storagetrans = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans",
                new QFilter[]{new QFilter("billno", QCP.equals, yem_billno)});
        if (yem_es_storagetrans != null) {
            long id = yem_es_storagetrans.getLong("id");
//            DynamicObject storagetrans = BusinessDataServiceHelper.loadSingle(id, "yem_es_storagetrans");
            DynamicObjectCollection yem_creditdetail = yem_es_storagetrans.getDynamicObjectCollection("yem_creditdetail");
            for (int i = 0; i < yem_creditdetail.size(); i++) {
                DynamicObject dynamicObject = yem_creditdetail.get(i);
                int yem_creditdate1_cd = dynamicObject.getInt("yem_creditdate1_cd");
                if (yem_creditdate1_cd > 0) {
                    dynamicObject.set("yem_paydate1", addDays(yem_tddate, yem_creditdate1_cd));
                } else {
                    dynamicObject.set("yem_paydate1", yem_tddate);
                }
                int yem_creditdate2_cd = dynamicObject.getInt("yem_creditdate2_cd");
                if (yem_creditdate2_cd > 0) {
                    dynamicObject.set("yem_paydate2", addDays(yem_tddate, yem_creditdate2_cd));
                } else {
                    dynamicObject.set("yem_paydate2", yem_tddate);
                }
                dynamicObject.set("yem_ladingdate", yem_tddate);
            }

            SaveServiceHelper.save(new DynamicObject[]{yem_es_storagetrans});
        }
    }

    private void syncOrderStatus() {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        Long id = (Long) this.getModel().getValue("yem_corebillid");
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", "id,billno,yem_sourcebillid"
                , new QFilter[]{new QFilter("id", QCP.equals, id)});
        if (dynamicObject != null) {
            long aLong = dynamicObject.getLong("yem_sourcebillid");
            DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle("yem_im_clientdemand", "id,billno,yem_orderplatid"
                    , new QFilter[]{new QFilter("id", QCP.equals, aLong)});
            if (loadSingle != null) {
                String yemOrderplatid = loadSingle.getString("yem_orderplatid");
                map.put("id", yemOrderplatid);
                String yemNoticeno = (String) this.getModel().getValue("yem_noticeno");
                Date yemTddate = (Date) this.getModel().getValue("yem_tddate");
                map.put("status", "4");
                map.put("logisticsNo", yemNoticeno);
                map.put("ladingDate", yemTddate);
                list.add(map);
                OrderApiUtils.partsorderlist(list);
            }
        }

    }

    private void updateCsrCredit(Date yem_tddate) {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        String yem_billno = dataEntity.getString("billno");
        DynamicObject yem_customer = dataEntity.getDynamicObject("yem_customer");
        DynamicObject company = dataEntity.getDynamicObject("yem_company.yem_erporg");
//        DynamicObject csrcreditline = BusinessDataServiceHelper.loadSingle("yem_im_csrcreditline", "id",
//                new QFilter[]{new QFilter("yem_customer", QCP.equals, yem_customer.getPkValue()),
//                        new QFilter("billstatus", QCP.equals, "C")});
        DynamicObject method = TotalUtil.getSettlementMethod(dataEntity);
        String swiftCode = TotalUtil.getSwiftCode(dataEntity);
        DynamicObject csrcreditline = TotalUtil.getCsrCreditLine(yem_customer, method, company, swiftCode);
        if (csrcreditline != null) {
//            long id = csrcreditline.getLong("id");
//            DynamicObject yem_im_csrcreditline = BusinessDataServiceHelper.loadSingle(id, "yem_im_csrcreditline");
//            if (yem_im_csrcreditline != null) {
            DynamicObjectCollection yem_creditdetail = csrcreditline.getDynamicObjectCollection("yem_im_info");
            for (int i = 0; i < yem_creditdetail.size(); i++) {
                DynamicObject dynamicObject = yem_creditdetail.get(i);
                DynamicObject yem_storagetransno = dynamicObject.getDynamicObject("yem_storagetransno");
                if (yem_storagetransno != null) {
                    String billno = yem_storagetransno.getString("billno");
                    if (yem_billno.equals(billno)) {
                        int yem_creditdate1_cd = dynamicObject.getInt("yem_creditdate1_cd");
                        if (yem_creditdate1_cd > 0) {
                            dynamicObject.set("yem_paydate1", addDays(yem_tddate, yem_creditdate1_cd));
                        } else {
                            dynamicObject.set("yem_paydate1", yem_tddate);
                        }
                        int yem_creditdate2_cd = dynamicObject.getInt("yem_creditdate2_cd");
                        if (yem_creditdate2_cd > 0) {
                            dynamicObject.set("yem_paydate2", addDays(yem_tddate, yem_creditdate2_cd));
                        } else {
                            dynamicObject.set("yem_paydate2", yem_tddate);
                        }
                        dynamicObject.set("yem_ladingdate", yem_tddate);

                        Date receivableDate = dynamicObject.getDate("yem_paydate1");
                        if (receivableDate != null) {
                            dynamicObject.set("yem_countpayback", CalendarUtils.calcPayBackCount(receivableDate));
                        }

                    }
                }
//                }
            }
            updateRecentLapseUseDataEntity(csrcreditline);
            SaveServiceHelper.save(new DynamicObject[]{csrcreditline});
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        super.confirmCallBack(e);
        String callBackId = e.getCallBackId();
        if ("creditInsuranceConfirms".equals(callBackId)) {
            if (MessageBoxResult.Yes.equals(e.getResult())) {
                creditInsuranceConfirms();
            }
        }
    }

    private void creditInsuranceConfirms() {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_creditdetail");
        StringBuilder sb = new StringBuilder();
        for (DynamicObject dynamicObject : collection) {
            int index = collection.indexOf(dynamicObject);
            // 投保金额（美元）
            BigDecimal usacreditamt = dynamicObject.getBigDecimal("yem_usacreditamt_cd");
            // 信保天数1
            int creditdate1 = dynamicObject.getInt("yem_creditdate1_cd");
            // 应收款金额1
            BigDecimal paymentamt1 = dynamicObject.getBigDecimal("yem_paymentamt1_cd");

            if (YEM.isEmpty(usacreditamt)) {
                sb.append(String.format("信保明细分录第 [%s] 行，投保金额（美元）不能为空", index + 1)).append("\n");
            }

            if (creditdate1 <= 0) {
                sb.append(String.format("信保明细分录第 [%s] 行，信保天数1不能为空", index + 1)).append("\n");
            }

            if (YEM.isEmpty(paymentamt1)) {
                sb.append(String.format("信保明细分录第 [%s] 行，应收款金额1不能为空", index + 1)).append("\n");
            }
        }

        if (sb.length() > 0) {
            view.showTipNotification(sb.toString());
        } else {
            dataEntity.set("yem_creditbackstatus", "A");
            view.showSuccessNotification("信保确认成功");
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String key = e.getProperty().getName();
        int rowIndex = e.getRow();
        switch (key) {
            case "yem_customclass":
                QFilter filter = filterCustomClass(rowIndex);
                e.addCustomQFilter(filter);
                break;
            case "yem_hscode":
                QFilter hsCodeFilter = filterHsCode(rowIndex);
                e.addCustomQFilter(hsCodeFilter);
                break;
            default:
                break;
        }
    }
    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 registerListener(EventObject e) {
        super.registerListener(e);

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

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

        IFormView view = this.getView();
        if ("yem_es_storagetrans_xbs".equals(view.getEntityId()) || "yem_es_storagetrans".equals(view.getEntityId())) {
            AttachmentPanel attachmentPanel = view.getControl("yem_attachmentpanelap1");
            if (YEM.isNotEmpty(attachmentPanel)) {
                attachmentPanel.addUploadListener(this);
            }
        }
    }

    public static Date addDays(Date d, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(d);
        calendar.add(Calendar.DAY_OF_MONTH, days);
        return calendar.getTime();
    }

    /**
     * 订舱通知单计算 出库报关金额值
     * 出库报关金额差值 = 出库金额 - 订舱通知单明细的销售金额（价格条款）
     * @param dataEntity
     */
    public static void calculateExportAmount(DynamicObject dataEntity) {
        String name = dataEntity.getDataEntityType().getName();
        DynamicObjectCollection materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject dynamicObject : materialinfo) {

            BigDecimal adstamount = dynamicObject.getBigDecimal("yem_adstamount"); // 销售出库金额-提交
            BigDecimal saamtpriceclause;
            if ("yem_es_declaredocx".equals(name)) {

                saamtpriceclause = dynamicObject.getBigDecimal("yem_sellamt"); // 销售金额（价格条款）
            } else {

                saamtpriceclause = dynamicObject.getBigDecimal("yem_saamtpriceclause"); // 销售金额（价格条款）
            }

            BigDecimal amt = adstamount.subtract(saamtpriceclause);
            dynamicObject.set("yem_exportmat", amt);
        }
    }
}
