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

import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.es.Util.ZJUtils;
import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import com.yem.wm.im.clientdemand.utils.ClientUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.IABudgetCommon;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
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.RowDataEntity;
import kd.bos.entity.datamodel.events.*;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.SplitContainer;
import kd.bos.form.events.*;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.ComboEdit;
import kd.bos.form.field.RefBillEdit;
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.sdk.plugin.Plugin;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

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

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

    @Override
    public void afterLoadData(EventObject e) {
        super.afterLoadData(e);
        System.out.println();
    }

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

    @Override
    public void hyperLinkClick(HyperLinkClickEvent e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String fieldName = e.getFieldName();
        int rowIndex = e.getRowIndex();
        if ("yem_intauditbusano".equals(fieldName)) {
            String intAuditBuSaNo = (String) model.getValue("yem_intauditbusano", rowIndex);
            if (YEM.isNotEmpty(intAuditBuSaNo)) {
                BillShowParameter bsp = new BillShowParameter();
                bsp.setFormId("yem_im_intauditbusa");
                bsp.setPkId(model.getValue("yem_intauditbusaid", rowIndex));
                bsp.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                view.showForm(bsp);
            }
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        FormShowParameter fsp = this.getView().getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        String formId = fsp.getFormId();
        String appId = fsp.getAppId();
        if (OperationStatus.ADDNEW == status&&appId.equals("yem_es")) {
            SplitContainer splitContainer = this.getControl("yem_splitcontainerap");
            splitContainer.setCollapse("yem_splitpanelap1", true);
            QFilter qFilter = null;
            if ("yem_es_salesorder_zj".equals(formId)) {
                qFilter = new QFilter("number", QCP.equals, "yem_es_salesorder_ZJ");
            }
            if ("yem_es_salesorder_nmzj".equals(formId)) {
                qFilter = new QFilter("number", QCP.equals, "yem_es_salesorder_nmzj");
            }
            if (YEM.isNotEmpty(qFilter)) {
                DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
                this.getModel().setValue("yem_billtype", billType);
                this.getModel().setValue("yem_billtypetext", billType.getString("name"));
            }
//            model.setValue("yem_givecurrency", model.getValue("yem_currency"));//配件币别默认赋值结算币别


        }
        model.setValue("yem_billbusstype", BusinessDataServiceHelper.loadSingle("yem_bd_billbusstype", "number", new QFilter("number", QCP.equals, "BBT-1").toArray()));
        setGiftGiving();
//        setRandomDataTools();
        FunctionalCommon.defaultValue(model, "yem_es_materialinfo");
        countGiftRate();
        countGiveRate();
        ClientUtils.forResourceNogLock(view, model, "yem_es_materialinfo");
    }

    @Override
    public void registerListener(EventObject e) {
        BasedataEdit billAskFor = this.getControl("yem_billaskfor");
        billAskFor.addBeforeF7SelectListener(this);
        BasedataEdit materialClass = this.getControl("yem_materialclass");
        materialClass.addBeforeF7SelectListener(this);
        BasedataEdit materiel = this.getControl("yem_materiel");
        materiel.addBeforeF7SelectListener(this);
        BasedataEdit productModel = this.getControl("yem_productmodel");
        productModel.addBeforeF7SelectListener(this);
        BasedataEdit resourceNog = this.getControl("yem_resourcenog");
        resourceNog.addBeforeF7SelectListener(this);
        BasedataEdit giveProAcType = this.getControl("yem_giveproactype");
        giveProAcType.addBeforeF7SelectListener(this);
//        BasedataEdit countExpense = this.getControl("yem_countexpense");
//        countExpense.addBeforeF7SelectListener(this);
        RefBillEdit agreementEw = (RefBillEdit) this.getControl("yem_agreementew");
        agreementEw.addBeforeF7SelectListener(this);
        EntryGrid detailedInfor = this.getControl("yem_es_materialinfo");
        detailedInfor.addHyperClickListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        int row = e.getRow();
        switch (name) {
            case "yem_billaskfor":
                billAskForF7Select(e);
                break;
            case "yem_materialclass":
                materialClassF7Select(e);
                break;
            case "yem_materiel":
                materialF7Select(e);
                break;
            case "yem_productmodel":
                selectF7ProductModel(e);
                break;
            case "yem_resourcenog":
                selectF7SourceNo(e, row);
                break;
            case "yem_agreementew":
                selectF7AgreementEw(e);
                break;
            case "yem_giveproactype":
                ZJUtils.selectF7GiveProAcType(model, e);
                break;
        }
    }

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        IFormView view = this.getView();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        IPageCache pageCache = this.getPageCache();
        switch (name) {
            case "yem_bd_products":
                TotalUtil.toolTip(this, e);
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        super.confirmCallBack(e);
        TotalUtil.confirmCallBackFunc(e, "yem_es_materialinfo");
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        Object oldValue = changeData.getOldValue();
        int rowIndex = changeData.getRowIndex();
        int ParentRow = changeData.getParentRowIndex();
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObjectCollection materialInfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        switch (name) {
            case "yem_countexpense":
                countExpense();//选择装箱核算运输费用 携带费用信息分录
                break;
            case "yem_costsumamount":
                countCalculationAmt();//计算附加费总额合计
                break;
            case "yem_addorsub":
                countCalculationAmt();//计算附加费总额合计
                break;

            case "yem_bigcabinetnumbers":
                countBigCabinetQty();//汇总表头大柜数量
                break;
            case "yem_mincabinetnumbers":
                countSmallCabinetQty();//汇总表头小柜数量
                break;
            case "yem_materiel":
                TotalUtil.setUnit(model, rowIndex);//物料为空时  计量单位  基本计量单位 为台
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
                DynamicObject materiel = collection.get(rowIndex).getDynamicObject("yem_materiel");
                if (materiel == null) {
                    model.setValue("yem_customclass", null, rowIndex);
                }
                break;
            case "yem_businesssort":
                countOrderSumNumber();
                setRandomDataTools();//
                ClientUtils.lock(view, model, rowIndex);
                ClientUtils.resourceNogLock(view, model, rowIndex);
                //业务分类改变 清除资源号、物料
                this.getModel().setValue("yem_resourcenog", null, rowIndex);
                this.getModel().setValue("yem_materiel", null, rowIndex);
                syncDeductionGifts(model, rowIndex);
                break;
            case "yem_ifgift":
                ClientUtils.resourceNogLock(view, model, rowIndex);
                ClientUtils.empty(model, rowIndex, "yem_es_materialinfo", view);
                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_safobamount", "yem_amount");//销售fob金额 汇总表头 fob金额
                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_saamtpriceclause", "yem_offeramount");//销售金额（价格条款）汇总表头 金额价格条款
//                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_onecarsum", "yem_sumcost");//单车总费用 汇总表头 总费用
                syncDeductionGifts(model, rowIndex);
                ClientUtils.clearRelevantPrice(model, view, rowIndex, "yem_es_materialinfo");
                break;
            case "yem_productmodel":
                setRandomDataTools();//
                FunctionalCommon.multiConfig(model, rowIndex);
                setGiftGiving();
                bringAssemblyAmount(rowIndex, model, "yem_es_materialinfo");
                break;
            case "yem_isnewagent":
                setGiftGiving();
                break;
            case "yem_resourcenog":
                DynamicObject resourceid = (DynamicObject) model.getValue("yem_resourcenog", rowIndex);
                String businesssort = (String) model.getValue("yem_businesssort", rowIndex);
                if (resourceid != null && "Z".equals(businesssort)) {
                    String resouceNumber = resourceid.getString("number");
                    List<QFilter> qFilterList = new ArrayList<QFilter>();
                    if (!Objects.equals(resouceNumber, "")) {
                        qFilterList.add(new QFilter("number", QCP.equals, resouceNumber));
                    }
                    DynamicObject tempCol = BusinessDataServiceHelper.loadSingle("bd_material", "11", qFilterList.toArray(new QFilter[0]));
                    if (tempCol != null) {
                        model.setValue("yem_materiel", tempCol.getLong("id"), rowIndex);
                    } else {
                        model.setValue("yem_materiel", null, rowIndex);
                        view.showMessage("请维护编码【" + resouceNumber + "】的物料！");
                    }
                }
                break;
            case "yem_incompid":
                ClientUtils.resouceToMaterial(model, view, rowIndex);
                ClientUtils.addPjSourceAccount(model, materialInfo);//资源配件金额
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_incomptext":
                String incomptext = (String) model.getValue("yem_incomptext", rowIndex);
                if (YEM.isEmpty(incomptext)) {
                    model.setValue("yem_incompid", null, rowIndex);
                    model.setValue("yem_resourcenog", null, rowIndex);
                }
                break;
            case "yem_exrate":
//            case "yem_exwrmbprice":
                ZJUtils.countCostSumAmountZJ(model);
                countCalculationAmt();
                ClientUtils.changeRate(model, "yem_es_materialinfo");
                ClientUtils.clearSalePrice(this.getModel());
                break;
            case "yem_qty":
                setRandomDataTools();
                ZJUtils.countOrderSumNumberZJ(model);
                setGiftGiving();
                ClientUtils.countFobAmt(model, rowIndex);//计算FOB金额
                ClientUtils.addSaPriceSale(model, rowIndex);//计算销售FOB金额
//                ClientUtils.countRealCatAmount(model, rowIndex);//实际整车金额
                ClientUtils.addPjSourcePrice(model, rowIndex);//资源配件单价
                ClientUtils.countRealCatAmountRMB(model, rowIndex);//实际整车金额人民币
                ClientUtils.countFrontDisAmt(model, rowIndex);//折扣前销售金额
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                ClientUtils.countAfterFrontPrice(model, rowIndex);//折扣后销售单价
                syncDeductionGifts(model, rowIndex);
                break;
            case "yem_saamtpriceclause"://销售金额（价格条款）
                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_saamtpriceclause", "yem_offeramount");//销售金额（价格条款）汇总表头 金额价格条款
                break;
            case "yem_frontdisprice"://折扣前单价
                ClientUtils.countFrontDisAmt(model, rowIndex);//折扣前销售金额
                break;
            case "yem_standardprice"://标配FOB（青岛价）
                ClientUtils.fobPriceAdd(model, materialInfo);//FOB单价
                ClientUtils.countFobAmtSale(model, rowIndex);//销售FOB标配青岛单价
                break;
            case "yem_truecarpriceba":
                ClientUtils.countRealCatAmountRMB(model, rowIndex);
                break;
            case "yem_unitsetamountbase"://单台加价金额
                ClientUtils.fobPriceAdd(model, materialInfo);//FOB单价
                break;
            case "yem_fobprice"://fob单价
                this.getModel().getValue("yem_fobprice", rowIndex);
                ClientUtils.countFobAmt(model, rowIndex);//计算FOB金额
                break;
            case "yem_pricefieldaccamt":
                ClientUtils.addPjSourcePrice(model, rowIndex);//资源配件单价
                break;
            case "yem_safobamount"://销售fob金额
                ClientUtils.addPjSourceAccount(model, materialInfo);//资源配件金额
                ClientUtils.addSaPriceSaleRMB(model, rowIndex);//销售FOB金额（人民币）
                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_safobamount", "yem_amount");//销售fob金额汇总表头fob金额
//                ClientUtils.countSaPricePriceClause(model, rowIndex);//计算销售单价（价格条款）
                ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex, view);//计算折扣金额
                ClientUtils.countAfterFrontAmt(model, rowIndex);//计算折扣后销售金额

                break;
            case "yem_sastandardprice"://
                ClientUtils.countFobAmtSaleRMB(model, rowIndex);//销售FOB标配青岛单价（本位币）
                ClientUtils.addSaPrice(model, materialInfo);//销售FOB单价（结算币别）
                break;
            case "yem_safobprice":
                ClientUtils.addSaPriceRMB(model, rowIndex);//销售FOB单价（人民币）
                ClientUtils.addSaPriceSale(model, rowIndex);//销售fob金额
                ClientUtils.countFrontDisPrice(model, rowIndex);//折扣前单价
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                ClientUtils.calculateInsurancePremiums(rowIndex, model);//保险费
                ClientUtils.calculateCreditAmount(rowIndex, model);//信保费
                ClientUtils.calculateBankInterestCharges(rowIndex, model);//银行利息费
                break;

            case "yem_onecarsum":
                ClientUtils.countFrontDisPrice(model, rowIndex);//折扣前单价
//                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_onecarsum", "yem_sumcost");//单车总费用 汇总表头 总费用
//                ClientUtils.countSaPricePriceClause(model, rowIndex);//计算销售单价（价格条款）
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_unitsetamount"://单台加价金额
                ClientUtils.addSaPrice(model, materialInfo);//销售FOB单价（结算币别）
                break;

            case "yem_sapricepriceclause"://销售单价（价格条款）结算币别
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_sapriceclausebase"://销售单价（价格条款人民币）
//                ClientUtils.countRealCatPrice(model, rowIndex);//实际整车单价
                break;
            case "yem_pricefieldacc"://销售单价（价格条款人民币）
//                ClientUtils.countRealCatPrice(model, rowIndex);//实际整车单价
                break;
            case "yem_truecarprice"://实际整车单价
//                ClientUtils.countRealCatAmount(model, rowIndex);//实际整车金额
                ClientUtils.countRealCatPriceRMB(model, rowIndex);//实际整车单价人民币
                break;
            case "yem_reccondition":
                ZJUtils.setSalesContracZJ(model);//选择收款条件时带出收款计划分录
                TotalUtil.countRapAmt(model, "yem_es_salescontrac_s");
                TotalUtil.countRapRate(model, "yem_es_salescontrac_s");
                break;
            case "yem_pricefieldaccba": //资源配件单价
//                ClientUtils.countSaPricePriceClause(model, rowIndex);//计算销售单价（价格条款）
//                ClientUtils.countRealCatPrice(model, rowIndex);
                ClientUtils.countFrontDisPrice(model, rowIndex);//折扣前单价
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_ticketprice":
            case "yem_bigcabinetprice":
            case "yem_mincabinetprice":
            case "yem_bigcabinetnumber":
            case "yem_mincabinetnumber":
            case "yem_singlenumber":
                ZJUtils.countCostSumAmountZJ(model);//
                break;
            case "yem_marketraisepribase":
                ClientUtils.countStandardSales(model);
                break;
            case "yem_giftcurrency":
                countGiftRate();
                break;
            case "yem_givecurrency":
                countGiveRate();
                break;
            case "yem_issinosurecon":
                setMustIsSinosure();
                setSinosureRate();
                break;
            case "yem_transportstyle":
//                setInsuranceFeeRate();
                break;
            case "yem_clientcountry":
            case "yem_rapstyle":
            case "yem_term":
                setSinosureRate();
                break;
            case "yem_offeramount":
                TotalUtil.countRapRate(model, "yem_es_salescontrac_s");
                TotalUtil.countRapAmt(model, "yem_es_salescontrac_s");
                break;
            case "yem_raprate":
                TotalUtil.countRapAmt(model, "yem_es_salescontrac_s");
                ClientUtils.calculateCreditAmount(-1, model);//信保费
                ClientUtils.calculateBankInterestCharges(-1, model);//银行利息费
                break;
            case "yem_rapamt":
                TotalUtil.countRapRate(model, "yem_es_salescontrac_s");
                break;
            case "yem_isgiftgive":
                setGiftGiving();
                isGiftGive();
                break;
            case "yem_lenghtunit"://长度单位
            case "yem_vol"://体积
                TotalUtil.countVolM3(model, rowIndex, "yem_lenghtunit", "yem_vol", "yem_volm3");
                ;
                break;
            case "yem_qtyint"://配件赠送分录 台数
                ZJUtils.limitQtyInt(view, model, oldValue, rowIndex);
                break;
            case "yem_afterfrontdisprice"://折扣后销售单价
//                ClientUtils.countSaPricePriceClause(model, rowIndex);//计算销售单价（价格条款）
                break;
            case "yem_accamtusetype"://配件资金使用方式
                ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex, view);//计算折扣金额
                break;
            case "yem_fundpoolamt"://使用额度
                ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex, view);//计算折扣金额
                break;
            case "yem_amount"://财务信息 fob金额
                ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex, view);//计算折扣金额
                break;
            case "yem_frontrateentry"://明细信息 折扣率
                ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex, view);//计算折扣金额
                break;
            case "yem_afterfrontdisamt"://折扣后销售金额
                ClientUtils.countAfterFrontPrice(model, rowIndex);//折扣后销售单价
                break;
            case "yem_disamt"://折扣金额
                ClientUtils.countFrontDisAmt(model, rowIndex);//折扣前金额
                ClientUtils.countAfterFrontAmt(model, rowIndex);//计算折扣后销售金额
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_giveproactype":
                summarizeModules(rowIndex);
                break;
            case "yem_totalamount": // 总费用(分录)
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_isgiftgiveparts":
                String isgiftgiveparts = (String) model.getValue("yem_isgiftgiveparts");
                if ("B".equals(isgiftgiveparts)) {
                    model.deleteEntryData("yem_es_salesorder_zp");
                }
                break;
            case "yem_sinosurerate"://信保费率
            case "yem_issinosure"://是否信保
                ClientUtils.calculateCreditAmount(-1, model);//信保费
                ClientUtils.calculateBankInterestCharges(-1, model);//银行利息费
                break;
            case "yem_e_seafreight":// 海运费
                ClientUtils.calculateInsurancePremiums(rowIndex, model);//保险费
                ClientUtils.calculateCreditAmount(rowIndex, model);//信保费
                ClientUtils.calculateBankInterestCharges(rowIndex, model);//银行利息费
                break;
            case "yem_insuranceaddrate"://保险加成率
                ClientUtils.calculateInsurancePremiums(-1, model);//保险费
                break;
            case "yem_insurancefeerate"://运保费率
                ClientUtils.calculateInsurancePremiums(-1, model);//保险费
                break;
            case "yem_e_marinsupreamt"://保险费
                ClientUtils.calculateCreditAmount(rowIndex, model);//信保费
                ClientUtils.calculateBankInterestCharges(rowIndex, model);//银行利息费
                break;
            case "yem_e_interestrate"://利息率%
                ClientUtils.calculateBankInterestCharges(rowIndex, model);//银行利息费
                break;
            case "yem_e_interestamt"://银行利息费
                ClientUtils.calculateCreditAmount(rowIndex, model);//信保费
                break;
            case "yem_interestdays":
                ClientUtils.calculateBankInterestCharges(-1, model);//银行利息费
                break;
        }
    }

    /**
     * 基础机型携带拆装费用
     *
     * @param rowIndex
     * @param entryKey
     */
    public static void bringAssemblyAmount(int rowIndex, IDataModel model, String entryKey) {
        DynamicObject dismountingcost = (DynamicObject) model.getValue("yem_productmodel", rowIndex);
        if (dismountingcost == null) return;
        DynamicObject products = dismountingcost.getDynamicObject("yem_products");
        if (products == null) return;
        Long id = (Long) products.getPkValue();
        QFilter qFilter = new QFilter("yem_detail.yem_bd_mechanical.id", QCP.equals, id);
        DynamicObject load = BusinessDataServiceHelper.loadSingle("yem_bd_costs", qFilter.toArray());
        if (load == null) return;
        DynamicObjectCollection collection = load.getDynamicObjectCollection("yem_detail");
        for (DynamicObject object : collection) {
            DynamicObject mechanical = object.getDynamicObject("yem_bd_mechanical");
            if (mechanical == null) continue;
            Long pkValue = (Long) mechanical.getPkValue();
            if (Objects.equals(pkValue, id)) {
                BigDecimal tearamount = object.getBigDecimal("yem_tearamount");
                model.setValue("yem_dismountingcost", tearamount, rowIndex);
            }
        }
    }

    /**
     * 选择赠送配件-产品机型，汇总明细信息中相同机型的数量
     * @param rowIndex
     */
    private void summarizeModules(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject dynamicObject = model.getDataEntity(true);
        DynamicObject giveproactype = (DynamicObject) model.getValue("yem_giveproactype", rowIndex);
        if (giveproactype == null) return;
        DynamicObjectCollection materialinfo = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
        BigDecimal qty = BigDecimal.ZERO;
        for (DynamicObject object : materialinfo) {
            String businesssort = object.getString("yem_businesssort");
            boolean ifgift = object.getBoolean("yem_ifgift");
            if ("Z".equals(businesssort) && !ifgift) {
                DynamicObject productmodel = object.getDynamicObject("yem_productmodel");
                if (productmodel == null) continue;
                productmodel = BusinessDataServiceHelper.loadSingle(productmodel.getPkValue(), productmodel.getDynamicObjectType().getName());
                DynamicObject products = productmodel.getDynamicObject("yem_products");
                if (products != null && products.getLong("id") == giveproactype.getLong("id")) {
                    qty = qty.add(object.getBigDecimal("yem_qty"));
                }
            }
        }
        model.setValue("yem_qtyint", qty, rowIndex);
    }


    /**
     * 修改商品明细中数量，同步修改礼品赠送中数量
     * @param model
     * @param rowIndex
     */
    private void syncDeductionGifts(IDataModel model, int rowIndex) {
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObject productmodel = (DynamicObject) model.getValue("yem_productmodel", rowIndex);
        if (productmodel == null) return;
        productmodel = BusinessDataServiceHelper.loadSingle(productmodel.getPkValue(), productmodel.getDynamicObjectType().getName());
        DynamicObject products = productmodel.getDynamicObject("yem_products");
        if (products == null) return;
        Long detailId = (Long) products.getPkValue();
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_zp");
        for (DynamicObject object : collection) {
            int index = collection.indexOf(object);
            DynamicObject giftproactype = object.getDynamicObject("yem_giveproactype");
            if (giftproactype == null) continue;
            Long giftId = (Long) giftproactype.getPkValue();
            if (Objects.equals(giftId, detailId)) {
                summarizeModules(index);
            }
        }
    }


    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        String name = e.getEntryProp().getName();
        RowDataEntity[] rowDataEntities = e.getRowDataEntities();
        IDataModel model = this.getModel();
        for (RowDataEntity rowDataEntitie : rowDataEntities) {
            int rowIndex = rowDataEntitie.getRowIndex();
            if ("yem_es_materialinfo".equals(name)) {
                setMaterialType(rowIndex);
                bringAssemblyAmount(rowIndex, model, name);
            }
        }

    }


    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getEntryProp().getName();
        int[] rowIndexs = e.getRowIndexs();

        for (int rowIndex : rowIndexs) {
            if ("yem_es_salesorder_p".equals(name)) {
//                deleteMaterialOperation(rowIndex);
            }

        }


    }


    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        super.afterDeleteRow(e);
        String name = e.getEntryProp().getName();
        DynamicObject dyEntry = this.getModel().getDataEntity(true);
        DynamicObjectCollection dy = dyEntry.getDynamicObjectCollection("yem_es_materialinfo");
        int[] rowIndexs = e.getRowIndexs();
        if ("yem_es_materialinfo".equals(name)) {
            setGiftGiving();
            ClientUtils.addPjSourceAccount(this.getModel(), dy);
        }
        if ("yem_multiconfig".equals(name)) {
            ClientUtils.deleteRowFobPriceAdd(this.getModel());
            ClientUtils.addSaPrice(this.getModel(), dy);
        }
    }

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

        switch (key) {
            case "optionaloperation":
                FunctionalCommon.optionalOperation(model, view, "yem_optional", "optionaloperation");
                break;
            case "replaceoperation":
                FunctionalCommon.optionalOperation(model, view, "yem_replace", "replaceoperation");
                break;
            case "retrofittingoperation":
                FunctionalCommon.optionalOperation(model, view, "yem_retrofitting", "retrofittingoperation");
                break;
            case "getprice":
                DynamicObject datas = this.getModel().getDataEntity(true);
                ClientUtils.getPriceNew(datas, this.getModel(), this.getView());
//                ClientUtils.clearSalePrice(this.getModel());
//                ClientUtils.resetValueZJ(this.getModel());
                String fundusetype = dataEntity.getString("yem_accamtusetype");
                if ("A".equals(fundusetype)) {
                    ClientUtils.countAmtDisAmt(model, "yem_es_materialinfo", view);
                }
                break;
            case "createauditbill":
                Boolean yem_changing = (Boolean) model.getValue("yem_changing");
                Boolean issinosurecon = (Boolean) model.getValue("yem_issinosurecon");
                DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
                String number = billType.getString("number");
                boolean pass = true;
                if (issinosurecon && !StringUtils.containsIgnoreCase(number, "nm")) {
                    StringBuilder sb = new StringBuilder();
                    int rowCount = model.getEntryRowCount("yem_es_salescontrac_s");
                    for (int i = 0; i < rowCount; i++) {
                        String issinosure = (String) model.getValue("yem_issinosure", i);
                        DynamicObject term = (DynamicObject) model.getValue("yem_term", i);
                        if ("A".equals(issinosure) && YEM.isEmpty(term)) {
                            sb.append(String.format("收款计划分录第 %s 行，是否信保为是，信用期限必填！！", i + 1)).append("\r\n");
                        }
                    }
                    if (sb.length() > 0) {
                        pass = false;
                        view.showErrorNotification(sb.toString());
                    }
                }
                if (!yem_changing && pass) {
//                    FunctionalCommon.clientDemandStartZj(this, "yem_es_materialinfo", "yem_es_salescontrac_s");
                    EntryGrid materialinfo = this.getControl("yem_es_materialinfo");
                    int[] selectRowIds = materialinfo.getSelectRows();
                    IABudgetCommon.pushToGeneration(dataEntity, selectRowIds, "yem_es_materialinfo");
                    view.invokeOperation("refresh");
                } else {
                    view.showErrorNotification("当前合同存在未审核的变更单，禁止生成《内审预算单》");
                }
                break;
            case "getmachine":
                ZJUtils.renewMachineProductInfo(view, model);
                renewTrackTask();
                break;
            case "save":
                view.invokeOperation("refresh");
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        IDataModel model = this.getModel();
        if ("save".equals(operateKey)) {
            SalesOrderUtils.generatePartGiftEntry(model);
        }
    }

    public void viewForm(String formId, Map<String, Object> map) {
        IFormView view = this.getView();
        FormShowParameter formShowParameter = new FormShowParameter();
        formShowParameter.setFormId(formId);
        formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        formShowParameter.setCustomParams(map);
        view.showForm(formShowParameter);
    }

    /**
     * @param rowIndex
     * @Description 明细分录增行根据 单据类型给物料分类赋值
     */
    private void setMaterialType(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        if (billType != null) {
            String number = billType.getString("number");
            model.setValue("yem_businesssort", "Z", rowIndex);
        }
    }

    /**
     * @param e
     * @Description 单据要求根据客户过滤
     */
    public void billAskForF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject customer = (DynamicObject) model.getValue("yem_customer");
        if (customer != null) {
            e.addCustomQFilter(new QFilter("yem_customer", QCP.equals, customer.getPkValue()));
        } else {
            e.addCustomQFilter(new QFilter("yem_customer", QCP.equals, 1L));
        }
    }

    /**
     * @param e
     * @Description 物料根据物料分类过滤
     */
    public void materialF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        int row = e.getRow();
        DynamicObject materialClass = (DynamicObject) model.getValue("yem_materialclass", row);
        if (materialClass != null) {
            e.addCustomQFilter(new QFilter("group", QCP.equals, materialClass.getPkValue()));
        }
    }

    /**
     * @param e
     * @Description 根据单据类型过滤明细分录 物料分类
     */
    public void materialClassF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        if (billType != null) {
            String number = billType.getString("number");
            e.addCustomQFilter(new QFilter("number", QCP.in, new String[]{"PJ", "ZJ"}));
        }
    }

    /**
     * @Description 选择装箱核算运输费用 携带费用信息分录
     */
    public void countExpense() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        model.deleteEntryData("yem_costinfor");
        Object exrateTable = model.getValue("yem_exratetable");
        Date exrateDate = (Date) model.getValue("yem_exratedate");
        DynamicObject countExpense = (DynamicObject) model.getValue("yem_countexpense");
        if (YEM.isNotEmpty(countExpense)) {
            countExpense = BusinessDataServiceHelper.loadSingle(countExpense.getPkValue(), countExpense.getDynamicObjectType().getName());
            DynamicObject priceCurrency = countExpense.getDynamicObject("yem_pricecurrency");
            BigDecimal ticketPriceRate = YEM.getExchangeRate(exrateTable, priceCurrency, FunctionalCommon.getAmountFieldCurrencyKey(view, "yem_ticketprice"), exrateDate);
            BigDecimal bigCabinetPrice = YEM.getExchangeRate(exrateTable, priceCurrency, FunctionalCommon.getAmountFieldCurrencyKey(view, "yem_bigcabinetprice"), exrateDate);
            BigDecimal minCabinetPrice = YEM.getExchangeRate(exrateTable, priceCurrency, FunctionalCommon.getAmountFieldCurrencyKey(view, "yem_mincabinetprice"), exrateDate);
            DynamicObjectCollection logistics = countExpense.getDynamicObjectCollection("yem_bd_logistics");
            for (DynamicObject logistic : logistics) {
                int salesOrderRow = model.createNewEntryRow("yem_costinfor");
                model.setValue("yem_addorsub", "B", salesOrderRow);//费用项目
                model.setValue("yem_padexpense", logistic.getDynamicObject("yem_padexpense"), salesOrderRow);//费用项目
                model.setValue("yem_bd_chargemode", logistic.getDynamicObject("yem_billingway"), salesOrderRow);//计费方式
                model.setValue("yem_ticketprice", logistic.getBigDecimal("yem_ticketprice").multiply(ticketPriceRate), salesOrderRow);//按票单价
                model.setValue("yem_bigcabinetprice", logistic.getBigDecimal("yem_bigcabinetprice").multiply(bigCabinetPrice), salesOrderRow);//大柜单价
                model.setValue("yem_mincabinetprice", logistic.getBigDecimal("yem_mincabinetprice").multiply(minCabinetPrice), salesOrderRow);//小柜单价
            }
        }

