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

import com.yem.tws.common1.BigDecimalUtils;
import com.yem.wm.es.Util.PJUtils;
import com.yem.wm.es.Util.TotalUtil;
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.entity.operate.result.OperationResult;
import kd.bos.form.*;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.SplitContainer;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.ComboEdit;
import kd.bos.form.field.FieldEdit;
import kd.bos.form.field.RefBillEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

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

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

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

    @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 afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IDataModel model = this.getModel();
        Object salesmethod = model.getValue("yem_salesmethod");
        if (YEM.isEmpty(salesmethod)) {

            DynamicObject single = BusinessDataServiceHelper.loadSingle("yem_bd_salesmethod", new QFilter[]{new QFilter("number", QCP.equals, "XSFS-003")});
            model.setValue("yem_salesmethod", single.getPkValue());
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        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_pj".equals(formId)) {
                qFilter = new QFilter("number", QCP.equals, "yem_es_salesorder_PJ");
            }
            if ("yem_es_salesorder_nmpj".equals(formId)) {
                qFilter = new QFilter("number", QCP.equals, "yem_es_salesorder_nmpj");
            }
            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"));//配件币别默认赋值结算币别

        }
        FieldEdit billbusstype = this.getControl("yem_billbusstype");
        billbusstype.setMustInput(true);
//        setRandomDataTools();
        countGiftRate();
        countGiveRate();
    }

    @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);
        RefBillEdit useDebcredNoteNo = this.getControl("yem_usedebcrednoteno");
        useDebcredNoteNo.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) {
        String name = e.getProperty().getName();
        int row = e.getRow();
        if ("yem_billaskfor".equals(name)) {
            billAskForF7Select(e);
        }
        if ("yem_materialclass".equals(name)) {
            materialClassF7Select(e);
        }
        if ("yem_materiel".equals(name)) {
            materialF7Select(e);//
        }
        if ("yem_productmodel".equals(name)) {
            selectF7ProductModel(e);//
        }
        if ("yem_resourcenog".equals(name)) {
            selectF7SourceNo(e, row);//
        }
//        if("yem_countexpense".equals(name)){
//            selectF7countExpense(e);//
//        }
        if ("yem_agreementew".equals(name)) {
            selectF7AgreementEw(e);//
        }
        //end by zhouc 2024-03-22 禁用
//        if ("yem_usedebcrednoteno".equals(name)) {
//            selectF7Debc(e);//
//        }

    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        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);//物料为空时  计量单位  基本计量单位 为台
                DynamicObject dataEntity = model.getDataEntity();
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
                DynamicObject materiel = collection.get(rowIndex).getDynamicObject("yem_materiel");
                if (materiel == null) {
                    QFilter qFilter = new QFilter("number", QCP.equals, "pcs");
                    DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_measureunits", qFilter.toArray());
                    if (dynamicObject != null) {
                        model.setValue("yem_unit", dynamicObject, rowIndex);//个
                        model.setValue("yem_baseunit", dynamicObject, rowIndex);
                    }
                    model.setValue("yem_customclass", null, rowIndex);
                }
                break;
            case "yem_resourcenog":
                setMaterialSource(rowIndex);
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_businesssort":
                countOrderSumNumber();
                setRandomDataTools();//
                FunctionalCommon.lock(view, model, rowIndex);
                break;
            case "yem_productmodel":
                setRandomDataTools();//
                FunctionalCommon.multiConfig(model, rowIndex);
                setGiftGiving();
                break;

            case "yem_reccondition":
                setSalesContrac();//选择收款条件时带出收款计划分录
                TotalUtil.countRapAmt(model, "yem_es_salescontrac_s");
                TotalUtil.countRapRate(model, "yem_es_salescontrac_s");
                break;
            case "yem_marketraiseprice":
                calculateFobPrice();//计算fob单据(张立攀)
                break;
            case "yem_ticketprice":
            case "yem_bigcabinetprice":
            case "yem_mincabinetprice":
            case "yem_bigcabinetnumber":
            case "yem_mincabinetnumber":
            case "yem_singlenumber":
                PJUtils.countCostSumAmountPJ(model);//
                break;
            case "yem_unitsetnumber":
                fobPriceAdd();
                break;
            case "yem_giftcurrency":
                countGiftRate();
                break;
            case "yem_givecurrency":
                countGiveRate();
                break;
            case "yem_issinosurecon":
                setMustIsSinosure();
                setSinosureRate();
                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");
                break;
            case "yem_rapamt":
                TotalUtil.countRapRate(model, "yem_es_salescontrac_s");
                break;
            case "yem_isgiftgive":
                isGiftGive();
                break;
            case "yem_exrate":
            case "yem_exwrmbprice":
                PJUtils.countCostSumAmountPJ(model);//
                countCalculationAmt();
                ClientUtils.changeRatePJ(model, "yem_es_materialinfo");
                break;
            case "yem_qty":
                setRandomDataTools();
                countOrderSumNumber();
                setGiftGiving();
                ClientUtils.countFobAmt(model, rowIndex);//fob金额
                ClientUtils.addSaPriceSale(model, rowIndex);//销售fob金额
                ClientUtils.countFrontDisAmt(model, rowIndex);//折扣前金额
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                ClientUtils.countAfterFrontPrice(model, rowIndex);//折扣后销售单价
                calculateCostSharing(model);
                break;
            case "yem_fobprice":
                ClientUtils.countFobAmt(model, rowIndex);//fob金额
                ClientUtils.countPjSaFobPrice(model, rowIndex);//计算销售fob单价
                break;
            case "yem_safobprice"://销售fob单价 结算币别
                ClientUtils.addSaPriceRMB(model, rowIndex);//计算销售fob单价 人民币
                ClientUtils.addSaPriceSale(model, rowIndex);//销售fob金额
                ClientUtils.countFrontDisPrice(model, rowIndex);//折扣前单价
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_safobamount"://销售fob金额
                ClientUtils.addSaPriceSaleRMB(model, rowIndex);//销售fob金额 人民币
                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_safobamount", "yem_amount");//销售fob金额 汇总表头 fob金额
                ClientUtils.countDisAmt(model, "yem_es_materialinfo", rowIndex, view);//计算折扣金额
                ClientUtils.countAfterFrontAmt(model, rowIndex);//计算折扣后销售金额
                break;
            case "yem_onecarsum"://单车总费用
                ClientUtils.countFrontDisPrice(model, rowIndex);//折扣前单价
