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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.es.Util.MaterialProperty;
import com.yem.wm.es.Util.MaterialVehicleNoCMMP;
import com.yem.wm.es.Util.ViewInterfaceDocking;
import com.yem.wm.es.Util.ZJUtils;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.RequestEAS;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.*;
import kd.bos.entity.property.EntryProp;
import kd.bos.exception.KDBizException;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.ComboEdit;
import kd.bos.form.field.ComboItem;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/8/10 17:13
 * @className tracktaskconsoleFormPlugIn
 * @description 跟单任务控制台表单插件
 */
public class tracktaskconsoleFormPlugIn extends AbstractBillPlugIn implements BeforeF7SelectListener {

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);
        FormShowParameter fsp = e.getFormShowParameter();
        String billtype = fsp.getFormConfig().getEntityTypeId();
        if (billtype != null) {
            String fromid = fsp.getFormId();
//            fsp.setFormId("yem_trackplace");
//            fsp.setCaption("产品经理下单确认");//
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
        if (yem_billtype != null) {
            String billtype = yem_billtype.getString("number");
            //分录配件生产信息 yem_es_salesorder_r
            // yem_stockway
            // 整机显示 现产 A 改制 B 外购	D
            //配件显示 自制 C 外购 D 调拨	E
            Map map = new HashMap<>();
            if (billtype.equals("yem_tracktaskconsole_zj")) {//整机
                map.put("现产", "A");
                map.put("改制", "B");
//                map.put("外购", "D");
                fillEntityCombo(map);
            }
            if (billtype.equals("yem_tracktaskconsole_pj")) {
                map.put("自制", "C");
                map.put("外购", "D");
                map.put("调拨", "E");
                map.put("库存", "F");
                fillEntityCombo(map);
            }
            Backcolor(billtype);
        }
    }

    /**
     * @param map 下拉项值
     */
    private void fillEntityCombo(Map<String, Object> map) {
        ComboEdit mainentry = (ComboEdit) this.getView().getControl("yem_stockway");
        if (map.size() > 0) {
            List<ComboItem> entryItems = this.buildEntryComboItems(map);
            mainentry.setComboItems(entryItems);
        } else {
            mainentry.setComboItems(null);
        }
    }

    /**
     * @param entitys
     * @return
     */
    private List<ComboItem> buildEntryComboItems(Map<String, Object> entitys) {
        ArrayList<ComboItem> entryItems = new ArrayList<>();
        ComboItem blankItem = new ComboItem();
        blankItem.setValue("");
        blankItem.setCaption(new LocaleString());
        entryItems.add(blankItem);
        if (entitys != null && entitys.size() > 0) {
            for (Map.Entry entry : entitys.entrySet()) {
                String mapKey = (String) entry.getKey();
                String mapValue = (String) entry.getValue();
                ComboItem entryItem = new ComboItem();
                entryItem.setValue(mapValue);
                entryItem.setCaption(new LocaleString(mapKey));
                entryItems.add(entryItem);
            }
        }
        return entryItems;
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (key.equals("carrystock")) {
            carrystock();
            this.getView().updateView("yem_es_materialinfo");
            this.getView().updateView("yem_es_salesorder_r");
            DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
            if (yem_billtype != null) {
                String billtype = yem_billtype.getString("number");
                Backcolor(billtype);
            }
            calcRemainingPushableOrderQuantity(this.getModel(), this.getView());
        }
        if (key.equals("splitrow")) {
            splitrow();
            this.getView().updateView("yem_es_materialinfo");
            this.getView().updateView("yem_es_salesorder_r");
            calcRemainingPushableOrderQuantity(this.getModel(), this.getView());
        }
        if (key.equals("deleteentry_bl")) {
            Quantityofstock();
            this.getView().updateView("yem_es_materialinfo");
            DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
            if (yem_billtype != null) {
                String billtype = yem_billtype.getString("number");
                Backcolor(billtype);
            }
//            Backcolor("");
        }
        if (key.equals("newproduction")) {
            newproduction();
            this.getView().updateView("yem_es_salesorder_z");
        }
        if (key.equals("getmachine")) {
            ZJUtils.renewMachineProductInfo(view, model);
//            renewMachineProductInfo();
        }
        if (key.equals("queryresourseplan")) {
            viewPlanPin("A");
        }
        if (key.equals("queryreformresourse")) {
            viewPlanPin("B");
        }
        if (key.equals("querystock")) {
            /**
             * 账龄赋值
             */
            DynamicObjectCollection yemEsMaterialinfo = (DynamicObjectCollection) this.getModel().getValue("yem_es_materialinfo");
            if (yemEsMaterialinfo.size() > 0) {
                for (int i = 0; i < yemEsMaterialinfo.size(); i++) {
                    DynamicObject yemMateriel = yemEsMaterialinfo.get(i).getDynamicObject("yem_materiel");
                    if (yemMateriel != null) {
                        String number = yemMateriel.getString("number");
                        QFilter qFilter = new QFilter("yem_materialentry.yem_materiel.number", QCP.equals, number);
                        qFilter.and(new QFilter("enable",QCP.equals,"1"));
                        String selectfield = DynamicObjectUtil.getSelectfields("yem_materialinventoryage", false);
                        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_materialinventoryage", "yem_materialentry", false);
                        DynamicObject[] load = BusinessDataServiceHelper.load("yem_materialinventoryage", selectfields, new QFilter[]{qFilter});
                        Date date = null;
                        if (load.length > 0) {
                            for (DynamicObject dynamicObject : load) {
                                Date yemBizdate = dynamicObject.getDate("yem_bizdate");
                                if (date != null) {
                                    if (date.compareTo(yemBizdate) < 0) {
                                        date = getDate(i, number, dynamicObject, yemBizdate);
                                    }
                                } else {
                                    date = getDate(i, number, dynamicObject, yemBizdate);
                                }
                            }
                        }else {
                            this.getModel().setValue("yem_ageingdata", 0, i);
                            this.getModel().setValue("yem_ageingdate", 0, i);
                            this.getModel().setValue("yem_ageing", 0, i);
                        }
                    }else {
                        this.getModel().setValue("yem_ageingdata", 0, i);
                        this.getModel().setValue("yem_ageingdate", 0, i);
                        this.getModel().setValue("yem_ageing", 0, i);
                    }
                }
            }

            EntryGrid materialinfo = this.getControl("yem_es_materialinfo");
            int[] selectRows = materialinfo.getSelectRows();
            if (selectRows.length == 0) {
                view.showErrorNotification("未选择数据");
            }
            DynamicObjectCollection materialEntries = (DynamicObjectCollection) this.getModel().getValue("yem_es_materialinfo");
            //产品类型
            DynamicObject yem_bd_products = (DynamicObject) model.getValue("yem_bd_products");
            for (int i : selectRows) {
                DynamicObject materialEntry = materialEntries.get(i);
                String materialNum = materialEntry.getString("yem_materiel.number");
                long materialNumid = materialEntry.getLong("yem_materiel.id");
                //已采购
                BigDecimal yem_buyfromcmmp = getbuyfromcmmp(materialNum, yem_bd_products);
                model.setValue("yem_buyfromcmmp", yem_buyfromcmmp, i);
                //储备
                DynamicObjectCollection yem_accreserveapply = QueryServiceHelper.query("yem_accreserveapply", "yem_detailinfo.yem_qty", new QFilter[]{new QFilter("yem_detailinfo.yem_materiel.id", QCP.equals, materialNumid), new QFilter("status", QCP.equals, "C")}, "yem_audittime desc", 1);
                if (yem_accreserveapply != null && yem_accreserveapply.size() > 0) {
                    model.setValue("yem_accreserveqty", yem_accreserveapply.get(0).getBigDecimal("yem_detailinfo.yem_qty"), i);
                }
                //VMI-eas数量+CMMP数量
                BigDecimal easyem_vmiqty = getSumEASqty(materialNum, "V");
                BigDecimal cmmpyem_vmiqty = getSumCMMPQty(materialNum, "V", yem_bd_products);
                model.setValue("yem_vmiqty", easyem_vmiqty.add(cmmpyem_vmiqty), i);
                //正常仓库
                BigDecimal easyem_normalqty = getSumEASqty(materialNum, "C");
                BigDecimal cmmpyem_normalqty = getSumCMMPQty(materialNum, "C", yem_bd_products);
                model.setValue("yem_normalqty", easyem_normalqty.add(cmmpyem_normalqty), i);
                //制造中心库
                BigDecimal easyem_zzzxqty = getSumEASqty(materialNum, "Z");
                BigDecimal cmmpyem_zzzxqty = getSumCMMPQty(materialNum, "Z", yem_bd_products);
                model.setValue("yem_zzzxqty", easyem_zzzxqty.add(cmmpyem_zzzxqty), i);
                //国贸配件库
                BigDecimal easyem_gmpjqty = getSumEASqty(materialNum, "D");
                BigDecimal cmmpyem_gmpjqty = getSumCMMPQty(materialNum, "D", yem_bd_products);
                model.setValue("yem_gmpjqty", easyem_gmpjqty.add(cmmpyem_gmpjqty), i);
                BigDecimal tolreqqty = gettolreqqty(yem_bd_products, materialNumid);
                model.setValue("yem_tolreqqty", tolreqqty, i);
                //处理库存差
                BigDecimal yem_qtysub = easyem_gmpjqty.add(cmmpyem_gmpjqty).add(yem_buyfromcmmp).subtract(tolreqqty);
                model.setValue("yem_qtysub", yem_qtysub, i);
            }
            this.getView().showMessage("查询库存成功！");
            this.getView().invokeOperation("save");
        }
        if (key.equals("pjstorequery")) {
            pjstorequery(e);
        }
        if (key.equals("getmaterialprop")) {
            DynamicObject yemBdProducts = (DynamicObject) this.getModel().getValue("yem_bd_products");
            long cpflid = yemBdProducts.getLong("id");
            DynamicObjectCollection materialEntries = (DynamicObjectCollection) this.getModel().getValue("yem_es_materialinfo");
            HashMap<String, Object> map = new HashMap<>();
            for (int i = 0; i < materialEntries.size(); i++) {
                DynamicObject materialEntry = materialEntries.get(i);
                map.put(MaterialProperty.materialcode, materialEntry.getString("yem_materiel.number"));
                List<Map> docking = ViewInterfaceDocking.docking(ViewInterfaceDocking.MATERIAL_PROPERTY, map, cpflid);
                for (Map map1 : docking) {
                    model.setValue("yem_materialprop", map1.get(MaterialProperty.materialProperty), i);
                }
            }
        }
    }

    /**
     * 账龄赋值
     * @param i
     * @param number
     * @param dynamicObject
     * @param yemBizdate
     * @return
     */
    private Date getDate(int i, String number, DynamicObject dynamicObject, Date yemBizdate) {
        Date date;
        date = yemBizdate;
        DynamicObjectCollection dynamicObjectCollection = dynamicObject.getDynamicObjectCollection("yem_materialentry");
        if (dynamicObjectCollection.size() > 0) {
            for (DynamicObject object : dynamicObjectCollection) {
                DynamicObject yem_materiel = object.getDynamicObject("yem_materiel");
                if (yem_materiel != null) {
                    String yem_materielnumber = yem_materiel.getString("number");
                    if (yem_materielnumber.equals(number)) {
                        BigDecimal yemAge1 = object.getBigDecimal("yem_age1");
                        BigDecimal yemAge2 = object.getBigDecimal("yem_age2");
                        BigDecimal yemAge3 = object.getBigDecimal("yem_age3");
                        this.getModel().setValue("yem_ageingdata", yemAge1, i);
                        this.getModel().setValue("yem_ageingdate", yemAge2, i);
                        this.getModel().setValue("yem_ageing", yemAge3, i);
                    }
                }
            }
        }
        return date;
    }

    /**
     * 配件库存查询
     */
    private void pjstorequery(AfterDoOperationEventArgs e) {
        //获取单据体控件
        EntryGrid entryGrid = this.getControl("yem_es_salesorder_r");
        //获取选中行，数组为行号，从0开始int[]
        //获取单据体数据集合
        DynamicObjectCollection entitys = this.getModel().getEntryEntity("yem_es_salesorder_r");//生产采购
        int selectRows[] = entryGrid.getSelectRows();
        if (selectRows != null && selectRows.length == 1) {
            FormShowParameter fsp = new FormShowParameter();
            fsp.setFormId("yem_accessorystorequery");
            //获取物料
            DynamicObject entry = entitys.get(selectRows[0]);
            long materialid = entry.getLong("yem_materielg.id");
            fsp.setCustomParam("materialid", materialid);
            //物料编码
            String materialnum = entry.getString("yem_materielg.number");
            fsp.setCustomParam("materialnum", materialnum);
            //获取商品分录数量
            DynamicObjectCollection goodColl = this.getModel().getEntryEntity("yem_es_materialinfo");
            BigDecimal yem_inqureqty = BigDecimal.ZERO;
            for (DynamicObject goodObj : goodColl) {
                if (materialid == goodObj.getLong("yem_materiel.id")) {
                    yem_inqureqty = yem_inqureqty.add(goodObj.getBigDecimal("yem_qty"));
                }
            }
            fsp.setCustomParam("yem_inqureqty", yem_inqureqty);
            //备料方式必须为调拨
            if (!"E".equals(entry.getString("yem_stockway"))) {
                this.getView().showErrorNotification("所选行必须为调拨才可查询库存！");
                return;
            }
            fsp.setCustomParam("yem_stockway", entry.getString("yem_stockway"));
            //获取yem_isvmi仓库类型
            String yem_isvmi = entry.getString("yem_isvmi");
            if (yem_isvmi == null) {
                this.getView().showErrorNotification("请选择所选行仓库类型！");
                return;
            }
            fsp.setCustomParam("yem_isvmi", yem_isvmi);
            HashMap<String, BigDecimal> map = new HashMap<>();
            //获取所有该物料的仓库
            for (DynamicObject entity : entitys) {
                //如果仓库类型一致、物料一直则添加仓库及数量
                if (yem_isvmi.equals(entity.getString("yem_isvmi")) && materialid == entity.getLong("yem_materielg.id")) {
                    //仓库空处理
                    //获取备料数量yem_stockqty
                    //仓库ID，数量
                    //获取仓库
                    if (entity.getString("yem_outhouse.number") != null) {
                        if (map.containsKey(entity.getString("yem_outhouse.number"))) {

                            map.put(entity.getString("yem_outhouse.number"),
                                    ((BigDecimal) map.get(entity.getString("yem_outhouse.number"))).add(entity.getBigDecimal("yem_stockqty")));
                        } else {
                            map.put(entity.getString("yem_outhouse.number"), entity.getBigDecimal("yem_stockqty"));
                        }
                    }
                }
            }

            fsp.setCustomParam("map", map);
            fsp.getOpenStyle().setShowType(ShowType.Modal);
            fsp.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "yem_accessorystorequery"));
            this.getView().showForm(fsp);
        } else {
            getView().showErrorNotification("请选择一行进行查询");
        }

    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        Object returnData = e.getReturnData();
        IFormView view = this.getView();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (actionId.equals("yem_accessorystorequery")) {
            ArrayList<Map<String, Object>> list = (ArrayList<Map<String, Object>>) returnData;
            System.out.println(list);
            String yem_isvmi = "";
            String yem_stockway = "";
            long yem_materielg = 0l;
            if (list != null) {
                for (int j = 0; j < list.size(); j++) {
                    Map<String, Object> map = list.get(j);
                    yem_materielg = (long) map.get("yem_materielg");
                    yem_isvmi = (String) map.get("yem_isvmi");
                    long yem_outhouse = (long) map.get("yem_outhouse");
                    int yem_stockqty = (int) map.get("yem_stockqty");
                    yem_isvmi = (String) map.get("yem_isvmi");
                    yem_stockway = (String) map.get("yem_stockway");
                    int erowcount = model.getEntryRowCount("yem_es_salesorder_r");
                    for (int i = 0; i < erowcount; i++) {
                        DynamicObject yem_materielg1 = (DynamicObject) model.getValue("yem_materielg", i);
                        DynamicObject yem_outhouse1 = (DynamicObject) model.getValue("yem_outhouse", i);
                        long yem_materielg1id = 0;
                        long yem_outhouse1id = 0;
                        if (yem_outhouse1 != null) yem_outhouse1id = yem_outhouse1.getLong("id");
                        if (yem_materielg1 != null) yem_materielg1id = yem_materielg1.getLong("id");
                        String yem_isvmi1 = (String) model.getValue("yem_isvmi", i);
                        String yem_stockway1 = (String) model.getValue("yem_stockway", i);
                        if (yem_isvmi.equals(yem_isvmi1) && yem_materielg == yem_materielg1id && yem_outhouse == yem_outhouse1id && yem_stockway1.equals(yem_stockway)) {
                            model.setValue("yem_stockqty", yem_stockqty, i);
                            list.remove(j);
                            j--;
                            break;
                        } else if (yem_outhouse1id == 0 && yem_isvmi.equals(yem_isvmi1) && yem_materielg == yem_materielg1id && yem_stockway1.equals(yem_stockway)) {
                            model.setValue("yem_stockqty", yem_stockqty, i);
                            model.setValue("yem_outhouse", yem_outhouse, i);
                            list.remove(j);
                            j--;
                            break;
                        }
                    }

                }
                //删除备料方式、仓库类型、物料且调出仓库为空的数据
                delEntryWithStockwayAOuthouse(model, yem_isvmi, yem_stockway, yem_materielg);
                //新增行
                for (int i = 0; i < list.size(); i++) {
                    //新增行
                    Map<String, Object> map = list.get(i);
                    yem_materielg = (long) map.get("yem_materielg");
                    long yem_outhouse = (long) map.get("yem_outhouse");
                    int yem_stockqty = (int) map.get("yem_stockqty");
                    if (yem_stockqty == 0) continue;
                    splitrow();
                    //遍历分录，获取物料一致，备料方式为空、仓库类型为空的数据
                    int erowcount = model.getEntryRowCount("yem_es_salesorder_r");
                    for (int j = 0; j < erowcount; j++) {
                        //物料
                        DynamicObject yemMaterielg = (DynamicObject) model.getValue("yem_materielg", j);
                        long materialid = 0l;
                        if (yemMaterielg != null) {
                            materialid = yemMaterielg.getLong("id");
                        }
                        //备料方式
                        String yem_stockway1 = (String) model.getValue("yem_stockway", j);
                        //备料方式
                        String yem_isvmi1 = (String) model.getValue("yem_isvmi", j);
                        if (materialid == yem_materielg && yem_stockway1 == null && yem_isvmi1 == null) {
                            model.setValue("yem_stockqty", yem_stockqty, j);
                            model.setValue("yem_isvmi", yem_isvmi, j);
                            model.setValue("yem_outhouse", yem_outhouse, j);
                            model.setValue("yem_stockway", yem_stockway, j);
                        }
                    }

                }
            }
            Quantityofstock();
            view.updateView("yem_es_salesorder_r");
        }
    }

    private static void delEntryWithStockwayAOuthouse(IDataModel model, String yem_isvmi, String yem_stockway, long yem_materielg) {
        int erowcount = model.getEntryRowCount("yem_es_salesorder_r");
        for (int i = 0; i < erowcount; i++) {
            DynamicObject mat = (DynamicObject) model.getValue("yem_materielg", i);
            long aLong = mat.getLong("id");
            if (yem_materielg == aLong && yem_isvmi.equals(model.getValue("yem_isvmi", i)) && yem_stockway.equals(model.getValue("yem_stockway", i)) && model.getValue("yem_outhouse", i) == null) {
                model.deleteEntryRow("yem_es_salesorder_r", i);
                erowcount--;
            }
        }
    }

    public static BigDecimal gettolreqqty(DynamicObject products, long materialNumid) {
//        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        List<Long> productId = getProductId(products);
        //备料（生产、采购）信息中(除本订单之外的)汇总
        DynamicObject[] yem_stockqtys = BusinessDataServiceHelper.load("yem_tracktaskconsole",
                "yem_es_materialinfo.yem_qty, yem_es_materialinfo.yem_materiel", new QFilter[]{
                        new QFilter("yem_es_materialinfo.yem_materiel.id", QCP.equals, materialNumid),
                        new QFilter("yem_bd_products.id", QCP.in, productId)
        });
        BigDecimal stockqty = BigDecimal.ZERO;
        for (DynamicObject yemStockqty : yem_stockqtys) {
            DynamicObjectCollection collection = yemStockqty.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                long materiel = dynamicObject.getLong("yem_materiel.id");
                if (materiel == materialNumid) {
                    stockqty = stockqty.add(qty);
                }
            }
        }
        //调拨订单中调出仓库的仓库分类为（国贸各事业部仓库）的yem_qty(yem_iseas=true)
        //获取仓库分类为（国贸各事业部仓库）id集合
        DynamicObjectCollection whColl = QueryServiceHelper.query("yem_warehouse", "id",
                new QFilter[]{new QFilter("yem_sort", QCP.equals, "D"),
                        new QFilter("enable", QCP.equals, "1")});
        ArrayList<Long> whids = new ArrayList<>();
        for (DynamicObject wh : whColl) {
            whids.add(wh.getLong("id"));
        }
        DynamicObject[] transqtyColl = BusinessDataServiceHelper.load("yem_transferorder", "billno, billstatus, yem_es_materialinfo.yem_qty, yem_es_materialinfo.yem_materiel", new QFilter[]{
                new QFilter("yem_es_materialinfo.yem_entryoutwarehouse.id", QCP.in, whids),//调出仓库的仓库分类为（国贸各事业部仓库）
                new QFilter("yem_es_materialinfo.yem_materiel.id", QCP.equals, materialNumid),//物料
//                new QFilter("yem_iseas", QCP.equals, true),//已同步EAS
                new QFilter("yem_bd_products.id", QCP.in, productId),
                new QFilter("billstatus", "=", "C")
        });
        BigDecimal transQty = BigDecimal.ZERO;
        for (DynamicObject transObj : transqtyColl) {
            DynamicObjectCollection collection = transObj.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                long materiel = dynamicObject.getLong("yem_materiel.id");
                if (materiel == materialNumid) {
                    transQty = transQty.add(qty);
                }

            }
        }
        return stockqty.subtract(transQty);
    }

    private static List<Long> getProductId(DynamicObject products) {
        String type = products.getDataEntityType().getName();
        String number = products.getString("number");
        DynamicObject[] load = null;
        if (number.contains("CC")) {
            load = BusinessDataServiceHelper.load(type, "id", new QFilter[]{new QFilter("number", QCP.in, new String[]{"CC", "CCPJ"})});
        }

        if (number.contains("ZZJ")) {
            load = BusinessDataServiceHelper.load(type, "id", new QFilter[]{new QFilter("number", QCP.in, new String[]{"ZZJ", "ZZJPJ"})});
        }

        if (number.contains("TLJ")) {
            load = BusinessDataServiceHelper.load(type, "id", new QFilter[]{new QFilter("number", QCP.in, new String[]{"TLJ", "TLJPJ"})});
        }
        List<Long> ids = new ArrayList<>();
        if (load != null) {
            for (DynamicObject dynamicObject : load) {
                ids.add(dynamicObject.getLong("id"));
            }
        }
        return ids;
    }

    /**
     * 查询已采购数量
     *
     * @param materialNum
     * @param yemBdProducts
     * @return
     */
    private BigDecimal getbuyfromcmmp(String materialNum, DynamicObject yemBdProducts) {
        //产品类型ID获取CMMP链接
        yemBdProducts = BusinessDataServiceHelper.loadSingle(yemBdProducts.getLong("id"), yemBdProducts.getDynamicObjectType().getName());
        Long topCplxid = RequestCmmp.getTopCplx(yemBdProducts);
        DynamicObject cmmpConn = QueryServiceHelper.queryOne("yem_cmmpconfig", "id", new QFilter[]{new QFilter("yem_cmmpconfigentry.yem_bd_productsgroupn.id", QCP.equals, topCplxid)});
        String sql1 = "SELECT sum(order_this) a from VIEW_APPLY_ENROUTE_WM where mater_code='" + materialNum + "' GROUP BY mater_code";
        List<Map> need_numlist = RequestCmmp.getFromCmmpWithConnId(cmmpConn.getLong("id"), sql1);
        BigDecimal needNum = BigDecimal.ZERO;
        for (Map map : need_numlist) {
            if (map.get("a") != null) {
                needNum = (BigDecimal) map.get("a");
            }
        }
        String sql2 = "SELECT sum(instock_qty) b from VIEW_APPLY_ENROUTE_WM where mater_code='" + materialNum + "' GROUP BY mater_code";
        List<Map> instock_qtylist = RequestCmmp.getFromCmmpWithConnId(cmmpConn.getLong("id"), sql2);
        BigDecimal instock_qty = BigDecimal.ZERO;
        for (Map map : instock_qtylist) {
            if (map.get("b") != null) {
                instock_qty = (BigDecimal) map.get("b");
            }
        }
        String sql3 = "SELECT sum(close_qty) c from VIEW_APPLY_ENROUTE_WM where mater_code='" + materialNum + "' GROUP BY mater_code";
        List<Map> close_qtylist = RequestCmmp.getFromCmmpWithConnId(cmmpConn.getLong("id"), sql3);
        BigDecimal close_qty = BigDecimal.ZERO;
        for (Map map : close_qtylist) {
            if (map.get("c") != null) {
                close_qty = (BigDecimal) map.get("c");
            }
        }
        return needNum.subtract(instock_qty).add(close_qty);
    }

    /**
     * @param materialNum     物料编码
     * @param a               仓库分类
     * @param yem_bd_products
     * @return
     */
    private BigDecimal getSumCMMPQty(String materialNum, String a, DynamicObject yem_bd_products) {
        //产品类型ID获取CMMP链接
        yem_bd_products = BusinessDataServiceHelper.loadSingle(yem_bd_products.getLong("id"), yem_bd_products.getDynamicObjectType().getName());
        Long topCplxid = RequestCmmp.getTopCplx(yem_bd_products);
        DynamicObject cmmpConn = QueryServiceHelper.queryOne("yem_cmmpconfig", "id", new QFilter[]{new QFilter("yem_cmmpconfigentry.yem_bd_productsgroupn.id", QCP.equals, topCplxid)});
        //通过CMMP链接跟仓库分类获取仓库
        DynamicObjectCollection whs = QueryServiceHelper.query("yem_warehouse", "number",
                new QFilter[]{new QFilter("yem_cmmpconfig.id", QCP.equals, cmmpConn.getLong("id")),
                        new QFilter("yem_sort", QCP.equals, a),
                        new QFilter("enable", QCP.equals, "1")});
        StringBuilder whsb = new StringBuilder();
        for (DynamicObject wh : whs) {
            whsb.append("'" + wh.getString("number") + "',");
        }
        whsb.append("''");
        String sql = "SELECT sum(canuse_num) from VIEW_MATER_STOCK_WM where MATER_CODE='" + materialNum + "' " + "and wh_code in(" + whsb.toString() + ") GROUP BY MATER_CODE";
        List<Map> canuse_nums = RequestCmmp.getFromCmmp(null, sql, yem_bd_products.getLong("id"));
        BigDecimal canuse_num = BigDecimal.ZERO;
        for (Map canuseNum : canuse_nums) {
            BigDecimal b = (BigDecimal) canuseNum.get("sum(canuse_num)");
            if (b == null) {
                canuse_num = canuse_num.add(BigDecimal.ZERO);
            } else {
                canuse_num = canuse_num.add(b);
            }
        }
        return canuse_num;
    }

    /**
     * @param materialNum 物料编码
     * @param a           仓库分类
     * @return
     */
    private BigDecimal getSumEASqty(String materialNum, String a) {
        //通过仓库分类查询所有EAS的仓库
        DynamicObjectCollection whs = QueryServiceHelper.query("yem_warehouse", "id,useorg.number,number",
                new QFilter[]{new QFilter("yem_belong", QCP.equals, "A"), new QFilter("yem_sort", QCP.equals, a),
                        new QFilter("enable", QCP.equals, "1")});
        JSONArray storageOrgs = new JSONArray();
        Set storageOrgs1 = new HashSet();
        Set warehouses1 = new HashSet();
        JSONArray warehouses = new JSONArray();
        for (DynamicObject wh : whs) {
            String useorgnum = wh.getString("useorg.number");
            storageOrgs1.add(useorgnum);
            String whnum = wh.getString("number");
            warehouses1.add(whnum);
        }
        for (Object o : storageOrgs1) {
            storageOrgs.add(o);
        }
        for (Object o : warehouses1) {
            warehouses.add(o);
        }
        if (whs.size() == 0) {
            return BigDecimal.ZERO;
        }
        JSONObject json = new JSONObject();
        json.put("start", 0);
        json.put("len", 1000);
        json.put("storageOrgs", storageOrgs);
        json.put("warehouses", warehouses);
        json.put("materialNumFrom", materialNum);//物料起--必填
        json.put("materialNumTo", materialNum);//物料止--必填
        String s = RequestEAS.InventoryListServiceFacadeGetData(json.toString());
        JSONObject result = JSONObject.parseObject(s);
        JSONArray list = result.getJSONArray("list");
        BigDecimal qty = BigDecimal.ZERO;
        if (list.size() == 1000) {
            json.put("start", (json.getIntValue("start") + 1) * json.getIntValue("len"));
            s = RequestEAS.InventoryListServiceFacadeGetData(json.toString());
            result = JSONObject.parseObject(s);
            list.addAll(result.getJSONArray("list"));
        }
        for (int i = 0; i < list.size(); i++) {
            JSONObject o = (JSONObject) list.get(i);
            BigDecimal fRealQty = o.getBigDecimal("FRealQty");
            if (fRealQty == null) {
                qty = qty.add(BigDecimal.ZERO);
            } else {
                qty = qty.add(fRealQty);
            }
        }
        return qty;
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit yem_reformresources = this.getControl("yem_reformresources");
        yem_reformresources.addBeforeF7SelectListener(this);
    }


    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        super.afterDeleteRow(e);
    }

    @Override
    public void afterDeleteEntry(AfterDeleteEntryEventArgs e) {
        super.afterDeleteEntry(e);
//        String key = e.getEntryProp().getName();
//        if(key.equals("yem_es_salesorder_r")){
//            Quantityofstock();
//        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IDataModel model = this.getModel();
        String fieldKey = e.getProperty().getName();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        ChangeData changeData = e.getChangeSet()[0];
        Object newValue = changeData.getNewValue();
//        int rowIndex = model.getEntryCurrentRowIndex("yem_invoicing_entry");
        if (fieldKey.equals("yem_stockqty")) {
            Quantityofstock();
            this.getView().updateView("yem_es_materialinfo");
//            this.getView().updateView("yem_es_salesorder_r");
        }

        int rowIndex = e.getChangeSet()[0].getRowIndex();
        if ("yem_ifreformg".equals(e.getProperty().getName())) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            collection.get(rowIndex).set("yem_reformdesg", null);
            this.getView().updateView();
        }
        if ("yem_impactprice1".equals(fieldKey)) {
            DynamicObjectCollection esMaterialinfo = model.getDataEntity().getDynamicObjectCollection("yem_es_materialinfo");
            for (int i = 0; i < esMaterialinfo.size(); i++) {
                DynamicObjectCollection multiconfig = esMaterialinfo.get(i).getDynamicObjectCollection("yem_multiconfig");
                Set<Boolean> set = new HashSet<>();
                for (DynamicObject object : multiconfig) {
                    // 影响调拨价
                    String impactprice1 = object.getString("yem_impactprice1");
                    set.add("A".equals(impactprice1));
                    if ("A".equals(impactprice1)) {
                        model.setValue("yem_impactprice", "A", i);
                    }
                    if (!set.contains(true)) {
                        model.setValue("yem_impactprice", "B", i);
                    }
                }
            }
        }

        if ("yem_stockqty".equals(fieldKey)) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");
            DynamicObject dynamicObject = collection.get(rowIndex);
            BigDecimal stockqty = dynamicObject.getBigDecimal("yem_stockqty");
            BigDecimal qtyfield6 = dynamicObject.getBigDecimal("yem_qtyfield6");
            BigDecimal closecount = dynamicObject.getBigDecimal("yem_closecount");
            if (stockqty.compareTo(qtyfield6.subtract(closecount)) < 0) {
                this.getView().showErrorNotification("备料信息第 " + (rowIndex + 1) + " 行，备料数量不能小于 关联订单产品需求单数量 - 关闭数量！");
            }
        }
        if ("yem_stockway".equals(fieldKey)) {
            DynamicObject yem_billtype = (DynamicObject) model.getValue("yem_billtype");
            if (yem_billtype != null) {
                String string = yem_billtype.getString("number");
                if ("yem_tracktaskconsole_pj".equals(string)) {
                    if (newValue.equals("E")) {
                        this.getView().setEnable(true, rowIndex, "yem_isvmi");
                    } else {
                        this.getView().setEnable(false, rowIndex, "yem_isvmi");
                    }
                }
            }
        }
    }

    /**
     * 执行备料
     */
    public void carrystock() {
        //获取单据体控件
        EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
        //获取选中行，数组为行号，从0开始int[]
        int selectRows[] = entryGrid.getSelectRows();
        //获取单据体数据集合
        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_es_salesorder_r = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");//备料（生产、采购）信息数据
        if (selectRows != null && selectRows.length > 0) {
            String yem_contracttype = dataEntity.getString("yem_contracttype");
            if (yem_contracttype.equals("yem_es_salesorder_ZJ") || yem_contracttype.equals("yem_es_salesorder_nmzj")) {
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    String yem_productstat = dynamicObject.getString("yem_productstat");
                    DynamicObject yemOrderholder = dynamicObject.getDynamicObject("yem_orderholder");
                    String seq = dynamicObject.getString("seq");
                    if (yemOrderholder == null) {//未确认
                        getView().showErrorNotification("选中行第【" + seq + "】行产品经理没有进行下单确认，不能进行备料！");
                        return;
                    }
                }
            }
//            //判断选中行是否已确认
//            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");
//            if (yemBilltype != null) {
//                String number = yemBilltype.getString("number");
//                if (number.equals("yem_tracktaskconsole_zj")) {
//
//                }
//            }
            int jr = 0;
            for (int selectRow : selectRows) {
                DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                BigDecimal yem_qty = dynamicObject.getBigDecimal("yem_qty");//数量
                BigDecimal yem_hqty = dynamicObject.getBigDecimal("yem_hqty");//已备料数量
                BigDecimal yem_nqty = dynamicObject.getBigDecimal("yem_nqty");//未备料数量
                if (yem_nqty.compareTo(BigDecimal.ZERO) == 0) {
                    jr++;
                    continue;
                }
                if (yem_hqty.compareTo(BigDecimal.ZERO) == 0) {
                    //插入备料（生产、采购）信息数据
                    DynamicObject salesorder = yem_es_salesorder_r.addNew();
                    AddrowData(dynamicObject, salesorder);
                } else
                //if (yem_hqty.compareTo(BigDecimal.ZERO) > 0 && yem_nqty.compareTo(yem_qty) == 1)
                {
                    InsetData(yem_es_salesorder_r, dynamicObject.getLong("id"), dynamicObject);
                }
            }
            if (jr == selectRows.length) {
                this.getView().showMessage("【未备料数量】为0，禁止拆分！");
            }
            Quantityofstock();
            if (yem_contracttype.equals("yem_es_salesorder_ZJ") || yem_contracttype.equals("yem_es_salesorder_nmzj")) {
                updateimpactprice();
            }

        } else {
            throw new KDBizException("请选择最少一行数据进行备料");
        }
    }

    /**
     * 汇总已备料数量
     */
    public void Quantityofstock() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection entity = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");//商品
        DynamicObjectCollection yem_es_salesorder_r = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");//备料（生产、采购）信息数据
        ArrayList<Integer> rows = new ArrayList<>();
        for (int i = 0; i < entity.size(); i++) {
            DynamicObject materialinfo = entity.get(i);
            BigDecimal yem_qty = materialinfo.getBigDecimal("yem_qty");//数量
            long fentryid = materialinfo.getLong("id");
            BigDecimal hqty = BigDecimal.ZERO;//已备料
            BigDecimal nqty = BigDecimal.ZERO;//未备料
            for (int k = 0; k < yem_es_salesorder_r.size(); k++) {
                DynamicObject salesorder = yem_es_salesorder_r.get(k);
                long yem_entrtyid = salesorder.getLong("yem_entrtyid");
                if (fentryid == yem_entrtyid) {
                    hqty = hqty.add(salesorder.getBigDecimal("yem_stockqty"));
                }
            }
            materialinfo.set("yem_hqty", hqty);//已备料
            materialinfo.set("yem_nqty", yem_qty.subtract(hqty));//未备料

            if (yem_qty.subtract(hqty).compareTo(BigDecimal.ZERO) > 0) {
                rows.add(i);
            }
        }

        EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
        entryGrid.setRowBackcolor("rgba(251,35,35,0.1)", rows.stream().mapToInt(Integer::intValue).toArray());
    }

    /**
     * 插入数据
     *
     * @param salesorder    备料信息实体
     * @param yem_entrtyid  商品分录id
     * @param dynamicObject 选中数据
     */
    public void InsetData(DynamicObjectCollection salesorder, long yem_entrtyid, DynamicObject dynamicObject) {
        int row = 0;
        for (int i = 0; i < salesorder.size(); i++) {
            DynamicObject Object = salesorder.get(i);
            if (yem_entrtyid == Object.getLong("yem_entrtyid")) {
                row = i;
            }
        }
        DynamicObject date = new DynamicObject(salesorder.getDynamicObjectType());
        if (dynamicObject.getDynamicObject("yem_resourcenog") != null) {
            date.set("yem_resourceno", dynamicObject.getDynamicObject("yem_resourcenog"));
            date.set("yem_productmodelb", dynamicObject.getDynamicObject("yem_resourcenog").getDynamicObject("yem_products"));//产品机型
        }

        date.set("yem_materielg", dynamicObject.getDynamicObject("yem_materiel"));
        date.set("yem_stockqty", dynamicObject.getBigDecimal("yem_nqty"));//备料数量
        date.set("yem_stockunit", dynamicObject.getDynamicObject("yem_unit"));//计量单位
        date.set("yem_stockbaseunit", dynamicObject.getDynamicObject("yem_baseunit"));//基本计量单位
        date.set("yem_stockbaseqty", dynamicObject.getBigDecimal("yem_nqty"));//基本计量单位
        date.set("yem_orderallocation1", dynamicObject.getString("yem_orderallocation"));//订单配置要求
        date.set("yem_orderallocationen1", dynamicObject.getString("yem_orderallocationen"));//配置英文描述
        date.set("yem_productmodel1", dynamicObject.getDynamicObject("yem_productmodel"));//基础机型
        date.set("yem_ifreformg1", dynamicObject.getString("yem_ifreformg"));//是否改制
        date.set("yem_reformdesg1", dynamicObject.getString("yem_reformdesg"));//改制描述
        date.set("yem_projectdesc1", dynamicObject.getString("yem_projectdesc"));//加装方案说明
        date.set("yem_ifsupportg1", dynamicObject.getString("yem_ifsupportg"));//是否技术支持
        date.set("yem_reqputstordate", this.getModel().getValue("yem_acshipdate"));//要求入库时间
        date.set("yem_entrtyid", dynamicObject.getLong("id"));
        date.set("yem_color_e", dynamicObject.getString("yem_color"));
        salesorder.add(row + 1, date);
    }

    /**
     * 新增备料（生产、采购）信息数据
     *
     * @param dynamicObject 商品明细数据
     * @param salesorder    待插入数据
     */
    public void AddrowData(DynamicObject dynamicObject, DynamicObject salesorder) {
//        salesorder.set("yem_typeconfigurationb", dynamicObject.getDynamicObject("yem_materiel").getString("yem_zhdescription"));
        if (dynamicObject.getDynamicObject("yem_resourcenog") != null) {
            salesorder.set("yem_resourceno", dynamicObject.getDynamicObject("yem_resourcenog"));
            salesorder.set("yem_productmodelb", dynamicObject.getDynamicObject("yem_resourcenog").getDynamicObject("yem_products"));//产品机型
        }

        salesorder.set("yem_materielg", dynamicObject.getDynamicObject("yem_materiel"));
        salesorder.set("yem_stockqty", dynamicObject.getBigDecimal("yem_nqty"));//备料数量
        salesorder.set("yem_stockunit", dynamicObject.getDynamicObject("yem_unit"));//计量单位
        salesorder.set("yem_stockbaseunit", dynamicObject.getDynamicObject("yem_baseunit"));//基本计量单位
        salesorder.set("yem_stockbaseqty", dynamicObject.getBigDecimal("yem_baseqty"));//基本计量单位
        salesorder.set("yem_orderallocation1", dynamicObject.getString("yem_orderallocation"));//订单配置要求
        salesorder.set("yem_orderallocationen1", dynamicObject.getString("yem_orderallocationen"));//配置英文描述
        salesorder.set("yem_productmodel1", dynamicObject.getDynamicObject("yem_productmodel"));//基础机型
        salesorder.set("yem_ifreformg1", dynamicObject.getString("yem_ifreformg"));//是否改制
        salesorder.set("yem_reformdesg1", dynamicObject.getString("yem_reformdesg"));//改制描述
        salesorder.set("yem_projectdesc1", dynamicObject.getString("yem_projectdesc"));//加装方案说明
        salesorder.set("yem_ifsupportg1", dynamicObject.getString("yem_ifsupportg"));//是否技术支持
        salesorder.set("yem_materialper", dynamicObject.getString("yem_materialprop"));//物料属性
        salesorder.set("yem_reqputstordate", this.getModel().getValue("yem_acshipdate"));//要求入库时间
        salesorder.set("yem_entrtyid", dynamicObject.getLong("id"));
//        calcRemainingPushableOrderQuantity(this.getModel(), this.getView());
        salesorder.set("yem_color_e", dynamicObject.getString("yem_color"));//颜色
    }

    /**
     * 计算剩余可下推订单数量
     */
    private void calcRemainingPushableOrderQuantity(IDataModel model, IFormView view) {
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");
        for (DynamicObject dynamicObject : collection) {
            // 备料数量
            BigDecimal stockqty = dynamicObject.getBigDecimal("yem_stockqty");
            // 关联订单需求表数量
            BigDecimal qtyfield6 = dynamicObject.getBigDecimal("yem_qtyfield6");
            // 关闭数量
            BigDecimal closecount = dynamicObject.getBigDecimal("yem_closecount");
            dynamicObject.set("yem_lastcanorderqty", stockqty.subtract(qtyfield6).add(closecount));
        }
        view.updateView("yem_es_salesorder_r");
    }

    /**
     * 拆分备料分录行
     */
    public void splitrow() {
        //获取单据体控件
        EntryGrid entryGrid = this.getControl("yem_es_salesorder_r");
        //获取选中行，数组为行号，从0开始int[]
        int selectRows[] = entryGrid.getSelectRows();
        //获取单据体数据集合
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
//        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_salesorder_r");//备料（生产、采购）信息数据
        DynamicObjectCollection entity = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");//备料（生产、采购）信息数据
        DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");//商品信息
        if (selectRows != null && selectRows.length > 0) {
            if (selectRows.length == 1) {
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    long yem_entrtyid = dynamicObject.getLong("yem_entrtyid");
                    BigDecimal nqty = BigDecimal.ZERO;
                    for (int i = 0; i < yem_es_materialinfo.size(); i++) {
                        DynamicObject materialinfo = yem_es_materialinfo.get(i);
                        if (yem_entrtyid == materialinfo.getLong("id")) {
                            nqty = materialinfo.getBigDecimal("yem_nqty");
                            if (nqty.compareTo(BigDecimal.ZERO) <= 0) {
                                this.getView().showMessage("当前行已备料完毕，禁止拆分!");
                            }
                            break;
                        }
                    }
                    if (nqty.compareTo(BigDecimal.ZERO) > 0) {
                        splitrowInsetData(entity, yem_entrtyid, dynamicObject, nqty);
                    }
                    Quantityofstock();
//                    calcRemainingPushableOrderQuantity(this.getModel(), this.getView());
                }
            } else {
                throw new KDBizException("拆分行有且只能选择一行进行拆分");
            }
        } else {
            throw new KDBizException("请选择一行数据进行拆分");
        }
    }

    /**
     * 插入数据
     *
     * @param salesorder    备料信息实体
     * @param yem_entrtyid  商品分录id
     * @param dynamicObject 选中数据
     */
    public void splitrowInsetData(DynamicObjectCollection salesorder, long yem_entrtyid, DynamicObject dynamicObject, BigDecimal nqty) {
        int row = 0;
        for (int i = 0; i < salesorder.size(); i++) {
            DynamicObject Object = salesorder.get(i);
            if (yem_entrtyid == Object.getLong("yem_entrtyid")) {
                row = i;
            }
        }
        DynamicObject date = new DynamicObject(salesorder.getDynamicObjectType());
        date.set("yem_materialper", dynamicObject.getString("yem_materialper"));// 物料属性
        // 要求入库时间
        date.set("yem_reqputstordate", this.getModel().getValue("yem_acshipdate"));
        // 预计完成时间
        date.set("yem_yieldetacdate", this.getModel().getValue("yem_yieldetacdate"));
        date.set("yem_entrtyid", dynamicObject.getLong("yem_entrtyid"));
        date.set("yem_materielg", dynamicObject.getDynamicObject("yem_materielg"));
        date.set("yem_stockqty", nqty);//备料数量
        date.set("yem_stockunit", dynamicObject.getDynamicObject("yem_stockunit"));//计量单位
        date.set("yem_stockbaseunit", dynamicObject.getDynamicObject("yem_stockbaseunit"));//基本计量单位
        date.set("yem_stockbaseqty", nqty);//基本计量单位
        if (dynamicObject.getDynamicObject("yem_resourceno") != null) {
            date.set("yem_productmodelb", dynamicObject.getDynamicObject("yem_resourceno").getDynamicObject("yem_products"));//产品型号
            date.set("yem_resourceno", dynamicObject.getDynamicObject("yem_resourceno"));
        }
        date.set("yem_orderallocation1", dynamicObject.getString("yem_orderallocation1"));//订单配置要求
        date.set("yem_orderallocationen1", dynamicObject.getString("yem_orderallocationen1"));//配置英文描述
        date.set("yem_productmodel1", dynamicObject.getDynamicObject("yem_productmodel1"));//基础机型
        date.set("yem_ifreformg1", dynamicObject.getString("yem_ifreformg1"));//是否改制
        date.set("yem_reformdesg1", dynamicObject.getString("yem_reformdesg1"));//改制描述
        date.set("yem_projectdesc1", dynamicObject.getString("yem_projectdesc1"));//加装方案说明
        date.set("yem_ifsupportg1", dynamicObject.getString("yem_ifsupportg1"));//是否技术支持
        date.set("yem_color_e", dynamicObject.getString("yem_color_e"));
        salesorder.add(row + 1, date);
    }

    public void newproduction() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        int currentRow = model.getEntryCurrentRowIndex("yem_es_salesorder_r");
