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

import com.google.common.collect.Sets;
import com.yem.tws.common1.BigDecimalUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.exception.KDBizException;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.RefBillEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import org.apache.commons.compress.utils.Lists;

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

/**
 * @author power
 * @ClassName: 出口费用申请单
 * @description: 子单据体数据汇总到父单据体 表单插件
 * @date 2023/8/16
 */
public class ExportCostEdit extends AbstractBillPlugIn implements BeforeF7SelectListener {

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        RefBillEdit salcontractno = this.getControl("yem_salcontractno");
        salcontractno.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        if ("yem_salcontractno".equals(key)) {
            ListShowParameter fsp = (ListShowParameter) e.getFormShowParameter();
            fsp.setMultiSelect(false);
            int rowIndex = model.getEntryCurrentRowIndex("yem_csotdetail");
            String storagetransno = (String) model.getValue("yem_storagetransno", rowIndex);
            if (YEM.isNotEmpty(storagetransno)) {
                DynamicObject[] load = BusinessDataServiceHelper.load("yem_es_storagetrans", "id, billno, yem_corebillid, yem_es_materialinfo.yem_corebillid_d", new QFilter[]{new QFilter("billno", "=", storagetransno)});
                HashSet<Long> set = Sets.newHashSet();
                for (DynamicObject dynamicObject : load) {
                    DynamicObjectCollection collection = dynamicObject.getDynamicObjectCollection("yem_es_materialinfo");
                    set.add(dynamicObject.getLong("yem_corebillid"));
                    for (DynamicObject object : collection) {
                        set.add(object.getLong("yem_corebillid_d"));
                    }
                }
                QFilter qFilter = new QFilter("id", "in", set);
                e.addCustomQFilter(qFilter);
            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        ChangeData cd = e.getChangeSet()[0];
        ChangeData[] changeData = e.getChangeSet();
        int row = changeData[0].getRowIndex();
        IDataModel model = this.getModel();
        switch (name) {
            case "yem_numerical":
                this.numerical(row);
                break;
            case "yem_applyamt_b":
//                this.calcAmountMethod();
                break;
            case "yem_salcontractno":
                carryContractInfo(model, row);
                break;
            default:
                break;
        }
    }

    private void carryContractInfo(IDataModel model, int row) {
        DynamicObject order = (DynamicObject) model.getValue("yem_salcontractno");
        if (order == null) return;
        order = BusinessDataServiceHelper.loadSingle(order.getPkValue(), order.getDynamicObjectType().getName());
        model.setValue("yem_category", order.getLong("yem_bd_products.id"), row);//品类
        model.setValue("yem_country", order.getLong("yem_clientcountry.id"), row);//国家
        model.setValue("yem_signdate", order.getDate("yem_signdate"), row);//合同签订日期
        model.setValue("yem_custom", order.getLong("yem_customer.id"), row);//客户
    }

    /**
     * 根据主提单号带出 储运脱单号
     */
    private void numerical(int row) {
        String numericalid = (String) this.getModel().getValue("yem_numerical", row);
        if (YEM.isNotEmpty(numericalid)) {
            DynamicObject aCollection1 = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "yem_noticeno,billno,", new QFilter[]{new QFilter("yem_noticeno", QCP.equals, numericalid)});
            if (aCollection1 != null) {
                String billno = aCollection1.getString("billno");
                this.getModel().setValue("yem_storagetransno", billno, row);
            } else {
                this.getModel().setValue("yem_storagetransno", "", row);
            }
        } else {
            this.getModel().setValue("yem_storagetransno", "", row);
        }
    }

    /**
     * 子分录 申请金额 汇总拆分费用合计
     */
    private void calcAmountMethod() {
        //目标单单据体数据，采购订单的单据体标识
        EntryGrid entry = this.getControl("yem_splitcost");
        //合计单据体的金额字段
        BigDecimal sumapplyamt = entry.getSum("yem_applyamt_b");
        BigDecimal sumapplyamtbase = entry.getSum("yem_applyamtbase_b");
        //设置合计字段到单据头的总金额字段(kded_amount)yem_applyamt_b
        this.getModel().setValue("yem_applyforamt", sumapplyamt);
        this.getModel().setValue("yem_applyforamtbase", sumapplyamtbase);
    }