//                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_onecarsum", "yem_sumcost");//单车总费用 汇总表头 总费用
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_saamtpriceclause"://销售金额（价格条款）
                ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_saamtpriceclause", "yem_offeramount");//销售金额（价格条款）汇总表头 金额价格条款
//                calculateCostSharing(model);
//                ClientUtils.countSaPricePriceClause(model, rowIndex); // 计算销售单价（价格条款）
                break;
            case "yem_sapricepriceclause"://销售单价（价格条款）

                break;
            case "yem_sapriceclausebase"://销售单价（价格条款）本位币
                break;
            case "yem_disamt"://折扣金额
                ClientUtils.countFrontDisAmt(model, rowIndex);//折扣前金额
                ClientUtils.countAfterFrontAmt(model, rowIndex);//计算折扣后销售金额
                ClientUtils.countPoolAmt(view, model, "yem_es_materialinfo");//汇总折扣金额使用金额
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_fundusetype"://资金使用类型
                model.setValue("yem_fundpoolamt", BigDecimal.ZERO);
                break;
            case "yem_frontdisprice"://折扣前销售单价
                ClientUtils.countFrontDisAmt(model, rowIndex);//折扣前金额
                break;
            case "yem_lenghtunit"://长度单位
            case "yem_vol"://体积
                TotalUtil.countVolM3(model, rowIndex, "yem_lenghtunit", "yem_vol", "yem_volm3");
                ;
                break;
                //end by zhouc 2024-03-22
//            case "yem_usedebcrednoteno"://体积
//                useDebcChange(rowIndex);
//                break;
            case "yem_ifgift":
                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");//单车总费用 汇总表头 总费用
                ClientUtils.clearRelevantPrice(model, view, rowIndex, "yem_es_materialinfo");
                break;
            case "yem_transportstyle":
//                setInsuranceFeeRate();
                break;
            case "yem_pricefieldaccba"://资源配置单价
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_afterfrontdisprice"://折扣后销售单价
                break;
            case "yem_accamtusetype"://配件资金使用方式
                ClientUtils.delValue(model, "yem_es_materialinfo");
//                ClientUtils.countDisAmt(model,"yem_es_materialinfo",rowIndex);//计算折扣金额
                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_exwrmbprice":
//                ClientUtils.exwRMBPriceChange(model, rowIndex);
//                break;
            case "yem_totalamount": // 总费用(分录)