//        setLockExpenseInfo(view, model);
    }

    /**
     * @Description 汇总表头大柜数量
     */
    private void countBigCabinetQty() {
        IDataModel model = this.getModel();
        BigDecimal totalQty = BigDecimal.ZERO;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            totalQty = totalQty.add((BigDecimal) model.getValue("yem_bigcabinetnumbers", i));
        }
        model.setValue("yem_bigcabinetnumber", totalQty);
    }

    /**
     * @Description 汇总表头小柜数量
     */
    private void countSmallCabinetQty() {
        IDataModel model = this.getModel();
        BigDecimal totalQty = BigDecimal.ZERO;
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        for (int i = 0; i < materialInfoRows; i++) {
            totalQty = totalQty.add((BigDecimal) model.getValue("yem_mincabinetnumbers", i));
        }
        model.setValue("yem_mincabinetnumber", totalQty);
    }


    /**
     * @Description 配件池计算折扣金额
     */
    public void countAccCapitalPool() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String fundUseType = (String) model.getValue("yem_fundusetype");
        BigDecimal fundPoolAmt = (BigDecimal) model.getValue("yem_fundpoolamt");
        if ("B".equals(fundUseType) && fundPoolAmt.compareTo(BigDecimal.ZERO) > 0) {
            BigDecimal total = (BigDecimal) model.getValue("yem_amount");
            int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
//            for (int i = 0; i < materialInfoRows; i++) {
//                total = total.add((BigDecimal) model.getValue("yem_amt",i));
//            }
            for (int i = 0; i < materialInfoRows; i++) {
                BigDecimal amt = (BigDecimal) model.getValue("yem_amt", i);
                if (total.compareTo(BigDecimal.ZERO) > 0) {
                    model.setValue("yem_disamt", amt.divide(total, 2).multiply(fundPoolAmt), i);
                } else {
                    model.setValue("yem_disamt", BigDecimal.ZERO, i);
                }

            }
        }
    }

