package com.yem.wm.im.clientdemand.form;

import com.yem.wm.es.Util.TotalUtil;
import com.yem.wm.im.clientdemand.utils.ClientUtils;
import com.yem.wm.im.clientdemand.utils.ValueSave;
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.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.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.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.List;

import static com.yem.wm.es.salesorder.from.SalesOrderZJEdit.bringAssemblyAmount;

/**
 * @author 张立攀
 * @version 1.0
 * @description 内贸客户需求单整机
 * @date 2023-09-14 17:23
 */
public class InClientDemandZJFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener, HyperLinkClickListener
{

    private ValueSave valueSave = new ValueSave();

    @Override
    public void registerListener(EventObject e)
    {
        BasedataEdit products = this.getView().getControl("yem_bd_products");
        if (products != null) {
            products.addBeforeF7SelectListener(this);
        }
        BasedataEdit materialclass = this.getView().getControl("yem_materielclass");
        if (materialclass != null) {
            materialclass.addBeforeF7SelectListener(this);
        }
        BasedataEdit resourceid = this.getView().getControl("yem_resourcenog");
        if (resourceid != null) {
            resourceid.addBeforeF7SelectListener(this);
        }
        BasedataEdit productmodel = this.getView().getControl("yem_productmodel");
        if (productmodel != null) {
            productmodel.addBeforeF7SelectListener(this);
        }
//        BasedataEdit countexpense = this.getView().getControl("yem_countexpense");
//        if(countexpense != null){
//            countexpense.addBeforeF7SelectListener(this);
//        }
        EntryGrid detailedInfor = this.getControl("yem_im_detailedinfor");
        detailedInfor.addHyperClickListener(this);
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e)
    {
        RowDataEntity[] rowDataEntities = e.getRowDataEntities();
        String entryName = e.getEntryProp().getName();
        //新增 明细信息分录行时 给字段赋默认值
        for (RowDataEntity re : rowDataEntities) {
            ClientUtils.setValueByAddRow(entryName, re, this.getModel(), valueSave);
        }
    }