//                calculateCostSharing(model);
                ClientUtils.addSaAmountTk(model, rowIndex);//销售金额（价格条款）结算币别
                break;
            case "yem_sumedamount":
                calculateCostSharing(model);
                break;
        }
    }

    private void calculateCostSharing(IDataModel model) {
//        ClientUtils.totalSaFobAmount(model, "yem_es_materialinfo", "yem_ifgift", "yem_safobamount", "yem_amount");//销售fob金额 汇总表头 fob金额
        int rowCount = model.getEntryRowCount("yem_es_materialinfo");
        BigDecimal amount = (BigDecimal) model.getValue("yem_amount");
        BigDecimal sumedamount = (BigDecimal) model.getValue("yem_sumedamount");
        BigDecimal excludeLastRow = BigDecimal.ZERO;
        List<Integer> seq = new ArrayList<>();
        for (int index = 0; index < rowCount; index++) {
            boolean ifgift = (boolean) model.getValue("yem_ifgift", index);
            if (!ifgift) {
                seq.add(index);
            } else {
                model.setValue("yem_totalamount", BigDecimal.ZERO, index);
            }

        }
        for (Integer i : seq) {
            BigDecimal safobamount = (BigDecimal) model.getValue("yem_safobamount", i);
            BigDecimal calc = BigDecimalUtils.div(safobamount, amount, 12).multiply(sumedamount).setScale(2, RoundingMode.HALF_UP);
            if (i == seq.size() - 1) {
                model.setValue("yem_totalamount", sumedamount.subtract(excludeLastRow), i);
            } else {
                model.setValue("yem_totalamount", calc, i);
                excludeLastRow = excludeLastRow.add(calc);
            }
        }
    }

    /**
     * @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 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 商品明细分录FOB单价（EXW单价）=SUM（标准销售加价*单台数量）+父单据体的标配FOB（青岛）价
     */
    private void calculateFobPrice() {
        int rowNow = 0;
        DynamicObject dyEntry = this.getModel().getDataEntity(true);
        DynamicObjectCollection dy = dyEntry.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject temp : dy) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            DynamicObjectCollection dc = temp.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal marketraiseprice = di.getBigDecimal("yem_marketraiseprice");
                BigDecimal unitsetnumber = di.getBigDecimal("yem_unitsetnumber");
                fobPrice = fobPrice.add(marketraiseprice.multiply(unitsetnumber));
            }
            BigDecimal standardprice = temp.getBigDecimal("yem_standardprice");
            this.getModel().setValue("yem_fobprice", fobPrice.add(standardprice), rowNow);
            rowNow++;
        }
    }


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

    }


    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        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();
        int[] rowIndexs = e.getRowIndexs();
        for (int rowIndex : rowIndexs) {
            if ("yem_multiconfig".equals(name)) {
                fobPriceAdd();
            }
        }
        if ("yem_es_materialinfo".equals(name)) {
            setGiftGiving();
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        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.resetValuePJ(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");
                if (!yem_changing) {
//                    FunctionalCommon.clientDemandStartPj(this, "yem_es_materialinfo", "yem_es_salescontrac_s");
                    int rowCount = model.getEntryRowCount("yem_es_materialinfo");
                    if (rowCount > 0) {
                        IABudgetCommon.pushToGeneration(dataEntity, new int[]{0}, "yem_es_materialinfo");
                        view.invokeOperation("refresh");
                    }
                } else {
                    view.showTipNotification("当前合同存在未审核的变更单，禁止生成《内审预算单》");
                }
                break;
            case "unsubmit":
            case "submit":
                if (operationResult.isSuccess()) {
                    view.invokeOperation("refresh");
                }
                break;
            default:
                break;
        }
    }


    /**
     * 多功能配置页签  单台数量计算fob单价
     */
    private void fobPriceAdd() {
        DynamicObject dyEntry = this.getModel().getDataEntity(true);
        DynamicObjectCollection dy = dyEntry.getDynamicObjectCollection("yem_es_materialinfo");
        int rowNow = 0;
        for (DynamicObject temp : dy) {
            BigDecimal fobPrice = BigDecimal.ZERO;
            DynamicObjectCollection dc = temp.getDynamicObjectCollection("yem_multiconfig");
            for (DynamicObject di : dc) {
                BigDecimal marketraiseprice = di.getBigDecimal("yem_marketraiseprice");
                BigDecimal unitsetnumber = di.getBigDecimal("yem_unitsetnumber");
                fobPrice = fobPrice.add(marketraiseprice.multiply(unitsetnumber));
            }
            BigDecimal standardprice = temp.getBigDecimal("yem_standardprice");
            this.getModel().setValue("yem_fobprice", fobPrice.add(standardprice), rowNow);
            rowNow++;
        }
    }


    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");
            if ("yem_es_salesorder_ZJ".equals(number) || "yem_es_salesorder_nmzj".equals(number)) {
                model.setValue("yem_businesssort", "Z", rowIndex);
                QFilter qFilter = new QFilter("number", QCP.equals, "UM-101");
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_measureunits", qFilter.toArray());
                if (dynamicObject != null) {
                    model.setValue("yem_unit", dynamicObject, rowIndex);//台
                    model.setValue("yem_baseunit", dynamicObject, rowIndex);
                }
            }
            if ("yem_es_salesorder_PJ".equals(number) || "yem_es_salesorder_nmpj".equals(number)) {
                model.setValue("yem_businesssort", "P", rowIndex);
                QFilter qFilter = new QFilter("number", QCP.equals, "pcs");
                DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle("bd_measureunits", qFilter.toArray());
                if (dynamicObject != null) {
                    model.setValue("yem_unit", dynamicObject, rowIndex);//个
                    model.setValue("yem_baseunit", dynamicObject, 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 products = (DynamicObject) model.getValue("yem_bd_products");
        DynamicObject materialClass = (DynamicObject) model.getValue("yem_materialclass", row);
        if (products == null) {
            this.getView().showMessage("请选择产品分类");
            e.setCancel(true);
        }
        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) {
            e.addCustomQFilter(new QFilter("number", QCP.equals, "PJ"));
        }
    }

    /**
     * @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 单据类型为整机 物料带出资源号
//     * @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);
//            }
//        }
//    }

    /**
     * @param rowIndex
     * @Description 单据类型为整机 资源号带出物料
     */
    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);
                    model.setValue("yem_materialentryid", id, 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);