//    /**
//     * @Description 单据类型为整机 物料带出资源号
//     * @param rowIndex
//     */
//    public void setResourceNog(int rowIndex){
//        IDataModel model = this.getModel();
//        DynamicObject billType = (DynamicObject)model.getValue("yem_billtype");
//        if(billType != null){
//            String number = billType.getString("number");
//            if("yem_es_salesorder_ZJ".equals(number)){
//                model.setValue("yem_resourcenog",model.getValue("yem_materiel", rowIndex),rowIndex);
//            }
//        }
//    }

//    /**
//     * @Description 单据类型为整机 资源号带出物料
//     * @param rowIndex
//     */
//    public void setMateriel(int rowIndex){
//        IDataModel model = this.getModel();
//        DynamicObject billType = (DynamicObject)model.getValue("yem_billtype");
//        if(billType != null) {
//            String number = billType.getString("number");
//            if ("yem_es_salesorder_ZJ".equals(number)) {
//                model.setValue("yem_materiel",model.getValue("yem_resourcenog", rowIndex),rowIndex);
//            }
//        }
//    }


    /**
     * @description 当物料分类为整机时，选择产品型号带出 随机资料及配件工具包分录
     * @author xwudd
     * return
     * @time 2023/7/25 9:09
     */

    public void setRandomDataTools() {
        IDataModel model = this.getModel();
        int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
        model.deleteEntryData("yem_es_salesorder_p");
        String selectfields = DynamicObjectUtil.getSelectfields("yem_overalltoollib", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_overalltoollib", "yem_infor", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_overalltoollib", "yem_spareparts", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_overalltoollib", "yem_tools", false);
        Map<Long, BigDecimal> map = new HashMap();
        for (int i = 0; i < materialInfoRows; i++) {
            String materialClass = (String) model.getValue("yem_businesssort", i);
            DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", i);
            if (YEM.isNotEmpty(materialClass) && YEM.isNotEmpty(productModel)) {
                if ("Z".equals(materialClass)) {
                    DynamicObject products = productModel.getDynamicObject("yem_products");
                    if (YEM.isNotEmpty(products)) {
                        Long id = products.getLong("id");
                        if (map.containsKey(id)) {
                            map.put(id, map.get(id).add((BigDecimal) model.getValue("yem_qty", i)));
                        } else {
                            map.put(id, (BigDecimal) model.getValue("yem_qty", i));
                        }
                    }

                }
            }
        }
        Set<Long> ids = map.keySet();
        for (Long id : ids) {
            DynamicObject overAllToolLib = BusinessDataServiceHelper.loadSingle("yem_overalltoollib", selectfields,
                    new QFilter[]{new QFilter("yem_productmodel", QCP.equals, id)});
            if (overAllToolLib != null) {
                DynamicObjectCollection infors = overAllToolLib.getDynamicObjectCollection("yem_infor");
                DynamicObjectCollection spareparts = overAllToolLib.getDynamicObjectCollection("yem_spareparts");
                DynamicObjectCollection tools = overAllToolLib.getDynamicObjectCollection("yem_tools");
//                for (DynamicObject infor : infors) {
//                    int entryRow = model.createNewEntryRow("yem_es_salesorder_p");
//                    model.setValue("yem_accessorytype", overAllToolLib.getDynamicObject("yem_productmodel"), entryRow);
//                    model.setValue("yem_volvotype", "A", entryRow);
//                    model.setValue("yem_accesmaterial", infor.getDynamicObject("yem_material_i"), entryRow);
//                    model.setValue("yem_acunit", infor.getDynamicObject("yem_unit_i"), entryRow);
//                    model.setValue("yem_bicycleqty", infor.getBigDecimal("yem_qty_i"), entryRow);
//                    model.setValue("yem_acremark", infor.getString("yem_remark_i"), entryRow);
//                    model.setValue("yem_pcstype", map.get(id), entryRow);
//                    model.setValue("yem_acallqty", map.get(id).multiply(infor.getBigDecimal("yem_qty_i")), entryRow);
//                }
                for (DynamicObject sparepart : spareparts) {
                    int entryRow = model.createNewEntryRow("yem_es_salesorder_p");
                    model.setValue("yem_accessorytype", overAllToolLib.getDynamicObject("yem_productmodel"), entryRow);
                    model.setValue("yem_volvotype", "B", entryRow);
                    model.setValue("yem_accesmaterial", sparepart.getDynamicObject("yem_material_s"), entryRow);
                    model.setValue("yem_acunit", sparepart.getDynamicObject("yem_unit_s"), entryRow);
                    model.setValue("yem_bicycleqty", sparepart.getBigDecimal("yem_qty_s"), entryRow);
                    model.setValue("yem_acremark", sparepart.getString("yem_remark_s"), entryRow);
                    model.setValue("yem_pcstype", map.get(id), entryRow);
                    model.setValue("yem_acallqty", map.get(id).multiply(sparepart.getBigDecimal("yem_qty_s")), entryRow);
                    model.setValue("yem_materialentryid", id, entryRow);
                }
                for (DynamicObject tool : tools) {
                    int entryRow = model.createNewEntryRow("yem_es_salesorder_p");
                    model.setValue("yem_accessorytype", overAllToolLib.getDynamicObject("yem_productmodel"), entryRow);
                    model.setValue("yem_volvotype", "C", entryRow);
                    model.setValue("yem_accesmaterial", tool.getDynamicObject("yem_material_t"), entryRow);
                    model.setValue("yem_acunit", tool.getDynamicObject("yem_unit_t"), entryRow);
                    model.setValue("yem_bicycleqty", tool.getBigDecimal("yem_qty_t"), entryRow);
                    model.setValue("yem_acremark", tool.getString("yem_remark_t"), entryRow);
                    model.setValue("yem_pcstype", map.get(id), entryRow);
                    model.setValue("yem_acallqty", map.get(id).multiply(tool.getBigDecimal("yem_qty_t")), entryRow);
                    model.setValue("yem_materialentryid", id, entryRow);
                }
            }
        }
    }


    public void deleteMaterialOperation(int rowIndex) {
        IDataModel model = this.getModel();
//        DynamicObject materialInfo = model.getEntryRowEntity("yem_es_materialinfo", rowIndex);
//        if (materialInfo != null) {
        List<Integer> seqs = new ArrayList();
//            Long id = materialInfo.getLong("id");
        long currentEntryId = (long) model.getValue("yem_materialentryid", rowIndex);
        int entryRows = model.getEntryRowCount("yem_es_salesorder_p");
        for (int i = 0; i < entryRows; i++) {
            Long materialEntryId = (Long) model.getValue("yem_materialentryid", i);
            if (materialEntryId.equals(currentEntryId)) {
                seqs.add(i);
            }
        }
        if (seqs.contains(rowIndex)) {
            seqs.remove(rowIndex);
        }
        model.deleteEntryRows("yem_es_salesorder_p", ArrayUtils.toPrimitive(seqs.toArray(new Integer[0])));
//        }
    }


    public void countCalculationAmt() {
        IDataModel model = this.getModel();
        int rows = model.getEntryRowCount("yem_costinfor");
        BigDecimal total = BigDecimal.ZERO;
        for (int i = 0; i < rows; i++) {
            String addOrSub = (String) model.getValue("yem_addorsub", i);
            if ("A".equals(addOrSub)) {
                total = total.add((BigDecimal) model.getValue("yem_costsumamount", i));
            }
        }
        model.setValue("yem_calculationamt", total);
    }


    /**
     * @description 选择基础机型根据表头产品分类过滤
     * @author xwudd
     * * @param[1] e
     * @time 2023/7/28 18:09
     */

    public void selectF7ProductModel(BeforeF7SelectEvent e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        if (products != null) {
            e.addCustomQFilter(new QFilter("yem_productsgroup", QCP.equals, products.getPkValue()));
        } else {
            view.showMessage("请先维护基本信息-产品分类字段!");
            e.setCancel(true);

        }
    }


    /**
     * @description 汇总数量到 订单总台数/数量
     * @author xwudd
     * return
     * @time 2023/7/29 16:38
     */

    public void countOrderSumNumber() {
        IDataModel model = this.getModel();
        BigDecimal total = BigDecimal.ZERO;
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        if (YEM.isNotEmpty(billType)) {
            String number = billType.getString("number");
            int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
            for (int i = 0; i < materialInfoRows; i++) {
                String businessSort = (String) model.getValue("yem_businesssort", i);
                if ("Z".equals(businessSort)) {
                    total = total.add((BigDecimal) model.getValue("yem_qty", i));
                }
            }

        }
        model.setValue("yem_ordersumnumber", total);
    }


    public void selectF7SourceNo(BeforeF7SelectEvent e, int row) {
        IDataModel model = this.getModel();
        DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", row);
        if (YEM.isNotEmpty(productModel)) {
            DynamicObject products = productModel.getDynamicObject("yem_products");
            if (products != null) {
                e.addCustomQFilter(new QFilter("yem_products", QCP.equals, products.getPkValue()));
            }
        }
    }

    /**
     * @description 计算礼品汇率
     * @author xwudd
     * return
     * @time 2023/8/2 18:02
     */

    public void countGiftRate() {
        IDataModel model = this.getModel();
        DynamicObject exrateTable = (DynamicObject) model.getValue("yem_exratetable");
        DynamicObject sourceCurrency = (DynamicObject) model.getValue("yem_giftcurrency");
        DynamicObject targetCurrency = (DynamicObject) model.getValue("yem_currencybase");
        Date exrateDate = (Date) model.getValue("yem_exratedate");
        BigDecimal exchangeRate = YEM.getExchangeRate(exrateTable, sourceCurrency, targetCurrency, exrateDate);
        model.setValue("yem_giftdecimal", exchangeRate);
    }

    /**
     * @description 计算配件汇率
     * @author xwudd
     * return
     * @time 2023/8/2 18:02
     */

    public void countGiveRate() {
        IDataModel model = this.getModel();
//        DynamicObject exrateTable = (DynamicObject) model.getValue("yem_exratetable");
//        DynamicObject sourceCurrency = (DynamicObject) model.getValue("yem_givecurrency");
//        DynamicObject targetCurrency = (DynamicObject) model.getValue("yem_currencybase");
//        Date exrateDate = (Date) model.getValue("yem_exratedate");
//        BigDecimal exchangeRate = YEM.getExchangeRate(exrateTable, sourceCurrency, targetCurrency, exrateDate);
        BigDecimal exrate = (BigDecimal) model.getValue("yem_exrate");
        model.setValue("yem_givedecimal", exrate);
    }

    /**
     * @description 是否信保 根据表头是否信保合同动态必录
     * @author xwudd
     * @time 2023/8/4 11:52
     */
    public void setMustIsSinosure() {
        IDataModel model = this.getModel();
        Boolean isSinosurecon = (Boolean) model.getValue("yem_issinosurecon");
        ComboEdit isSinosure = (ComboEdit) this.getControl("yem_issinosure");
        if (isSinosurecon) {
            isSinosure.setMustInput(true);
        } else {
            isSinosure.setMustInput(false);
        }
    }

    /**
     * @description 赋值信保费率
     * @author xwudd
     * return
     * @time 2023/8/4 14:18
     */
    public void setSinosureRate() {
        SalesOrderUtils.setSinosureRate(this.getModel(), this.getView());
    }


    /**
     * @description 过滤装箱核算运输费用
     * @author xwudd
     * @param[1] e
     * return
     * @time 2023/8/7 18:02
     */

    public void selectF7countExpense(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject billType = (DynamicObject) model.getValue("yem_billtype");
        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        if (YEM.isNotEmpty(billType)) {
            e.addCustomQFilter(new QFilter("yem_accountingtype", QCP.equals, "Z"));
        }
        if (YEM.isNotEmpty(products)) {
            e.addCustomQFilter(new QFilter("yem_bd_products", QCP.equals, products.getPkValue()));
        }
    }

    /**
     * @description 根据客户过滤框架合同协议
     * @author xwudd
     * @param[1] e
     * return
     * @time 2023/8/8 9:28
     */
    private void selectF7AgreementEw(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject customer = (DynamicObject) model.getValue("yem_customer");
        if (YEM.isNotEmpty(customer)) {
            e.addCustomQFilter(new QFilter("yem_customer", QCP.equals, customer.getPkValue()));
        }
    }

    /**
     * @description 根据明细信息的 基础机型和数量 带出礼品赠送分录
     * @author xwudd
     * return
     * @time 2023/8/8 10:56
     */

    private void setGiftGiving() {
        IDataModel model = this.getModel();
        String isNewAgent = (String) model.getValue("yem_isnewagent");
        String isGiftGive = (String) model.getValue("yem_isgiftgive");
        if ("A".equals(isGiftGive)) {
            model.deleteEntryData("yem_es_salesorder_l");
            Map<Long, BigDecimal> map = new HashMap<>();
            int materialInfoRows = model.getEntryRowCount("yem_es_materialinfo");
            for (int i = 0; i < materialInfoRows; i++) {
                DynamicObject productModel = (DynamicObject) model.getValue("yem_productmodel", i);
                if (YEM.isNotEmpty(productModel)) {
                    DynamicObject products = productModel.getDynamicObject("yem_products");
                    if (YEM.isNotEmpty(products)) {
                        Long productsId = products.getLong("id");
                        BigDecimal qty = (BigDecimal) model.getValue("yem_qty", i);
                        if (map.containsKey(productsId)) {
                            qty = map.get(productsId).add(qty);
                        }
                        map.put(productsId, qty);
                    }
                }
            }
            BigDecimal exrate = (BigDecimal) model.getValue("yem_giftdecimal");
            Set<Long> productModelIds = map.keySet();
            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.in, productModelIds.toArray(new Long[productModelIds.size()])),
                            new QFilter("yem_ynnewdealer", QCP.equals, isNewAgent)});
            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 (map.containsKey(id)) {
                            int entryRow = model.createNewEntryRow("yem_es_salesorder_l");
                            BigDecimal tsagerQty = map.get(id);
                            BigDecimal giveAmoBase = giftRules_a.getBigDecimal("yem_giveamo");
                            BigDecimal giveAmo = null;
                            if (exrate.compareTo(BigDecimal.ZERO) != 0) {
                                giveAmo = giveAmoBase.divide(exrate, RoundingMode.HALF_DOWN);
                            }

                            model.setValue("yem_giftproactype", productType, 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);//礼品金额本位币
                        }
                    }
                }
            }
        }
    }

    /**
     * @description 是否礼品赠送  否时 清空礼品赠送分录
     * @author xwudd
     * return
     * @time 2023/8/9 9:57
     */
    private void isGiftGive() {
        IDataModel model = this.getModel();
        String isGiftGive = (String) model.getValue("yem_isgiftgive");
        if ("B".equals(isGiftGive)) {
            model.deleteEntryData("yem_es_salesorder_l");
        }
    }

    /**
     * @description 赋值海运保险费率
     * @author xwudd
     * return
     * @time 2023/8/9 14:17
     */

    private void setInsuranceFeeRate() {
        IDataModel model = this.getModel();
        BigDecimal insuranceFeeRate = BigDecimal.ZERO;
        DynamicObject clientCountry = (DynamicObject) model.getValue("yem_clientcountry");
        DynamicObject transportStyle = (DynamicObject) model.getValue("yem_transportstyle");
        if (YEM.isNotEmpty(transportStyle)) {
            if (YEM.isNotEmpty(clientCountry)) {
                QFilter qFilter = new QFilter("yem_rateinfo.yem_country", QCP.equals, clientCountry.getPkValue());
                qFilter.and(new QFilter("yem_rateinfo.yem_transway", QCP.equals, transportStyle.getPkValue()));
                DynamicObject[] insuranceFeeRateObjs = BusinessDataServiceHelper.load("yem_bd_rate", "id,yem_rateinfo.yem_country,yem_rateinfo.yem_transway,yem_rateinfo.yem_rate",
                        qFilter.toArray());
                if (insuranceFeeRateObjs.length > 0) {
                    for (DynamicObject insuranceFeeRateObj : insuranceFeeRateObjs) {
                        DynamicObjectCollection rateInfos = insuranceFeeRateObj.getDynamicObjectCollection("yem_rateinfo");
                        for (DynamicObject rateInfo : rateInfos) {
                            DynamicObject country = rateInfo.getDynamicObject("yem_country");
                            DynamicObject transWay = rateInfo.getDynamicObject("yem_transway");
                            if (YEM.isNotEmpty(country) && YEM.isNotEmpty(transWay)) {
                                if (clientCountry.getLong("id") == country.getLong("id")
                                        && transportStyle.getLong("id") == transWay.getLong("id")) {
                                    insuranceFeeRate = rateInfo.getBigDecimal("yem_rate");
                                }
                            }
                        }
                    }
                } else {
                    qFilter = new QFilter("yem_rateinfo.yem_transway", QCP.equals, transportStyle.getPkValue());
                    insuranceFeeRateObjs = BusinessDataServiceHelper.load("yem_bd_rate", "id,yem_rateinfo.yem_country,yem_rateinfo.yem_transway,yem_rateinfo.yem_rate",
                            qFilter.toArray());
                    for (DynamicObject insuranceFeeRateObj : insuranceFeeRateObjs) {
                        DynamicObjectCollection rateInfos = insuranceFeeRateObj.getDynamicObjectCollection("yem_rateinfo");
                        for (DynamicObject rateInfo : rateInfos) {
                            DynamicObject country = rateInfo.getDynamicObject("yem_country");
                            DynamicObject transWay = rateInfo.getDynamicObject("yem_transway");
                            if (YEM.isEmpty(country) && YEM.isNotEmpty(transWay)) {
                                if (transportStyle.getLong("id") == transWay.getLong("id")) {
                                    insuranceFeeRate = rateInfo.getBigDecimal("yem_rate");
                                }
                            }
                        }
                    }
                }
            } else {
                QFilter qFilter = new QFilter("yem_rateinfo.yem_transway", QCP.equals, transportStyle.getPkValue());
                DynamicObject[] insuranceFeeRateObjs = BusinessDataServiceHelper.load("yem_bd_rate", "id,yem_rateinfo.yem_country,yem_rateinfo.yem_transway,yem_rateinfo.yem_rate",
                        qFilter.toArray());
                for (DynamicObject insuranceFeeRateObj : insuranceFeeRateObjs) {
                    DynamicObjectCollection rateInfos = insuranceFeeRateObj.getDynamicObjectCollection("yem_rateinfo");
                    for (DynamicObject rateInfo : rateInfos) {
                        DynamicObject country = rateInfo.getDynamicObject("yem_country");
                        DynamicObject transWay = rateInfo.getDynamicObject("yem_transway");
                        if (YEM.isEmpty(country) && YEM.isNotEmpty(transWay)) {
                            if (transportStyle.getLong("id") == transWay.getLong("id")) {
                                insuranceFeeRate = rateInfo.getBigDecimal("yem_rate");
                            }
                        }
                    }
                }
            }

        }
        model.setValue("yem_insurancefeerate", insuranceFeeRate);
    }


    /**
     * @description 同步跟单任务控制台 整机生产信息
     * @author xwudd
     * return
     * @time 2023/9/6 16:43
     */

    public void renewTrackTask() {
        IDataModel model = this.getModel();
        int currentRowIndex = model.getEntryCurrentRowIndex("yem_es_materialinfo");
        DynamicObjectCollection materialInfos = model.getEntryEntity("yem_es_materialinfo");
        DynamicObject materialInfo = materialInfos.get(currentRowIndex);
        DynamicObjectCollection saleMachineInfos = materialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
        Map<Long, DynamicObject> saleMachineInfosMap = saleMachineInfos.stream().collect(Collectors.toMap(x -> x.getLong("yem_tracktaskmachinid"), y -> y));
        long id = materialInfo.getLong("id");
        String selectfields = DynamicObjectUtil.getSelectfields("yem_tracktaskconsole", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_tracktaskconsole", "yem_es_materialinfo", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_tracktaskconsole", "yem_es_salesorder_r", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_tracktaskconsole", "yem_es_salesorder_r", "yem_es_salesorder_z", false);
        DynamicObject[] trackTaskConsoles = BusinessDataServiceHelper.load("yem_tracktaskconsole", selectfields,
                new QFilter[]{new QFilter("yem_es_materialinfo.yem_sourceentryid", QCP.equals, id)});
        for (DynamicObject trackTaskConsole : trackTaskConsoles) {//
            DynamicObjectCollection trackMaterialInfos = trackTaskConsole.getDynamicObjectCollection("yem_es_materialinfo");
            DynamicObjectCollection prepareFeeds = trackTaskConsole.getDynamicObjectCollection("yem_es_salesorder_r");
            for (DynamicObject trackMaterialInfo : trackMaterialInfos) {//跟单任务控制台 明细信息
                long sourceEntryId = trackMaterialInfo.getLong("yem_sourceentryid");
                if (id == sourceEntryId) {
                    long trackMaterialInfoId = trackMaterialInfo.getLong("id");
                    for (DynamicObject prepareFeed : prepareFeeds) {//跟单任务控制台 备料信息
                        long entryId = prepareFeed.getLong("yem_entrtyid");
                        if (trackMaterialInfoId == entryId) {
                            DynamicObjectCollection machineInfos = prepareFeed.getDynamicObjectCollection("yem_es_salesorder_z");
                            for (DynamicObject machineInfo : machineInfos) {//跟单任务控制台 整机生产信息
                                long machineInfoId = machineInfo.getLong("id");
                                DynamicObject saleMachineInfo = saleMachineInfosMap.get(machineInfoId);
                                machineInfo.set("yem_resourcescode", saleMachineInfo.get("yem_resourcescode"));//资源号
                                machineInfo.set("yem_milltype", saleMachineInfo.get("yem_milltype"));//机型
                                machineInfo.set("yem_yieldway", saleMachineInfo.get("yem_yieldway"));//物料属性
                                machineInfo.set("yem_prepareway", saleMachineInfo.get("yem_prepareway"));//备料方式
                                machineInfo.set("yem_vehicleno", saleMachineInfo.get("yem_vehicleno"));//整机编号
                                machineInfo.set("yem_engineno", saleMachineInfo.get("yem_engineno"));//发动机号
                                machineInfo.set("yem_enginemodel", saleMachineInfo.get("yem_enginemodel"));//发动机型号
                                machineInfo.set("yem_enginevendor", saleMachineInfo.get("yem_enginevendor"));//发动机厂商
                                machineInfo.set("yem_currentstate", saleMachineInfo.get("yem_currentstate"));//当前状态
                                machineInfo.set("yem_currentstatedate", saleMachineInfo.get("yem_currentstatedate"));//当前状态时间
                                machineInfo.set("yem_assembleupline", saleMachineInfo.get("yem_assembleupline"));//总装上线
                                machineInfo.set("yem_upline", saleMachineInfo.get("yem_upline"));//上线时间
                                machineInfo.set("yem_assembledownline", saleMachineInfo.get("yem_assembledownline"));//总装下线
                                machineInfo.set("yem_downline", saleMachineInfo.get("yem_downline"));//下线时间
                                machineInfo.set("yem_debugst", saleMachineInfo.get("yem_debugst"));//调试
                                machineInfo.set("yem_debugstatdate", saleMachineInfo.get("yem_debugstatdate"));//调试完成时间
                                machineInfo.set("yem_waitforinspection", saleMachineInfo.get("yem_waitforinspection"));//待检
                                machineInfo.set("yem_waitforinspecdate", saleMachineInfo.get("yem_waitforinspecdate"));//待检时间
                                machineInfo.set("yem_accuracytest", saleMachineInfo.get("yem_accuracytest"));//精试
                                machineInfo.set("yem_accuratdate", saleMachineInfo.get("yem_accuratdate"));//精试完成时间
                                machineInfo.set("yem_qualitytest", saleMachineInfo.get("yem_qualitytest"));//质检
                                machineInfo.set("yem_qualitytestdate", saleMachineInfo.get("yem_qualitytestdate"));//质检合格时间
                                machineInfo.set("yem_factputstor", saleMachineInfo.get("yem_factputstor"));//入库
                                machineInfo.set("yem_factputstordate", saleMachineInfo.get("yem_factputstordate"));//实际入库时间
                                machineInfo.set("yem_backonline", saleMachineInfo.get("yem_backonline"));//返工上线
                                machineInfo.set("yem_backonlinedate", saleMachineInfo.get("yem_backonlinedate"));//返工上线时间
                                machineInfo.set("yem_putintostorage", saleMachineInfo.get("yem_putintostorage"));//改制入库
                                machineInfo.set("yem_putintostoragedate", saleMachineInfo.get("yem_putintostoragedate"));//改制入库时间
                                machineInfo.set("yem_vehicleremark", saleMachineInfo.get("yem_vehicleremark"));//备注
                                machineInfo.set("yem_ifdelivered", saleMachineInfo.get("yem_ifdelivered"));//备注
                            }
                        }
                    }
                }
            }
        }
        SaveServiceHelper.save(trackTaskConsoles);
    }
}