    /**
     * 删除单据体触发
     * 子分录 申请金额 汇总拆分费用合计
     */
    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        //通过单据体行删除事件来触发
        String entryName = e.getEntryProp().getName();
        if ("yem_splitcost".equals(entryName)) {
//            calcAmountMethod();
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        IDataModel model = this.getModel();
        switch (operateKey) {
            case "splitfee":
                splitFee();
                break;
            //反写 明细信息中 拆分方式
            case "dobyconstract":
//                splitByConstract(model);
                splitCost(model, "contract");
                break;
            //反写 明细信息中 拆分方式
            case "dobycar":
//                splitByCar(model);
                splitCost(model, "car");
                break;
            case "save":
                this.getView().invokeOperation("refresh");
                break;
        }
    }

    private void splitCost(IDataModel model, String type) {
        DynamicObject dataEntity = model.getDataEntity(true);

        EntryGrid control = this.getControl("yem_csotdetail");
        int[] selectRows = control.getSelectRows();
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_csotdetail");

        BigDecimal exrate = dataEntity.getBigDecimal("yem_exrate");

        for (int selectRow : selectRows) {
            // 费用明细
            DynamicObject costEntry = collection.get(selectRow);
            // 提单号
            String numerical = costEntry.getString("yem_numerical");
            // 申请金额
            BigDecimal applyforamt = costEntry.getBigDecimal("yem_applyforamt");

            if ("car".equals(type)) {
                costEntry.set("yem_splitting", "B");
            } else {
                costEntry.set("yem_splitting", "A");
            }

            // key = 合同号_发运明细号，value = 订舱通知单分录行[]
            Map<String, List<DynamicObject>> map = new HashMap<>();

            String splitType;

            // 提单号不为空按照提单号拆分
            if (YEM.isNotEmpty(numerical)) {
                String selectfields = DynamicObjectUtil.getSelectfields("yem_es_storagetrans");
                String entrySelectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_es_storagetrans", "yem_es_materialinfo");
                QFilter qFilter = new QFilter("yem_noticeno", QCP.equals, numerical).and("billstatus", QCP.equals, "C");
                DynamicObject[] loads = BusinessDataServiceHelper.load("yem_es_storagetrans", entrySelectfields, qFilter.toArray());
                if (loads.length == 0) {
                    throw new KDBizException(String.format("提单号 [ %s ]下未找到已审核的订舱通知单！", numerical));
                }
                splitType = "T";
                for (DynamicObject load : loads) {
                    // 订舱通知单 商品明细
                    DynamicObjectCollection materialinfo = load.getDynamicObjectCollection("yem_es_materialinfo");
                    for (DynamicObject object : materialinfo) {
                        String contractnumbers = object.getString("yem_contractnumbers_m");
                        String shipmentnumbers = object.getString("yem_shipmentnumbers_m");
                        long materiel = object.getLong("yem_materiel.id");
                        if (YEM.isEmpty(contractnumbers) || YEM.isEmpty(shipmentnumbers)) continue;
                        String key = String.format("%s_%s", contractnumbers, shipmentnumbers);
                        if ("car".equals(type)) {
                            key = String.format("%s_%s_%s", contractnumbers, shipmentnumbers, materiel);
                        }
                        boolean ifgift = object.getBoolean("yem_ifgift");
                        if (!ifgift) {
                            List<DynamicObject> exist;
                            if (map.containsKey(key)) {
                                exist = map.get(key);
                            } else {
                                exist = new ArrayList<>();
                            }
                            exist.add(object);
                            map.put(key, exist);
                        }
                    }
                }
            } else {
                // 提单号为空，按照合同号拆分
                // key = 合同号  value = 合同分录录行[]
                DynamicObject salcontractno = costEntry.getDynamicObject("yem_salcontractno");
                if (YEM.isEmpty(salcontractno)) continue;

                splitType = "C";
                salcontractno = BusinessDataServiceHelper.loadSingle(salcontractno.getPkValue(), salcontractno.getDynamicObjectType().getName());

                String key = salcontractno.getString("billno");
                DynamicObjectCollection materialinfo = salcontractno.getDynamicObjectCollection("yem_es_materialinfo");
                for (DynamicObject object : materialinfo) {
                    boolean ifgift = object.getBoolean("yem_ifgift");
                    if (!ifgift) {
                        List<DynamicObject> exist;
                        if (map.containsKey(key)) {
                            exist = map.get(key);
                        } else {
                            exist = new ArrayList<>();
                        }
                        exist.add(object);
                        map.put(key, exist);
                    }
                }
            }

            Map<String, List<DynamicObject>> merge = new HashMap<>();

            for (Map.Entry<String, List<DynamicObject>> existMap : map.entrySet()) {
                String key = existMap.getKey();
                List<DynamicObject> value = existMap.getValue();
                BigDecimal mergeQty = BigDecimal.ZERO;
                BigDecimal mergeAmt = BigDecimal.ZERO;
                DynamicObject base = value.get(0);
                for (DynamicObject object : value) {
                    mergeQty = mergeQty.add(object.getBigDecimal("yem_qty"));
                    mergeAmt = mergeAmt.add(object.getBigDecimal("yem_saamtpriceclause"));
                }
                base.set("yem_qty", mergeQty);
                base.set("yem_saamtpriceclause", mergeAmt);

                List<DynamicObject> list = new ArrayList<>();
                list.add(base);
                merge.put(key, list);
            }

            // 拆分费用
            DynamicObjectCollection splitcost = costEntry.getDynamicObjectCollection("yem_splitcost");
            splitcost.clear();

            Set<String> businesssortSet = new HashSet<>();

            // 相同合同号_发运明细号的分录行
            for (Map.Entry<String, List<DynamicObject>> keyValEntry : merge.entrySet()) {
                List<DynamicObject> entryRows = keyValEntry.getValue();

                for (DynamicObject row : entryRows) {
                    // 业务分类
                    String businesssort = row.getString("yem_businesssort");
                    if (YEM.isEmpty(businesssort)) continue;
                    businesssortSet.add(businesssort);
                }
            }

            // 有业务分类为整机的。按照整机拆分 分摊，配件不分摊，否则按照配件分摊
            if (businesssortSet.contains("Z")) {

                // 费用合计
                BigDecimal sumAmt = calculateSumAmount(merge.entrySet(), "Z");
                for (Map.Entry<String, List<DynamicObject>> keyValEntry : merge.entrySet()) {
                    List<DynamicObject> entryRows = keyValEntry.getValue();

                    for (DynamicObject row : entryRows) {
                        // 业务分类
                        String businesssort = row.getString("yem_businesssort");
                        if (YEM.isEmpty(businesssort)) continue;
                        if ("Z".equals(businesssort)) {
                            // 分摊金额 = 申请金额 * row.销售金额 / 费用合计
                            BigDecimal apportionedAmount = BigDecimalUtils.div(applyforamt.multiply(row.getBigDecimal("yem_saamtpriceclause")), sumAmt, 2);
                            // 数量 = row.数量
                            BigDecimal qty = row.getBigDecimal("yem_qty");
                            DynamicObject addNew = splitcost.addNew();

                            addNew.set("yem_applyamt_b", apportionedAmount);
                            addNew.set("yem_applyamtbase_b", apportionedAmount.multiply(exrate));
                            addNew.set("yem_qtys", qty);

                            addNew.set("yem_padexpense_b", costEntry.get("yem_padexpense")); // 费用项目
                            addNew.set("yem_underdep_b", costEntry.get("yem_underdep")); // 承担部门
                            addNew.set("yem_costbelong_b", costEntry.get("yem_costbelong")); // 费用归属
                            addNew.set("yem_numerical_b", costEntry.get("yem_numerical")); // 提单号

                            String contractnumbers;
                            // 提单号
                            if ("T".equals(splitType)) {
                                contractnumbers = row.getString("yem_contractnumbers_m");

                            } else {
                                // 合同号
                                contractnumbers = keyValEntry.getKey();
                            }
                            DynamicObject salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, contractnumbers)});
                            addNew.set("yem_salcontractno_b", salesorder); // 合同号

                            long entryId = row.getLong("id");
                            DynamicObject storagetransno = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "id, billno", new QFilter[]{new QFilter("yem_es_materialinfo.id", QCP.equals, entryId)});
                            if (YEM.isNotEmpty(storagetransno)) {
                                addNew.set("yem_storagetransno_b", storagetransno.getString("billno")); // 储运托单号
                            }

                            if ("car".equals(type)) {

                                addNew.set("yem_resourcenog_b", row.getDynamicObject("yem_materiel")); // 物料编码
                            }


                            addNew.set("yem_paypurpose_b", costEntry.get("yem_paypurpose")); // 付款类型
                            addNew.set("yem_clearing_b", costEntry.get("yem_clearing_a")); // 结算方式
                            BigDecimal taxrate = costEntry.getBigDecimal("yem_taxrate"); // 税率
                            addNew.set("yem_taxrate_b", taxrate);
                            addNew.set("yem_taxrateamt_b", BigDecimalUtils.div(taxrate.multiply(apportionedAmount), new BigDecimal("100"), 2)); // 税额

                            BigDecimal bikecost = BigDecimalUtils.div(apportionedAmount, qty, 2);
                            addNew.set("yem_bikecost", bikecost); // 单车费用
                            addNew.set("yem_bikecostbase", bikecost.multiply(exrate));

                            addNew.set("yem_remark_b", costEntry.getString("yem_remark"));
                        }
                    }
                }
            }

            // 没有整机，按照配件拆分
            if (!businesssortSet.isEmpty() && !businesssortSet.contains("Z")) {
                // 费用合计
                BigDecimal sumAmt = calculateSumAmount(merge.entrySet(), "P");

                for (Map.Entry<String, List<DynamicObject>> keyValEntry : merge.entrySet()) {
                    List<DynamicObject> entryRows = keyValEntry.getValue();

                    for (DynamicObject row : entryRows) {
                        // 业务分类
                        String businesssort = row.getString("yem_businesssort");
                        if (YEM.isEmpty(businesssort)) continue;
                        if ("P".equals(businesssort)) {
                            // 分摊金额 = 申请金额 * row.销售金额 / 费用合计
                            BigDecimal apportionedAmount = BigDecimalUtils.div(applyforamt.multiply(row.getBigDecimal("yem_saamtpriceclause")), sumAmt, 2);
                            // 数量 = row.数量
                            BigDecimal qty = row.getBigDecimal("yem_qty");
                            DynamicObject addNew = splitcost.addNew();

                            addNew.set("yem_applyamt_b", apportionedAmount);
                            addNew.set("yem_applyamtbase_b", apportionedAmount.multiply(exrate));
                            addNew.set("yem_qtys", qty);

                            addNew.set("yem_padexpense_b", costEntry.get("yem_padexpense")); // 费用项目
                            addNew.set("yem_underdep_b", costEntry.get("yem_underdep")); // 承担部门
                            addNew.set("yem_costbelong_b", costEntry.get("yem_costbelong")); // 费用归属
                            addNew.set("yem_numerical_b", costEntry.get("yem_numerical")); // 提单号

                            String contractnumbers;
                            // 提单号
                            if ("T".equals(splitType)) {
                                contractnumbers = row.getString("yem_contractnumbers_m");

                            } else {
                                // 合同号
                                contractnumbers = keyValEntry.getKey();
                            }
                            DynamicObject salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("billno", QCP.equals, contractnumbers)});
                            addNew.set("yem_salcontractno_b", salesorder); // 合同号

                            long entryId = row.getLong("id");
                            DynamicObject storagetransno = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "id, billno", new QFilter[]{new QFilter("yem_es_materialinfo.id", QCP.equals, entryId)});
                            if (YEM.isNotEmpty(storagetransno)) {
                                addNew.set("yem_storagetransno_b", storagetransno.getString("billno")); // 储运托单号
                            }

                            if ("car".equals(type)) {

                                addNew.set("yem_resourcenog_b", row.getDynamicObject("yem_materiel")); // 物料编码
                            }

                            addNew.set("yem_paypurpose_b", costEntry.get("yem_paypurpose")); // 付款类型
                            addNew.set("yem_clearing_b", costEntry.get("yem_clearing_a")); // 结算方式
                            BigDecimal taxrate = costEntry.getBigDecimal("yem_taxrate"); // 税率
                            addNew.set("yem_taxrate_b", taxrate);
                            addNew.set("yem_taxrateamt_b", BigDecimalUtils.div(taxrate.multiply(apportionedAmount), new BigDecimal("100"), 2)); // 税额

                            BigDecimal bikecost = BigDecimalUtils.div(apportionedAmount, qty, 2);
                            addNew.set("yem_bikecost", bikecost); // 单车费用
                            addNew.set("yem_bikecostbase", bikecost.multiply(exrate));

                            addNew.set("yem_remark_b", costEntry.getString("yem_remark"));
                        }
                    }
                }
            }
        }

        tailDifference(model);

        this.getView().updateView("yem_csotdetail");
        this.getView().updateView("yem_splitcost");
    }

    private void tailDifference(IDataModel model) {
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_csotdetail");
        for (DynamicObject object : collection) {
            BigDecimal applyforamt = object.getBigDecimal("yem_applyforamt");
            DynamicObjectCollection subCollection = object.getDynamicObjectCollection("yem_splitcost");
            for (DynamicObject subObject : subCollection) {
                int index = subCollection.indexOf(subObject);
                if (index == subCollection.size() - 1) {
                    subObject.set("yem_applyamt_b", applyforamt);
                }
                applyforamt = applyforamt.subtract(subObject.getBigDecimal("yem_applyamt_b"));
            }
        }
    }


    /**
     * 计算费用合计
     *
     * @param entryRows
     * @param businesssort
     * @return
     */
    private BigDecimal calculateSumAmount(Set<Map.Entry<String, List<DynamicObject>>> entryRows, String businesssort) {
        BigDecimal sumAmt = BigDecimal.ZERO;
        for (Map.Entry<String, List<DynamicObject>> entryRow : entryRows) {
            List<DynamicObject> list = entryRow.getValue();
            for (DynamicObject row : list) {
                String entryBusinessSort = row.getString("yem_businesssort");
                if (businesssort.equals(entryBusinessSort)) {
                    if ("Z".equals(businesssort)) {
                        sumAmt = sumAmt.add(row.getBigDecimal("yem_saamtpriceclause"));
                    }
                    if ("P".equals(businesssort)) {
                        if (Boolean.FALSE.equals(row.getBoolean("yem_ifgift"))) {
                            sumAmt = sumAmt.add(row.getBigDecimal("yem_saamtpriceclause"));
                        }
                    }
                }
            }
        }
        return sumAmt;
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        if ("save".equals(operateKey)) {
            IDataModel model = this.getModel();
            DynamicObject dataEntity = model.getDataEntity(true);
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_csotdetail");
            StringBuilder sb = new StringBuilder();
            Set<String> set = new HashSet<>();
            for (DynamicObject dynamicObject : collection) {
                String numerical = dynamicObject.getString("yem_numerical");
                if (YEM.isNotEmpty(numerical)) {
                    set.add(numerical);
                }
            }
            for (String no : set) {
                sb.append(no).append("；");
            }
            dataEntity.set("yem_tdno", sb.toString());
        }
    }

    /***
     * 按单车拆分
     */

    private void splitByCar(IDataModel model) {
        int currentRow = model.getEntryCurrentRowIndex("yem_csotdetail");
        BigDecimal yemApplyforamt = (BigDecimal) model.getValue("yem_applyforamt", currentRow);
        this.getModel().setValue("yem_splitting", "B", currentRow);
        //拆分逻辑
        String storagetransno = (String) model.getValue("yem_storagetransno", currentRow);
        DynamicObject object = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "billstatus", new QFilter[]{new QFilter("billno", QCP.equals, storagetransno)});
        if (object != null) {
            String billstatus = object.getString("billstatus");
            if (!"C".equals(billstatus)) {
                throw new KDBizException(String.format("费用明细第 [ %s ] 行，订舱通知单 [ %s ] 未审核，请审核后再进行拆分！", currentRow + 1, storagetransno));
            }
            DynamicObject datas = BusinessDataServiceHelper.loadSingle(object.getPkValue(), object.getDynamicObjectType().getName());
            //单车 全配件拆分
            DynamicObjectCollection materialinfo = datas.getDynamicObjectCollection("yem_es_materialinfo");
            //是否全配件
            boolean flag = true;
            for (DynamicObject dt : materialinfo) {
                String string = dt.getString("yem_businesssort");
                if ("Z".equals(string)) {
                    flag = false;
                }
            }
            //全配件

            List<BigDecimal> list = new ArrayList();
            if (flag) {
                //合并数据(合同号、出运明细、物料编码)
                HashMap<String, BigDecimal> constractData = new LinkedHashMap<>();
                BigDecimal count = BigDecimal.ZERO;
                for (DynamicObject dc : materialinfo) {
                    if (!dc.getBoolean("yem_ifgift")) {
                        count = count.add(dc.getBigDecimal("yem_saamtpriceclause"));
                        String contractnumbers = dc.getString("yem_contractnumbers_m");
                        String shipmentnumbers = dc.getString("yem_shipmentnumbers_m");
                        DynamicObject yemMateriel = dc.getDynamicObject("yem_materiel");
                        String MaterielNumber = "";
                        if (yemMateriel != null) {
                            MaterielNumber = yemMateriel.getString("number");
                        }
                        String newKey = contractnumbers + shipmentnumbers + MaterielNumber;
                        BigDecimal yemSaamtpriceclause = dc.getBigDecimal("yem_saamtpriceclause");
                        if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && YEM.isNotEmpty(MaterielNumber) && !constractData.containsKey(newKey)) {
                            constractData.put(newKey, yemSaamtpriceclause);
                        } else if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && YEM.isNotEmpty(MaterielNumber) && constractData.containsKey(newKey)) {
                            BigDecimal decimal = constractData.get(newKey);
                            if (decimal != null) {
                                constractData.put(newKey, decimal.add(yemSaamtpriceclause));
                            }
                        }
                    }
                }
                //拆分后的数据集合
                for (String key : constractData.keySet()) {
                    if (count.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal endAmount = yemApplyforamt.multiply(constractData.get(key)).divide(count, RoundingMode.UP);
                        list.add(endAmount);
                    }
                }