//        if(currentRow<0){
        DynamicObjectCollection salesorder_r = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");
        if (salesorder_r.size() > 0) {
            DynamicObject salesorder = salesorder_r.get(currentRow);
            DynamicObjectCollection yem_es_salesorder_z = salesorder.getDynamicObjectCollection("yem_es_salesorder_z");
            DynamicObject salesorder_z = yem_es_salesorder_z.addNew();
            salesorder_z.set("yem_resourcescode", salesorder.getDynamicObject("yem_resourceno"));
            salesorder_z.set("yem_milltype", salesorder.getDynamicObject("yem_productmodelb"));
            salesorder_z.set("yem_yieldway", salesorder.getString("yem_materialper"));
            salesorder_z.set("yem_prepareway", salesorder.getString("yem_stockway"));
            salesorder_z.set("yem_assembleupline", "B");
            salesorder_z.set("yem_assembledownline", "B");
            salesorder_z.set("yem_debugst", "B");
            salesorder_z.set("yem_waitforinspection", "B");
            salesorder_z.set("yem_accuracytest", "B");
            salesorder_z.set("yem_qualitytest", "B");
            salesorder_z.set("yem_factputstor", "B");
            salesorder_z.set("yem_backonline", "B");
            salesorder_z.set("yem_putintostorage", "B");
        }