//                }
                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);
            }
        }
        int[] rows = new int[seqs.size()];
        for (int i = 0; i < seqs.size(); i++) {
            rows[i] = seqs.get(i);
        }
        model.deleteEntryRows("yem_es_salesorder_p", rows);
//        }
    }

    /**
     * @description 选择收款计划时带出收款计划分录
     * @author xwudd
     * @time 2023/7/25 9:24
     */

    public void setSalesContrac() {
        IDataModel model = this.getModel();
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        model.deleteEntryData("yem_es_salescontrac_s");
        if (recCondition != null) {
            String basis = recCondition.getString("basis");
            DynamicObjectCollection entrys = recCondition.getDynamicObjectCollection("entry");
            for (DynamicObject entry : entrys) {
                int entryRow = model.createNewEntryRow("yem_es_salescontrac_s");
                model.setValue("yem_ispre", entry.getBoolean("ispre"), entryRow);
                model.setValue("yem_payment", recCondition, entryRow);
                model.setValue("yem_isprepayment", entry.getString("yem_isprepayment"), entryRow);
                model.setValue("yem_isshippayment", entry.getString("yem_isshippayment"), entryRow);
                if ("A".equals(basis)) {
                    model.setValue("yem_raprate", entry.getBigDecimal("rate"), entryRow);
                }
                if ("B".equals(basis)) {
                    model.setValue("yem_rapamt", entry.getBigDecimal("amount"), entryRow);
                }
            }
        }
    }

    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.showErrorNotification("请先维护基本信息-产品分类字段!");
            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 ("P".equals(businessSort)) {
                    total = total.add((BigDecimal) model.getValue("yem_qty", i));
                }
            }

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


    /**
     * @description 资源号带出物料
     * @author xwudd
     * return
     * @time 2023/7/29 17:42
     */

    public void setMaterialSource(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject resourceNog = (DynamicObject) model.getValue("yem_resourcenog", rowIndex);
        if (resourceNog != null) {
            String number = resourceNog.getString("number");
            DynamicObject material = BusinessDataServiceHelper.loadSingle("bd_material", "id",
                    new QFilter[]{new QFilter("number", QCP.equals, number)});
            model.setValue("yem_materiel", material, rowIndex);
        } else {
            model.setValue("yem_materiel", null, rowIndex);
        }
    }


    @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");
    }

    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);
        model.setValue("yem_givedecimal", exchangeRate);
    }

    /**
     * @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)) {
            String number = billType.getString("number");
            if ("yem_es_salesorder_PJ".equals(number)) {
                e.addCustomQFilter(new QFilter("yem_accountingtype", QCP.equals, "P"));
            }
            if ("yem_es_salesorder_ZJ".equals(number)) {
                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 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_exrate");
            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()]))});
            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 = 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
     * @param[1] rowIndex
     * return
     * @time 2023/8/31 18:52
     */

    public void useDebcChange(int rowIndex) {
        IDataModel model = this.getModel();
        DynamicObject useDebcrednoteObj = (DynamicObject) model.getValue("yem_usedebcrednoteno", rowIndex);
        if (YEM.isNotEmpty(useDebcrednoteObj)) {
            String billNo = useDebcrednoteObj.getString("billno");
            String selectfields = DynamicObjectUtil.getSelectfields("yem_spcapitalpool", false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_spcapitalpool", "yem_spcapitalpool_o", false);
            DynamicObject spcapitalPool = BusinessDataServiceHelper.loadSingle("yem_spcapitalpool", selectfields,
                    new QFilter[]{new QFilter("yem_spcapitalpool_o.yem_originno", QCP.equals, billNo)});
            if (YEM.isNotEmpty(spcapitalPool)) {
                DynamicObjectCollection spcapitalPool_os = spcapitalPool.getDynamicObjectCollection("yem_spcapitalpool_o");
                for (DynamicObject spcapitalPool_o : spcapitalPool_os) {
                    String originNo = spcapitalPool_o.getString("yem_originno");
                    if (billNo.equals(originNo)) {
                        model.setValue("yem_debcredtype", spcapitalPool_o.get("yem_origintype"), rowIndex);//贷记单类型
                        model.setValue("yem_debcrednotecurr", spcapitalPool_o.get("yem_origincurr"), rowIndex);//贷记单币别
                        model.setValue("yem_debcoriginalamt", spcapitalPool_o.get("yem_originamt"), rowIndex);//贷记单原始金额
                        model.setValue("yem_debcleaveamt", spcapitalPool_o.get("yem_residueavaamt"), rowIndex);//贷记单剩余金额
                    }
                }
            }
        } else {
            model.setValue("yem_debcredtype", null, rowIndex);//贷记单类型
            model.setValue("yem_debcrednotecurr", null, rowIndex);//贷记单币别
            model.setValue("yem_debcoriginalamt", null, rowIndex);//贷记单原始金额
            model.setValue("yem_debcleaveamt", null, rowIndex);//贷记单剩余金额
        }
    }


    /**
     * @description 过滤使用贷记单号  配件资金池中-配件资金来源-剩余额度大于0的行对应的来源单号
     * @author xwudd
     * @param[1] e
     * return
     * @time 2023/8/31 18:52
     */

    public void selectF7Debc(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        List<Long> ids = new ArrayList();
        String selectfields = DynamicObjectUtil.getSelectfields("yem_spcapitalpool", false);
        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_spcapitalpool", "yem_spcapitalpool_o", false);
        DynamicObject[] spcapitalPools = BusinessDataServiceHelper.load("yem_spcapitalpool", selectfields,
                new QFilter[]{new QFilter("yem_spcapitalpool_o.yem_residueavaamt", QCP.large_than, 0)});
        for (DynamicObject spcapitalPool : spcapitalPools) {
            DynamicObjectCollection spcapitalPool_os = spcapitalPool.getDynamicObjectCollection("yem_spcapitalpool_o");
            for (DynamicObject spcapitalPool_o : spcapitalPool_os) {
                BigDecimal residueAvaAmt = spcapitalPool_o.getBigDecimal("yem_residueavaamt");
                if (residueAvaAmt.compareTo(BigDecimal.ZERO) > 0) {
                    ids.add(spcapitalPool_o.getLong("yem_sourcebillid_o"));
                }
            }
        }
        e.addCustomQFilter(new QFilter("id", QCP.in, ids));
        DynamicObject customer = (DynamicObject) model.getValue("yem_customer");
        if (YEM.isNotEmpty(customer)) {
            e.addCustomQFilter(new QFilter("yem_customer", QCP.in, customer.getPkValue()));
        } else {
            e.addCustomQFilter(new QFilter("yem_customer", QCP.in, 0L));
        }

    }

}