//                for(DynamicObject dc:materialinfo){
//                    if(!dc.getBoolean("yem_ifgift")){
//                        count = count.add(dc.getBigDecimal("yem_saamtpriceclause"));
//                    }
//                }
//                //拆分后的数据集合
//
//                for(DynamicObject dc:materialinfo){
//                    if(!dc.getBoolean("yem_ifgift")){
//                        if(count.compareTo(BigDecimal.ZERO) != 0){
//                            BigDecimal endAmount = yemApplyforamt.multiply(dc.getBigDecimal("yem_saamtpriceclause")).divide(count, RoundingMode.UP);
//                            list.add(endAmount);
//                        }
//
//                    }
//                }


            } else {
                //有整机有配件
                HashMap<String, BigDecimal> constractData = new LinkedHashMap<>();
                BigDecimal count = BigDecimal.ZERO;
                for (DynamicObject dc : materialinfo) {
                    if ("Z".equals(dc.getString("yem_businesssort"))) {
                        count = count.add(dc.getBigDecimal("yem_saamtpriceclause"));
                        String contractnumbers = dc.getString("yem_contractnumbers_m");
                        String shipmentnumbers = dc.getString("yem_shipmentnumbers_m");

                        BigDecimal yemSaamtpriceclause = dc.getBigDecimal("yem_saamtpriceclause");
                        DynamicObject yemMateriel = dc.getDynamicObject("yem_materiel");
                        String MaterielNumber = "";
                        if (yemMateriel != null) {
                            MaterielNumber = yemMateriel.getString("number");
                        }
                        String newKey = contractnumbers + shipmentnumbers + yemMateriel;
                        if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && YEM.isNotEmpty(MaterielNumber) && !constractData.containsKey(newKey)) {
                            constractData.put(newKey, yemSaamtpriceclause);
                        } else if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && YEM.isNotEmpty(MaterielNumber) && constractData.containsKey(newKey)) {
                            BigDecimal decimal = constractData.get(newKey);
                            if (decimal != null) {
                                constractData.put(newKey, decimal.add(yemSaamtpriceclause));
                            }

                        }
                    }
                }
                for (String key : constractData.keySet()) {
                    if (count.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal endAmount = yemApplyforamt.multiply(constractData.get(key)).divide(count, RoundingMode.UP);
                        list.add(endAmount);
                    }
                }