//        }
//        else{
//            this.getView()
//        }
    }

    /**
     * @description 查询资源进度，查询改制资源进度
     * @author xwudd
     * return
     * @time 2023/9/5 9:51
     */

    public void viewPlanPin(String type) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        int currentRowIndex = model.getEntryCurrentRowIndex("yem_es_salesorder_r");
        DynamicObject resourceNo = (DynamicObject) model.getValue("yem_resourceno", currentRowIndex);
        EntryGrid machineProductInfos = view.getControl("yem_es_salesorder_z");
        int[] selectRows = machineProductInfos.getSelectRows();
        if ("B".equals(type)) {
            resourceNo = (DynamicObject) model.getValue("yem_reformresources", currentRowIndex);
            if (selectRows.length != 1) {
                view.showErrorNotification("改制资源操作，只能选择一行整机生产信息进行操作！");
                return;
            }
        }
        viewForm(type, resourceNo);
    }

    public void viewForm(String type, DynamicObject resourceNo) {
        IFormView view = this.getView();
        if (YEM.isNotEmpty(resourceNo)) {
            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setFormId("yem_planpin");
            formShowParameter.getOpenStyle().setShowType(ShowType.Modal);
            formShowParameter.setCustomParam(MaterialVehicleNoCMMP.productCode, resourceNo);
            formShowParameter.setCustomParam("type", type);
            DynamicObject yemBdProducts = (DynamicObject) this.getModel().getValue("yem_bd_products");
            long cpflid = yemBdProducts.getLong("id");
            formShowParameter.setCustomParam("yem_bd_products", cpflid);
            view.showForm(formShowParameter);
        }
    }

    public void renewSaleMachineInfo() {
        IDataModel model = this.getModel();
        DynamicObjectCollection prepareFeeds = model.getEntryEntity("yem_es_salesorder_r");
        int prepareFeedRowIndex = model.getEntryCurrentRowIndex("yem_es_salesorder_r");
        DynamicObject prepareFeed = prepareFeeds.get(prepareFeedRowIndex);
        DynamicObjectCollection machineInfos = prepareFeed.getDynamicObjectCollection("yem_es_salesorder_z");
        Map<Long, DynamicObject> machineInfoIds = machineInfos.stream().collect(Collectors.toMap(x -> x.getLong("id"), y -> y));
        long entryId = prepareFeed.getLong("yem_entrtyid");
        DynamicObjectCollection materialInfos = model.getEntryEntity("yem_es_materialinfo");
        Map<Long, Long> materialInfoIds = materialInfos.stream().collect(Collectors.toMap(x -> x.getLong("id"), y -> y.getLong("yem_sourceentryid")));
        if (materialInfoIds.containsKey(entryId)) {
            long sourceEntryId = materialInfoIds.get(entryId);
            String selectfields = DynamicObjectUtil.getSelectfields("yem_es_salesorder", false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_es_salesorder", "yem_es_materialinfo", false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_es_salesorder", "yem_es_materialinfo", "yem_es_salesorder_z", false);
            DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", selectfields, new QFilter[]{new QFilter("yem_es_materialinfo.id", QCP.equals, sourceEntryId)});
            if (YEM.isNotEmpty(salesOrder)) {
                DynamicObjectCollection saleOrderMaterialInfos = salesOrder.getDynamicObjectCollection("yem_es_materialinfo");
                for (DynamicObject saleOrderMaterialInfo : saleOrderMaterialInfos) {
                    long saleOrderMaterialInfoId = saleOrderMaterialInfo.getLong("id");
                    if (sourceEntryId == saleOrderMaterialInfoId) {
                        DynamicObjectCollection saleMachineInfos = saleOrderMaterialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
                        for (DynamicObject saleMachineInfo : saleMachineInfos) {
                            long trackTaskMachineId = saleMachineInfo.getLong("yem_tracktaskmachinid");
                            if (machineInfoIds.containsKey(trackTaskMachineId)) {
                                DynamicObject trackMachineInfo = machineInfoIds.get(trackTaskMachineId);
                                saleMachineInfo.set("yem_resourcescode", trackMachineInfo.get("yem_resourcescode"));//资源号
                                saleMachineInfo.set("yem_milltype", trackMachineInfo.get("yem_milltype"));//机型
                                saleMachineInfo.set("yem_yieldway", trackMachineInfo.get("yem_yieldway"));//物料属性
                                saleMachineInfo.set("yem_prepareway", trackMachineInfo.get("yem_prepareway"));//备料方式
                                saleMachineInfo.set("yem_vehicleno", trackMachineInfo.get("yem_vehicleno"));//整机编号
                                saleMachineInfo.set("yem_engineno", trackMachineInfo.get("yem_engineno"));//发动机号
                                saleMachineInfo.set("yem_enginemodel", trackMachineInfo.get("yem_enginemodel"));//发动机型号
                                saleMachineInfo.set("yem_enginevendor", trackMachineInfo.get("yem_enginevendor"));//发动机厂商
                                saleMachineInfo.set("yem_currentstate", trackMachineInfo.get("yem_currentstate"));//当前状态
                                saleMachineInfo.set("yem_currentstatedate", trackMachineInfo.get("yem_currentstatedate"));//当前状态时间
                                saleMachineInfo.set("yem_assembleupline", trackMachineInfo.get("yem_assembleupline"));//总装上线
                                saleMachineInfo.set("yem_upline", trackMachineInfo.get("yem_upline"));//上线时间
                                saleMachineInfo.set("yem_assembledownline", trackMachineInfo.get("yem_assembledownline"));//总装下线
                                saleMachineInfo.set("yem_downline", trackMachineInfo.get("yem_downline"));//下线时间
                                saleMachineInfo.set("yem_debugst", trackMachineInfo.get("yem_debugst"));//调试
                                saleMachineInfo.set("yem_debugstatdate", trackMachineInfo.get("yem_debugstatdate"));//调试完成时间
                                saleMachineInfo.set("yem_waitforinspection", trackMachineInfo.get("yem_waitforinspection"));//待检
                                saleMachineInfo.set("yem_waitforinspecdate", trackMachineInfo.get("yem_waitforinspecdate"));//待检时间
                                saleMachineInfo.set("yem_accuracytest", trackMachineInfo.get("yem_accuracytest"));//精试
                                saleMachineInfo.set("yem_accuratdate", trackMachineInfo.get("yem_accuratdate"));//精试完成时间
                                saleMachineInfo.set("yem_qualitytest", trackMachineInfo.get("yem_qualitytest"));//质检
                                saleMachineInfo.set("yem_qualitytestdate", trackMachineInfo.get("yem_qualitytestdate"));//质检合格时间
                                saleMachineInfo.set("yem_factputstor", trackMachineInfo.get("yem_factputstor"));//入库
                                saleMachineInfo.set("yem_factputstordate", trackMachineInfo.get("yem_factputstordate"));//实际入库时间
                                saleMachineInfo.set("yem_backonline", trackMachineInfo.get("yem_backonline"));//返工上线
                                saleMachineInfo.set("yem_backonlinedate", trackMachineInfo.get("yem_backonlinedate"));//返工上线时间
                                saleMachineInfo.set("yem_putintostorage", trackMachineInfo.get("yem_putintostorage"));//改制入库
                                saleMachineInfo.set("yem_putintostoragedate", trackMachineInfo.get("yem_putintostoragedate"));//改制入库时间
                                saleMachineInfo.set("yem_vehicleremark", trackMachineInfo.get("yem_vehicleremark"));//备注
                                saleMachineInfo.set("yem_ifdelivered", trackMachineInfo.get("yem_ifdelivered"));//备注
                            }
                        }
                    }
                }
            }
        }

    }

    /**
     * 赋值背景色
     *
     * @param Type
     */
    public void Backcolor(String Type) {
        List sreloading = new ArrayList();
        EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
        for (int i = 0; i < entity.size(); i++) {
            DynamicObject dynamicObject = entity.get(i);  //获取选中行的单据体数据
            if ("yem_tracktaskconsole_zj".equals(Type)) {
                String yem_productstat = dynamicObject.getString("yem_productstat");
                if (yem_productstat.equals("B")) {
                    BigDecimal yem_nqty = dynamicObject.getBigDecimal("yem_nqty");//为备料数量
                    if (yem_nqty.compareTo(BigDecimal.ZERO) > 0) {
                        sreloading.add(i);
                    }
                }
            } else if ("yem_tracktaskconsole_pj".equals(Type)) {
                BigDecimal yem_nqty = dynamicObject.getBigDecimal("yem_nqty");//为备料数量
                if (yem_nqty.compareTo(BigDecimal.ZERO) > 0) {
                    sreloading.add(i);
                }
            }
        }
        if (sreloading.size() > 0) {
            int[] selectRows = new int[sreloading.size()];
            for (int i = 0; i < sreloading.size(); i++) {
                selectRows[i] = Integer.valueOf(sreloading.get(i).toString());
            }
            entryGrid.setRowBackcolor("rgba(251,35,35,0.1)", selectRows);
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        int row = e.getRow();
        switch (name) {
            case "yem_reformresources":
                selectF7reformresources(e);
                break;
        }
    }

    public void selectF7reformresources(BeforeF7SelectEvent e) {
        int row = e.getRow();
        IDataModel model = this.getModel();
        DynamicObject yem_milltype = (DynamicObject) model.getValue("yem_milltype");
        if (YEM.isNotEmpty(yem_milltype)) {
            e.addCustomQFilter(new QFilter("yem_products", QCP.equals, yem_milltype.getPkValue()));
        }
    }

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

    /**
     * 更新到对应的外销合同的商品明细、多功能配置 下单审批
     */
    public void updateimpactprice() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_es_materialinfo = this.getModel().getEntryEntity("yem_es_materialinfo");//跟单任务控制台商品
        long yem_sourcebillid = dataEntity.getLong("yem_sourcebillid");//单据头来源单据ID（外销合同id）
        if (yem_sourcebillid > 0) {
            DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle(yem_sourcebillid, "yem_es_salesorder");
            if (yem_es_salesorder != null) {
                DynamicObjectCollection salesordermater = yem_es_salesorder.getDynamicObjectCollection("yem_es_materialinfo");
                if (yem_es_materialinfo.size() > 0) {
                    for (int i = 0; i < yem_es_materialinfo.size(); i++) {
                        DynamicObject dynamicObject = yem_es_materialinfo.get(i);
                        DynamicObjectCollection yem_multiconfig = dynamicObject.getDynamicObjectCollection("yem_multiconfig");
                        long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid");
                        String yem_businesssort = dynamicObject.getString("yem_businesssort");
                        if (yem_businesssort.equals("Z")) {
                            for (int j = 0; j < salesordermater.size(); j++) {
                                DynamicObject dynamicObject1 = salesordermater.get(j);
                                long id = dynamicObject1.getLong("id");
                                if (yem_sourceentryid == id) {
                                    dynamicObject1.set("yem_impactprice", dynamicObject.getString("yem_impactprice"));
                                }
                                //获取子分录
                                DynamicObjectCollection salesordmult = dynamicObject1.getDynamicObjectCollection("yem_multiconfig");
                                for (int k = 0; k < yem_multiconfig.size(); k++) {
                                    DynamicObject dynamicObject2 = yem_multiconfig.get(k);
                                    long yem_multid = dynamicObject2.getLong("yem_multid");
                                    for (int g = 0; g < salesordmult.size(); g++) {
                                        long id1 = salesordmult.get(g).getLong("id");
                                        if (id1 == yem_multid) {
                                            salesordmult.get(g).set("yem_impactprice1", dynamicObject2.getString("yem_impactprice1"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{yem_es_salesorder});
            }
            //下单审批
            QFilter qFilter = new QFilter("yem_sourcebillid", QCP.equals, yem_sourcebillid);
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("yem_placeexamine", "id", qFilter.toArray());
            if (billType != null) {
                DynamicObject yem_placeexamine = BusinessDataServiceHelper.loadSingle(billType.getLong("id"), "yem_placeexamine");
                if (yem_placeexamine != null) {
                    DynamicObjectCollection salesordermater = yem_placeexamine.getDynamicObjectCollection("yem_es_materialinfo");
                    if (yem_es_materialinfo.size() > 0) {
                        for (int i = 0; i < yem_es_materialinfo.size(); i++) {
                            DynamicObject dynamicObject = yem_es_materialinfo.get(i);
                            DynamicObjectCollection yem_multiconfig = dynamicObject.getDynamicObjectCollection("yem_multiconfig");
                            long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid");
                            String yem_businesssort = dynamicObject.getString("yem_businesssort");
                            if (yem_businesssort.equals("Z")) {
                                for (int j = 0; j < salesordermater.size(); j++) {
                                    DynamicObject dynamicObject1 = salesordermater.get(j);
                                    long id = dynamicObject1.getLong("id");
                                    if (yem_sourceentryid == id) {
                                        dynamicObject1.set("yem_impactprice", dynamicObject.getString("yem_impactprice"));
                                    }
                                    //获取子分录
                                    DynamicObjectCollection salesordmult = dynamicObject1.getDynamicObjectCollection("yem_multiconfig");
                                    for (int k = 0; k < yem_multiconfig.size(); k++) {
                                        DynamicObject dynamicObject2 = yem_multiconfig.get(k);
                                        long yem_multid = dynamicObject2.getLong("yem_multid");
                                        for (int g = 0; g < salesordmult.size(); g++) {
                                            long id1 = salesordmult.get(g).getLong("id");
                                            if (id1 == yem_multid) {
                                                salesordmult.get(g).set("yem_impactprice1", dynamicObject2.getString("yem_impactprice1"));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    SaveServiceHelper.save(new DynamicObject[]{yem_placeexamine});
                }
            }
        }
    }

    @Override
    public void beforeDeleteRow(BeforeDeleteRowEventArgs e) {
        super.beforeDeleteRow(e);
        int[] rowIndex = e.getRowIndexs();
        EntryProp entryProp = e.getEntryProp();
        String name = entryProp.getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("yem_es_salesorder_r".equals(name)) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_salesorder_r");
            StringBuilder sb = new StringBuilder();
            for (int index : rowIndex) {
                DynamicObject dynamicObject = collection.get(index);
                // 关联订单需求表数量
                BigDecimal qtyfield6 = dynamicObject.getBigDecimal("yem_qtyfield6");
                if (qtyfield6.compareTo(BigDecimal.ZERO) > 0) {
                    sb.append(String.format("备料信息第 [ %s ] 行，关联订单需求表数量大于0，不能删除！", index + 1)).append("\n");
                }
            }
            if (sb.length() > 0) {
                e.setCancel(true);
                this.getView().showErrorNotification(sb.toString());
            }
        }
    }
}