    @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 afterDeleteRow(AfterDeleteRowEventArgs e)
    {
        String name = e.getEntryProp().getName();
        DynamicObject datas = this.getModel().getDataEntity(true);
        DynamicObject dyEntry = this.getModel().getDataEntity(true);
        DynamicObjectCollection dy = dyEntry.getDynamicObjectCollection("yem_im_detailedinfor");
        if ("yem_im_detailedinfor".equals(name)) {
            ClientUtils.addPjSourceAccount(this.getModel(), dy);
        }
        if ("yem_multiconfig".equals(name)) {
            ClientUtils.deleteRowFobPriceAddkh(this.getModel());
            ClientUtils.addSaPrice(this.getModel(), dy);
        }

    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e)
    {
        int[] rows = e.getRowIndexs();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getEntryProp().getName();
        DynamicObject datas = this.getModel().getDataEntity(true);
        int index = this.getModel().getEntryCurrentRowIndex("yem_im_detailedinfor");
        for (int row : rows) {
            //删除行 更新需求数量
            if ("yem_im_detailedinfor".equals(name)) {
                BigDecimal quantityrequired = (BigDecimal) this.getModel().getValue("yem_qty", row);
                int ordersumnumber = datas.getInt("yem_ordersumnumber");
                int temp = 0;
                if (quantityrequired != null) {
                    temp = quantityrequired.intValue();
                }
                this.getModel().setValue("yem_ordersumnumber", ordersumnumber - temp);
                //多功能配置页签删除行 更新FOB单价
            } else if ("yem_multiconfig".equals(name)) {
                BigDecimal unitsetamountbase = (BigDecimal) this.getModel().getValue("yem_unitsetamountbase", row);
                BigDecimal fobprice = (BigDecimal) this.getModel().getValue("yem_fobprice", index);
                this.getModel().setValue("yem_fobprice", fobprice.subtract(unitsetamountbase), index);
            }
        }

    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e)
    {
        IDataModel model = this.getModel();
        DynamicObject datas = model.getDataEntity(true);
        DynamicObjectCollection dy = datas.getDynamicObjectCollection("yem_im_detailedinfor");
        int index = model.getEntryCurrentRowIndex("yem_im_detailedinfor");
        int indexMg = model.getEntryCurrentRowIndex("yem_multiconfig");
        //跳转资源申请单
        IFormView view = this.getView();
        if ("openpage".equals(e.getOperateKey())) {
            BillShowParameter billShowParameter = new BillShowParameter();

            billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);

            billShowParameter.setFormId("yem_sourceapply");

            view.showForm(billShowParameter);

        }
        if ("newentry3".equals(e.getOperateKey())) {
            if ("整机客户需求单".equals(datas.getString("yem_billtype.name"))) {
                if (dy == null || dy.size() == 0) {
                    return;
                }
                DynamicObject nowEntry = dy.get(index);
                long resourceid = 0L;
                if (nowEntry != null) {
                    resourceid = nowEntry.getLong("yem_resourcenog.id");
                }
                if (resourceid == 0L) {
                    view.showMessage("需要先维护明细信息中的【资源号】！");
                    return;
                }
                model.createNewEntryRow("yem_retrofitting");
                model.setValue("yem_resourceid1", resourceid, nowEntry.getDynamicObjectCollection("yem_retrofitting").size() - 1);
            } else {
                model.createNewEntryRow("yem_retrofitting");
            }

        }
        //获取标准价
        if ("getprice".equals(e.getOperateKey())) {
            ClientUtils.getPriceNew(datas, model, view);
            int rowCount = model.getEntryRowCount("yem_im_detailedinfor");
            for (int i = 0; i < rowCount; i++) {
                ClientUtils.addSaAmountTk(model, i);
            }
        }
        //回填资源号
        if ("backfillingsource".equals(e.getOperateKey())) {
            backFillSource();
        }
        //可选装、可替换等方法
        if ("optionaloperation".equals(e.getOperateKey())) {
            FunctionalCommon.optionalOperation(model, view, "yem_optional", "optionaloperation");
        }
        if ("replaceoperation".equals(e.getOperateKey())) {
            FunctionalCommon.optionalOperation(model, view, "yem_replace", "replaceoperation");
        }
        if ("retrofittingoperation".equals(e.getOperateKey())) {
            FunctionalCommon.optionalOperation(model, view, "yem_retrofitting", "retrofittingoperation");
        }
        if ("createauditbill".equals(e.getOperateKey())) {
//            FunctionalCommon.clientDemandStartZj(this, "yem_im_detailedinfor", "yem_salescontrac_s");
            EntryGrid materialinfo = this.getControl("yem_im_detailedinfor");
            int[] selectRowIds = materialinfo.getSelectRows();
            DynamicObject dataEntity = model.getDataEntity(true);
            IABudgetCommon.pushToGeneration(dataEntity, selectRowIds, "yem_im_detailedinfor");
            view.invokeOperation("refresh");
        }
    }


    @Override
    public void afterBindData(EventObject e)
    {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        //郭祥代码
        //判断当前页面是整机还是配件
        OperationStatus status = this.getView().getFormShowParameter().getStatus();
        if (OperationStatus.ADDNEW == status) {
            String formId = this.getView().getFormShowParameter().getFormId();
            DynamicObject tpv_billtype = (DynamicObject) this.getModel().getValue("yem_billtype");
            if (null == tpv_billtype) {
                QFilter qFilter1 = new QFilter("number", QCP.equals, formId);
                DynamicObject[] bos_billtype_s = BusinessDataServiceHelper.load("bos_billtype",
                        "id,name,number", new QFilter[]{qFilter1}, null);
                if (null != bos_billtype_s && bos_billtype_s.length > 0) {
                    this.getModel().setValue("yem_billtype", bos_billtype_s[0].getLong("id"));
                    this.getModel().setValue("yem_billtypetext", bos_billtype_s[0].getString("name"));
                    this.getView().setEnable(false, "yem_billtype");
                }
            }
        }
        ClientUtils.forResourceNogLock(view, model, "yem_im_detailedinfor");
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e)
    {
        DynamicObject datas = this.getModel().getDataEntity(true);
        String key = e.getProperty().getName();
        int rowNow = e.getRow();
        QFilter qFilter = null;
        DynamicObject products = datas.getDynamicObject("yem_bd_products");
        switch (key) {
            //过滤产品分类
            case "yem_bd_products":
                DynamicObject types = datas.getDynamicObject("yem_billtype");
                if (types == null) {
                    this.getView().showMessage("请选择单据类型");
                    e.setCancel(true);
                } else {
                    qFilter = new QFilter("yem_businesssort", QCP.equals,
                            types.getString("number").equals("yem_im_inclientdeman_zj") ? "Z" : "P");
                    e.addCustomQFilter(qFilter);
                }
                break;
            //明细信息 产品型号 根据产品类型过滤
            case "yem_productmodel":
                if (products == null) {
                    this.getView().showMessage("请选择产品分类");
                    e.setCancel(true);
                } else {
                    e.addCustomQFilter(new QFilter("yem_productsgroup", QCP.equals, products.getPkValue()));
                }
                break;
            //明细信息 资源号过滤
            case "yem_resourcenog":
                int row = this.getModel().getEntryCurrentRowIndex("yem_im_detailedinfor");
                DynamicObject productmodel = (DynamicObject) this.getModel().getValue("yem_productmodel", row);
                String businesssort = (String) this.getModel().getValue("yem_businesssort", row);
                if ("P".equals(businesssort)) {
                    break;
                }
                if (productmodel == null) {
                    this.getView().showMessage("请选择基础机型第" + (row + 1) + "行");
                    e.setCancel(true);
                } else {
                    Long yemproducts = productmodel.getLong("yem_products.id");
                    e.addCustomQFilter(new QFilter("yem_products", QCP.equals, yemproducts));
                }
                break;
            //装箱核算运输费用过滤
            default:
                break;
        }

    }

    @Override
    public void propertyChanged(PropertyChangedArgs e)
    {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        ChangeData changeData = e.getChangeSet()[0];
        String proName = e.getProperty().getName();
        int ParentRow = changeData.getParentRowIndex();
        int row = changeData.getRowIndex();
        DynamicObject dyEntry = this.getModel().getDataEntity(true);
        DynamicObjectCollection dy = dyEntry.getDynamicObjectCollection("yem_im_detailedinfor");
        DynamicObjectCollection costinfor = dyEntry.getDynamicObjectCollection("yem_costinfor");
        int ordersumnumber = dyEntry.getInt("yem_ordersumnumber");
        BigDecimal yemExrate = (BigDecimal) this.getModel().getValue("yem_exrate");
        //订单总台数(整机)
        int count = 0;
        //订单总台数(配件)
        int countByP = 0;
        //分录行索引
        int rowNow = 0;
        switch (proName) {
            case "yem_exrate":
                ClientUtils.changeRate(model, "yem_im_detailedinfor");
//                ClientUtils.clearSalePrice(this.getModel());
                break;
            case "yem_qty":
                quantityRequiredAdd(dyEntry, dy, count, countByP, rowNow);
                //新计算
                ClientUtils.countFobAmt(model, row);
                ClientUtils.addSaPriceSale(model, row);
//                ClientUtils.countRealCatAmount(model, row);
                ClientUtils.countRealCatAmountRMB(model, row);
                ClientUtils.addPjSourcePrice(model, row);
                ClientUtils.countFrontDisAmt(model, row);//折扣前销售金额
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                ClientUtils.countAfterFrontPrice(model, row);//折扣后销售单价
                break;
            case "yem_frontdisprice"://折扣前单价
                ClientUtils.countFrontDisAmt(model, row);//折扣前销售金额
                break;
            case "yem_costsumamountcoin":
                cartfulAmountByTotalAmount(ordersumnumber, row);
                break;

            case "yem_ordersumnumber":
                cartfulAmountByTotalCount(costinfor, ordersumnumber, rowNow);
                break;
            //费用信息 费用类型触发
            case "yem_addorsub":
                forTotal(dyEntry, costinfor);
                break;
            // 表头大小柜变动时重新计算分录费用总金额
            case "yem_bigcabinetnumber":
                forTotal(dyEntry, costinfor);
                break;
            case "yem_mincabinetnumber":
                forTotal(dyEntry, costinfor);
                break;
            case "yem_singlenumber":
                forTotal(dyEntry, costinfor);
                break;
            case "yem_ticketprice":
                forTotal(dyEntry, costinfor);
                break;
            case "yem_bigcabinetprice":
                forTotal(dyEntry, costinfor);
                break;
            case "yem_mincabinetprice":
                forTotal(dyEntry, costinfor);
                break;
            case "yem_bigcabinetnumbers":
                bigcabinetNumberAdd(dy);
                break;
            case "yem_mincabinetnumbers":
                mincabinetNumberAdd(dy);
                break;
            //按照分录汇总 报价金额(价格条款)
            case "yem_saamtpriceclause":
                ;
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_saamtpriceclause", "yem_offeramount");//销售金额（价格条款）汇总表头 金额价格条款
                break;
            case "yem_countexpense":
                countexPenseTakeInformation(dyEntry, rowNow);
                break;
            case "yem_resourcenog":
                ClientUtils.resouceToMaterial(model, view, row);
                ClientUtils.addPjSourceAccount(model, dy);
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                break;
            case "yem_fobprice":
                ClientUtils.countFobAmt(model, row);
                break;
            case "yem_pricefieldaccamt":
                ClientUtils.addPjSourcePrice(model, row);

                break;
            case "yem_businesssort":
                quantityRequiredAdd(dyEntry, dy, count, countByP, rowNow);
                ClientUtils.lock(view, model, row);
                ClientUtils.resourceNogLock(view, model, row);
                //业务分类改变 清除资源号、物料
                this.getModel().setValue("yem_resourcenog", null, row);
                this.getModel().setValue("yem_materiel", null, row);
                break;
            case "yem_ifgift":
                ClientUtils.lock(view, model, row);
                ClientUtils.resourceNogLock(view, model, row);
                ClientUtils.empty(model, row, "yem_im_detailedinfor", view);
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_safobamount", "yem_amount");//销售fob金额 汇总表头 fob金额
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_saamtpriceclause", "yem_offeramount");//销售金额（价格条款）汇总表头 金额价格条款
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_totalamount", "yem_sumcost");//总费用 汇总表头 总费用
                ClientUtils.clearRelevantPrice(model, view, row, "yem_im_detailedinfor");
                break;
            case "yem_materiel":
                //物料改变 清除fob单价、单价（价格条款）配件
                String businesssorts = (String) this.getModel().getValue("yem_businesssort");
                if ("P".equals(businesssorts)) {
                    this.getModel().setValue("yem_fobprice", null, row);
                    this.getModel().setValue("yem_price", null, row);
                }
                TotalUtil.setUnit(model, row);//物料为空时  计量单位  基本计量单位 为台
                break;
            case "yem_productmodel":
                this.getModel().deleteEntryData("yem_multiconfig");
                FunctionalCommon.multiConfig(model, row);
                bringAssemblyAmount(row, model, "yem_im_detailedinfor");
                break;
            case "yem_reccondition":
                setSalesContrac();//选择收款条件时带出收款计划分录
                TotalUtil.countRapAmt(model, "yem_salescontrac_s");
                TotalUtil.countRapRate(model, "yem_salescontrac_s");
                break;
            case "yem_offeramount":
                TotalUtil.countRapAmt(model, "yem_salescontrac_s");
                TotalUtil.countRapRate(model, "yem_salescontrac_s");
                break;
            case "yem_raprate":
                TotalUtil.countRapAmt(model, "yem_salescontrac_s");
                break;
            case "yem_rapamt":
                TotalUtil.countRapRate(model, "yem_salescontrac_s");
                break;
            case "yem_clientcountry":
            case "yem_transportstyle":
//                setInsuranceFeeRate();
                break;
//            case "yem_price":
//                ClientUtils.countSalePrice(model,row);
//                break;
            case "yem_sapricepriceclause":
//                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                break;
            case "yem_sapriceclausebase":
//                ClientUtils.countRealCatPrice(model, row);
                break;
            case "yem_pricefieldacc":
//                ClientUtils.countRealCatPrice(model, row);
                break;
            case "yem_truecarprice":
//                ClientUtils.countRealCatAmount(model, row);
                ClientUtils.countRealCatPriceRMB(model, row);
                break;
            case "yem_truecarpriceba":
                ClientUtils.countRealCatAmountRMB(model, row);
                break;
            case "yem_standardprice":
                ClientUtils.fobPriceAdd(model, dy);
                ClientUtils.countFobAmtSale(model, row);
            case "yem_safobprice":
                ClientUtils.addSaPriceRMB(model, row);
                ClientUtils.addSaPriceSale(model, row);
                ClientUtils.countFrontDisPrice(model, row);//折扣前单价
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                break;
            case "yem_marketraisepribase":
                ClientUtils.countStandardSales(model);
                break;
            case "yem_sastandardprice":
                ClientUtils.countFobAmtSaleRMB(model, row);
                ClientUtils.addSaPrice(model, dy);
                break;
            case "yem_safobamount":
                ClientUtils.addSaPriceSaleRMB(model, row);
                ClientUtils.addPjSourceAccount(model, dy);
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_safobamount", "yem_amount");//销售fob金额 汇总表头 fob金额
//                ClientUtils.countSaPricePriceClause(model, row);//计算销售单价（价格条款）
                ClientUtils.countAfterFrontAmt(model, row);//计算折扣后销售金额
                ClientUtils.countDisAmt(model, "yem_im_detailedinfor", row, view);//计算折扣金额
                break;
            case "yem_unitsetamount":
                ClientUtils.addSaPrice(model, dy);
                break;
            case "yem_onecarfreight":
                addTotalCarCost();
                break;
            case "yem_onecarpremium":
                addTotalCarCost();
                break;
            case "yem_onecarcom":
                addTotalCarCost();
                break;
            case "yem_onecarcredit":
                addTotalCarCost();
                break;
            case "yem_bankinterest":
                addTotalCarCost();
                break;
            case "yem_giveparts":
                addTotalCarCost();
                break;
            case "yem_onecarelse":
                addTotalCarCost();
                break;
            case "yem_unitsetamountbase":
                ClientUtils.fobPriceAdd(model, dy);
                break;
            case "yem_onecarsum":
                ClientUtils.countFrontDisPrice(model, row);//折扣前单价
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_totalamount", "yem_sumcost");//总费用 汇总表头 总费用
//                ClientUtils.countSaPricePriceClause(model, row);//计算销售单价（价格条款）
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                break;
            case "yem_lenghtunit"://长度单位
            case "yem_vol"://体积
                TotalUtil.countVolM3(model, row, "yem_lenghtunit", "yem_vol", "yem_volm3");
                break;

            case "yem_pricefieldaccba":
//                ClientUtils.countRealCatPrice(model, row);
                ClientUtils.countFrontDisPrice(model, row);//折扣前单价
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别

//                ClientUtils.countSaPricePriceClause(model, row);//计算销售单价（价格条款）
                break;
            case "yem_afterfrontdisprice"://折扣后销售单价
//                ClientUtils.countSaPricePriceClause(model, row);//计算销售单价（价格条款）
                break;
            case "yem_accamtusetype"://配件资金使用方式
                ClientUtils.countDisAmt(model, "yem_im_detailedinfor", row, view);//计算折扣金额
                break;
            case "yem_fundpoolamt"://使用额度
                ClientUtils.countDisAmt(model, "yem_im_detailedinfor", row, view);//计算折扣金额
                break;
            case "yem_amount"://财务信息 fob金额
                ClientUtils.countDisAmt(model, "yem_im_detailedinfor", row, view);//计算折扣金额
                break;
            case "yem_frontrateentry"://明细信息 折扣率
                ClientUtils.countDisAmt(model, "yem_im_detailedinfor", row, view);//计算折扣金额
                break;
            case "yem_afterfrontdisamt"://折扣后销售金额
                ClientUtils.countAfterFrontPrice(model, row);//折扣后销售单价
                break;
            case "yem_disamt"://折扣金额
                ClientUtils.countFrontDisAmt(model, row);//折扣前金额
                ClientUtils.countAfterFrontAmt(model, row);//计算折扣后销售金额
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                break;
            case "yem_totalamount":
                ClientUtils.totalSaFobAmount(model, "yem_im_detailedinfor", "yem_ifgift", "yem_totalamount", "yem_sumcost");//总费用 汇总表头 总费用
                ClientUtils.addSaAmountTk(model, row);//销售金额（价格条款）结算币别
                break;
            default:
                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_im_detailedinfor");
    }

    /**
     * 计算单车总费用
     */
    private void addTotalCarCost()
    {
        BigDecimal onecarfreight = (BigDecimal) this.getModel().getValue("yem_onecarfreight");
        BigDecimal onecarpremium = (BigDecimal) this.getModel().getValue("yem_onecarpremium");
        BigDecimal onecarcom = (BigDecimal) this.getModel().getValue("yem_onecarcom");
        BigDecimal onecarcredit = (BigDecimal) this.getModel().getValue("yem_onecarcredit");
        BigDecimal bankinterest = (BigDecimal) this.getModel().getValue("yem_bankinterest");
        BigDecimal giveparts = (BigDecimal) this.getModel().getValue("yem_giveparts");
        BigDecimal onecarelse = (BigDecimal) this.getModel().getValue("yem_onecarelse");
        this.getModel().setValue("yem_onecarsum", onecarfreight.add(onecarpremium).add(onecarcom).add(onecarcredit).
                add(bankinterest).add(giveparts).add(onecarelse));
    }

    /**
     * 装箱核算运输费用携带 费用信息
     */
    private void countexPenseTakeInformation(DynamicObject dyEntry, int rowNow)
    {
        this.getModel().deleteEntryData("yem_costinfor");
        String countexpense = dyEntry.getString("yem_countexpense.number");
        List<QFilter> list = new ArrayList<>();
        if (countexpense != null) {
            list.add(new QFilter("number", QCP.equals, countexpense));
            DynamicObjectCollection collection = QueryServiceHelper.query("yem_bd_transportcosts", "yem_bd_logistics.yem_padexpense.id,yem_bd_logistics.yem_billingway.id," +
                    "yem_bd_logistics.yem_ticketprice,yem_bd_logistics.yem_bigcabinetprice,yem_bd_logistics.yem_mincabinetprice", list.toArray(new QFilter[0]));
            for (DynamicObject temp : collection) {
                Long padexpense = temp.getLong("yem_bd_logistics.yem_padexpense.id");
                Long billingway = temp.getLong("yem_bd_logistics.yem_billingway.id");
                BigDecimal ticketprice = temp.getBigDecimal("yem_bd_logistics.yem_ticketprice");
                BigDecimal bigcabinetprice = temp.getBigDecimal("yem_bd_logistics.yem_bigcabinetprice");
                BigDecimal mincabinetprice = temp.getBigDecimal("yem_bd_logistics.yem_mincabinetprice");
                this.getModel().createNewEntryRow("yem_costinfor");
                this.getModel().setValue("yem_padexpense", padexpense, rowNow);
                this.getModel().setValue("yem_bd_chargemode", billingway, rowNow);
                this.getModel().setValue("yem_ticketprice", ticketprice, rowNow);
                this.getModel().setValue("yem_bigcabinetprice", bigcabinetprice, rowNow);
                this.getModel().setValue("yem_mincabinetprice", mincabinetprice, rowNow);
                rowNow++;
            }
        }

    }


    /**
     * 小柜数量明细信息汇总
     */
    private void mincabinetNumberAdd(DynamicObjectCollection dy)
    {
        BigDecimal total2 = BigDecimal.ZERO;
        for (DynamicObject temp : dy) {
            BigDecimal bigcabinetnumbers = temp.getBigDecimal("yem_mincabinetnumbers");
            total2 = total2.add(bigcabinetnumbers);
        }
        this.getModel().setValue("yem_mincabinetnumber", total2);
    }

    /**
     * 大柜数量明细信息汇总
     */
    private void bigcabinetNumberAdd(DynamicObjectCollection dy)
    {
        BigDecimal total = BigDecimal.ZERO;
        for (DynamicObject temp : dy) {
            BigDecimal bigcabinetnumbers = temp.getBigDecimal("yem_bigcabinetnumbers");
            total = total.add(bigcabinetnumbers);
        }
        this.getModel().setValue("yem_bigcabinetnumber", total);
    }

    /**
     * 单车费用金额=费用总金额本位币/订单总台数
     * 订单总台数触发
     */
    private void cartfulAmountByTotalCount(DynamicObjectCollection costinfor, int ordersumnumber, int rowNow)
    {
        for (DynamicObject temp : costinfor) {
            BigDecimal decimal = temp.getBigDecimal("yem_costsumamountcoin");
            BigDecimal end = BigDecimal.ZERO;
            if (ordersumnumber != 0) {
                end = decimal.divide(new BigDecimal(ordersumnumber), RoundingMode.HALF_UP);
            }
            this.getModel().setValue("yem_cartfulamountcoin", end, rowNow);
            rowNow++;
        }
    }

    /**
     * 单车费用金额=分录费用总金额/订单总台数
     * 分录费用总金额触发
     */
    private void cartfulAmountByTotalAmount(int ordersumnumber, int row)
    {
        Object costsumamount = this.getModel().getValue("yem_costsumamountcoin", row);
        if (costsumamount == null) {
            return;
        }
        BigDecimal costsumamounts = (BigDecimal) costsumamount;
        if (ordersumnumber != 0) {
            this.getModel().setValue("yem_cartfulamountcoin", costsumamounts.divide(new BigDecimal(ordersumnumber), RoundingMode.HALF_UP), row);
        }
    }

    /**
     * 明细分录中业务分类为整机的【需求数量】总和汇总至 表头【订单总台数】
     */
    private void quantityRequiredAdd(DynamicObject dyEntry, DynamicObjectCollection dy, int count, int countByP, int rowNow)
    {
        for (DynamicObject temp : dy) {
            String businesssort = temp.getString("yem_businesssort");
            if (businesssort != null && "Z".equals(businesssort)) {
                int tempCount = temp.getInt("yem_qty");
                count += tempCount;
            } else if (businesssort != null && "P".equals(businesssort)) {
                int tempCount = temp.getInt("yem_qty");
                countByP += tempCount;
            }

            rowNow++;
        }
        if (ClientUtils.isZJPage(this.getModel())) {
            this.getModel().setValue("yem_ordersumnumber", count);
        } else if (ClientUtils.isPjPage(this.getModel())) {
            this.getModel().setValue("yem_ordersumnumber", countByP);
        }
    }

    /**
     * 重新计算分录费用总金额
     */

    private void forTotal(DynamicObject dyEntry, DynamicObjectCollection costinfor)
    {
        int tempRow = 0;
        int bigcabinetnumber = dyEntry.getInt("yem_bigcabinetnumber");
        int mincabinetnumber = dyEntry.getInt("yem_mincabinetnumber");
        int singlenumber = dyEntry.getInt("yem_singlenumber");
        //附加费用合计
        BigDecimal addorsubCount = BigDecimal.ZERO;
        //汇率
        BigDecimal rate = BigDecimal.ONE;
        boolean flag = false;
        for (DynamicObject temp : costinfor) {
            String chargemode = temp.getString("yem_bd_chargemode.name");
            String yem_addorsub = temp.getString("yem_addorsub");
            BigDecimal total = BigDecimal.ZERO;
            if ("按柜计费".equals(chargemode)) {
                BigDecimal bigcabinetprice = temp.getBigDecimal("yem_bigcabinetprice");
                BigDecimal mincabinetprice = temp.getBigDecimal("yem_mincabinetprice");
                if (bigcabinetprice != null && mincabinetprice != null) {
                    total = bigcabinetprice.multiply(new BigDecimal(bigcabinetnumber)).add(
                            mincabinetprice.multiply(new BigDecimal(mincabinetnumber))
                    );
                }
            } else if ("按票计费".equals(chargemode)) {
                BigDecimal ticketprice = temp.getBigDecimal("yem_ticketprice");
                if (ticketprice != null) {
                    total = ticketprice.multiply(new BigDecimal(singlenumber));
                }
            }
            //汇总 附加费用合计
            if ("A".equals(yem_addorsub)) {
                flag = true;
                addorsubCount = addorsubCount.add(total);
            }
            this.getModel().setValue("yem_costsumamountcoin", total, tempRow);
            tempRow++;
        }
        if (flag) {
            this.getModel().setValue("yem_calculationamtcoin", addorsubCount);
        }


    }

    /**
     * 回填资源号
     */
    public void backFillSource()
    {
        FormShowParameter fsp = new FormShowParameter();
        fsp.setFormId("yem_backresourceno");
        fsp.getOpenStyle().setShowType(ShowType.Modal);
        this.getView().showForm(fsp);
    }


    /**
     * @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_salescontrac_s");
        if (recCondition != null) {
            String basis = recCondition.getString("basis");
            DynamicObjectCollection entrys = recCondition.getDynamicObjectCollection("entry");
            for (DynamicObject entry : entrys) {
                int entryRow = model.createNewEntryRow("yem_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 countRapAmt()
    {
        IDataModel model = this.getModel();
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        if (YEM.isNotEmpty(recCondition)) {
            String basis = recCondition.getString("basis");
            BigDecimal billAmt = (BigDecimal) model.getValue("yem_amount");
            if ("A".equals(basis) && billAmt.compareTo(BigDecimal.ZERO) > 0) {
                int salescontracs = model.getEntryRowCount("yem_salescontrac_s");
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapRate = (BigDecimal) model.getValue("yem_raprate", i);
                    model.setValue("yem_rapamt", billAmt.multiply(rapRate.divide(new BigDecimal(100), RoundingMode.HALF_UP)), i);
                }
            }
        }
    }

    public void countRapRate()
    {
        IDataModel model = this.getModel();
        DynamicObject recCondition = (DynamicObject) model.getValue("yem_reccondition");
        if (YEM.isNotEmpty(recCondition)) {
            String basis = recCondition.getString("basis");
            BigDecimal total = BigDecimal.ZERO;
            if ("B".equals(basis)) {
                int salescontracs = model.getEntryRowCount("yem_salescontrac_s");
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                    total = total.add(rapAmt);
                }
                for (int i = 0; i < salescontracs; i++) {
                    BigDecimal rapAmt = (BigDecimal) model.getValue("yem_rapamt", i);
                    model.setValue("yem_raprate", rapAmt.multiply(new BigDecimal(100)).divide(total, RoundingMode.HALF_DOWN), i);
                }
            }
        }
    }

    /**
     * @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(clientCountry) && YEM.isNotEmpty(transportStyle)) {
            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());
            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");
                        }
                    }
                }
            }
        }
        model.setValue("yem_insurancefeerate", insuranceFeeRate);
    }
}