//                BigDecimal count = BigDecimal.ZERO;
//                for(DynamicObject dc:materialinfo){
//                    if("Z".equals(dc.getString("yem_businesssort"))){
//                        count = count.add(dc.getBigDecimal("yem_saamtpriceclause"));
//                    }
//                }
//
//                for(DynamicObject dc:materialinfo){
//                    if("Z".equals(dc.getString("yem_businesssort"))){
//                        if(count.compareTo(BigDecimal.ZERO) != 0){
//                            BigDecimal endAmount = yemApplyforamt.multiply(dc.getBigDecimal("yem_saamtpriceclause")).divide(count, RoundingMode.UP);
//                            list.add(endAmount);
//                        }
//
//                    }
//                }

            }
            //申请金额 尾差处理
            BigDecimal countTemp = BigDecimal.ZERO;
            for (BigDecimal temp : list) {
                countTemp = countTemp.add(temp);
            }
            if (countTemp.compareTo(yemApplyforamt) < 0) {
                if (list.size() > 0) {
                    BigDecimal decimal = list.get(0);
                    list.set(0, decimal.add(yemApplyforamt.subtract(countTemp)));
                }
            }
            //反写给出口费用申请 拆分费用分录
            model.deleteEntryData("yem_splitcost");
            for (BigDecimal temp : list) {
                int rowIdx = model.createNewEntryRow("yem_splitcost");
                model.setValue("yem_applyamt_b", temp, rowIdx);
                model.setValue("yem_qtys", list.size(), rowIdx);
            }
        }
    }

    /**
     * 按合同拆分
     */
    private void splitByConstract(IDataModel model) {
        int currentRow = model.getEntryCurrentRowIndex("yem_csotdetail");
        BigDecimal yemApplyforamt = (BigDecimal) model.getValue("yem_applyforamt", currentRow);
        this.getModel().setValue("yem_splitting", "A", currentRow);
        //拆分逻辑
        String storagetransno = (String) model.getValue("yem_storagetransno", currentRow);
        DynamicObject object = BusinessDataServiceHelper.loadSingle("yem_es_storagetrans", "billstatus", new QFilter[]{new QFilter("billno", QCP.equals, storagetransno)});
        if (object != null) {
            String billstatus = object.getString("billstatus");
            if (!"C".equals(billstatus)) {
                throw new KDBizException(String.format("费用明细第 [ %s ] 行，订舱通知单 [ %s ] 未审核，请审核后再进行拆分！", currentRow + 1, storagetransno));
            }
            DynamicObject datas = BusinessDataServiceHelper.loadSingle(object.getPkValue(), object.getDynamicObjectType().getName());
            //单车 全配件拆分
            DynamicObjectCollection materialinfo = datas.getDynamicObjectCollection("yem_es_materialinfo");
            //是否全配件
            boolean flag = true;
            for (DynamicObject dt : materialinfo) {
                String string = dt.getString("yem_businesssort");
                if ("Z".equals(string)) {
                    flag = false;
                }
            }
            //全配件
            List<BigDecimal> list = new ArrayList();
            if (flag) {
                //相同合同号合并数据(合同号，销售金额合并)
                HashMap<String, BigDecimal> constractData = new LinkedHashMap<>();
                BigDecimal count = BigDecimal.ZERO;
                for (DynamicObject dc : materialinfo) {
                    if (!dc.getBoolean("yem_ifgift")) {
                        count = count.add(dc.getBigDecimal("yem_saamtpriceclause"));
                        String contractnumbers = dc.getString("yem_contractnumbers_m");
                        String shipmentnumbers = dc.getString("yem_shipmentnumbers_m");
                        String newKey = contractnumbers + shipmentnumbers;
                        BigDecimal yemSaamtpriceclause = dc.getBigDecimal("yem_saamtpriceclause");
                        if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && !constractData.containsKey(newKey)) {
                            constractData.put(newKey, yemSaamtpriceclause);
                        } else if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && constractData.containsKey(newKey)) {
                            BigDecimal decimal = constractData.get(newKey);
                            if (decimal != null) {
                                constractData.put(newKey, decimal.add(yemSaamtpriceclause));
                            }
                        }
                    }
                }
                //拆分后的数据集合
                for (String key : constractData.keySet()) {
                    if (count.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal endAmount = yemApplyforamt.multiply(constractData.get(key)).divide(count, RoundingMode.UP);
                        list.add(endAmount);
                    }
                }
            } else {
                //有整机有配件
                HashMap<String, BigDecimal> constractData = new LinkedHashMap<>();
                BigDecimal count = BigDecimal.ZERO;
                for (DynamicObject dc : materialinfo) {
                    if ("Z".equals(dc.getString("yem_businesssort"))) {
                        count = count.add(dc.getBigDecimal("yem_saamtpriceclause"));
                        String contractnumbers = dc.getString("yem_contractnumbers_m");
                        String shipmentnumbers = dc.getString("yem_shipmentnumbers_m");
                        String newKey = contractnumbers + shipmentnumbers;
                        BigDecimal yemSaamtpriceclause = dc.getBigDecimal("yem_saamtpriceclause");
                        if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && !constractData.containsKey(newKey)) {
                            constractData.put(newKey, yemSaamtpriceclause);
                        } else if (YEM.isNotEmpty(contractnumbers) && YEM.isNotEmpty(shipmentnumbers) && constractData.containsKey(newKey)) {
                            BigDecimal decimal = constractData.get(newKey);
                            if (decimal != null) {
                                constractData.put(newKey, decimal.add(yemSaamtpriceclause));
                            }

                        }
                    }
                }
                for (String key : constractData.keySet()) {
                    if (count.compareTo(BigDecimal.ZERO) != 0) {
                        BigDecimal endAmount = yemApplyforamt.multiply(constractData.get(key)).divide(count, RoundingMode.UP);
                        list.add(endAmount);
                    }
                }

            }
            //申请金额 尾差处理
            BigDecimal countTemp = BigDecimal.ZERO;
            for (BigDecimal temp : list) {
                countTemp = countTemp.add(temp);
            }
            if (countTemp.compareTo(yemApplyforamt) < 0) {
                if (list.size() > 0) {
                    BigDecimal decimal = list.get(0);
                    list.set(0, decimal.add(yemApplyforamt.subtract(countTemp)));
                }
            }
            //反写给出口费用申请 拆分费用分录
            model.deleteEntryData("yem_splitcost");
            for (BigDecimal temp : list) {
                int rowIdx = model.createNewEntryRow("yem_splitcost");
                model.setValue("yem_applyamt_b", temp, rowIdx);
                model.setValue("yem_qtys", list.size(), rowIdx);
            }
        }
    }

    public void splitFee() {
        IFormView view = this.getView();
        FunctionalCommon.viewForm("yem_costsplit", null, view);
    }
}
