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

import com.yem.wm.es.Util.ZJUtils;
import com.yem.wm.utils.DynamicObjectUtil;
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.dataentity.metadata.dynamicobject.DynamicProperty;
import kd.bos.entity.datamodel.IDataModel;
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.EntryGrid;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.events.*;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.mvc.FormConfigFactory;
import kd.bos.mvc.SessionManager;
import kd.bos.mvc.bill.BillModel;
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 kd.sdk.plugin.Plugin;

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

/**
 * @author zhouc
 * @date 2023/9/27 14:15
 * @className TrackplaceFormPlugIn
 * @description 产品经理下单确认表单插件
 */
public class TrackplaceFormPlugIn extends AbstractBillPlugIn implements Plugin, BeforeF7SelectListener, RowClickEventListener, HyperLinkClickListener {

    @Override
    public void registerListener(EventObject e) {
        BasedataEdit resourceid = this.getView().getControl("yem_resourcenog");
        resourceid.addBeforeF7SelectListener(this);

        EntryGrid entryGrid = this.getView().getControl("yem_es_materialinfo");
        entryGrid.addRowClickListener(this);
        entryGrid.addHyperClickListener(this);
        BasedataEdit yem_albumassemblyno = this.getView().getControl("yem_albumassemblyno");
        yem_albumassemblyno.addBeforeF7SelectListener(this);
        BasedataEdit yem_materiel1 = this.getView().getControl("yem_materiel1");
        yem_materiel1.addBeforeF7SelectListener(this);
//        EntryGrid detailedInfor = this.getControl("yem_im_detailedinfor");
//        detailedInfor.addRowClickListener(this);
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        QFilter qFilter1 = new QFilter("number", QCP.equals, "yem_tracktaskconsole_zj");
        DynamicObject bos_billtype_s = BusinessDataServiceHelper.loadSingle("bos_billtype",
                "id,name,number", new QFilter[]{qFilter1});
        if (bos_billtype_s != null) {
            this.getView().getModel().setValue("yem_billtypes", bos_billtype_s.getString("name"));
        }
        Backcolor("A");
        lockresourceno();
        GetTracktaskconsole();
    }

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);
    }

    @Override
    public void beforeClosed(BeforeClosedEvent e) {
        super.beforeClosed(e);
        //文本字段退出不提醒
        DynamicObject dataEntity = this.getModel().getDataEntity();
        DynamicProperty yem_picturefield1 = dataEntity.getDynamicObjectType().getProperty("yem_billtypes");
        dataEntity.getDataEntityState().setBizChanged(yem_picturefield1.getOrdinal(), false);
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        ChangeData changeData = e.getChangeSet()[0];
        String proName = e.getProperty().getName();
        int row = changeData.getRowIndex();
        switch (proName) {
            case "yem_resourcenog":
                DynamicObject resourceid = (DynamicObject) model.getValue("yem_resourcenog", row);
                String businesssort = (String) model.getValue("yem_businesssort", row);
                if (resourceid != null && "Z".equals(businesssort)) {

                    String resouceNumber = resourceid.getString("number");
                    List<QFilter> qFilterList = new ArrayList<QFilter>();
                    if (!Objects.equals(resouceNumber, "")) {
                        qFilterList.add(new QFilter("number", QCP.equals, resouceNumber.trim()));
                    }
                    DynamicObject tempCol = BusinessDataServiceHelper.loadSingle("bd_material", "11", qFilterList.toArray(new QFilter[0]));
                    if (tempCol != null) {
                        model.setValue("yem_materiel", tempCol.getLong("id"), row);
                    } else {
                        model.setValue("yem_materiel", null, row);
                        view.showMessage("请维护编码【" + resouceNumber + "】的物料！");
                    }

                    //修改子单据体资源号
                    DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
                    DynamicObject dynamicObject = entity.get(row);  //获取选中行的单据体数据
                    DynamicObjectCollection yem_retrofitting = dynamicObject.getDynamicObjectCollection("yem_retrofitting");
                    if (yem_retrofitting.size() > 0) {
                        for (int i = 0; i < yem_retrofitting.size(); i++) {
                            model.setValue("yem_resourceid1", resourceid, i);
                        }
                    }
                } else {
                    model.setValue("yem_materiel", null, row);
                }
                break;
            default:
                break;
            case "yem_ifreformg":
                DynamicObject dataEntity = model.getDataEntity();
                DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
                collection.get(row).set("yem_reformdesg", null);
                this.getView().updateView();
                break;
            case "yem_impactprice1":
                // 影响调拨价
                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);
                        }
                    }
                }
                // 多功能配置
                break;
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        DynamicObject datas = this.getModel().getDataEntity(true);
        String key = e.getProperty().getName();
        QFilter qFilter = null;
        DynamicObject products = datas.getDynamicObject("yem_bd_products");
        switch (key) {
            //明细信息 资源号过滤
            case "yem_resourcenog":
                int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
                DynamicObject productmodel = (DynamicObject) this.getModel().getValue("yem_productmodel", row);

                String businesssort = (String) this.getModel().getValue("yem_businesssort", row);
                if ("P".equals(businesssort)) {
                    break;
                }
                DynamicObject yem_prod = (DynamicObject) this.getModel().getValue("yem_prod", row);
                long yem_sourceentryid = (long) this.getModel().getValue("yem_sourceentryid", row);
                QFilter Filter = new QFilter("yem_es_materialinfo.yem_sourceentryid", QCP.in, yem_sourceentryid);
                Filter.and(new QFilter("yem_es_materialinfo.yem_prod.id", QCP.not_equals, 0));
                DynamicObjectCollection yem_es_salesorder = QueryServiceHelper.query("yem_tracktaskconsole_prod",
                        "id,billno,billstatus,yem_es_materialinfo.yem_resourcenog.id",
                        new QFilter[]{Filter}, null);
                if (productmodel == null) {
                    this.getView().showMessage("请选择基础机型第" + (row + 1) + "行");
                    e.setCancel(true);
                } else {
                    Long yemproducts = productmodel.getLong("yem_products.id");
                    QFilter qFilter1 = new QFilter("yem_products", QCP.equals, yemproducts);
                    if (yem_es_salesorder.size() > 0) {
                        long id = yem_es_salesorder.get(0).getLong("yem_es_materialinfo.yem_resourcenog.id");
                        qFilter1.and(new QFilter("id", QCP.equals, id));
                    }
                    e.addCustomQFilter(qFilter1);
                }
                break;
            default:
                break;

            case "yem_albumassemblyno":
                QFilter qFilter1 = new QFilter("yem_isadditional", QCP.equals, "A");
                qFilter1.and(new QFilter("status", QCP.equals, "C"));
                e.addCustomQFilter(qFilter1);
                break;
            case "yem_materiel1":
                int retrow = this.getModel().getEntryCurrentRowIndex("yem_retrofitting");
                DynamicObject yem_albumassemblyno = (DynamicObject) this.getModel().getValue("yem_albumassemblyno", retrow);
                if (yem_albumassemblyno != null) {
                    String number = yem_albumassemblyno.getString("number");
                    long id = yem_albumassemblyno.getLong("id");
                    DynamicObject billType = BusinessDataServiceHelper.loadSingle(id, "yem_em_assatlasdet");
                    if (billType != null) {
                        List list = new ArrayList<>();
                        DynamicObjectCollection yem_entryentity = billType.getDynamicObjectCollection("yem_entryentity");
                        for (int i = 0; i < yem_entryentity.size(); i++) {
                            DynamicObject dynamicObject = yem_entryentity.get(i);
                            String yem_partnumber = dynamicObject.getString("yem_partnumber");
                            list.add(yem_partnumber);
                        }
                        if (list.size() > 0) {
                            QFilter mateFilter = new QFilter("number", QCP.in, list);
                            mateFilter.and(new QFilter("status", QCP.equals, "C"));
                            e.addCustomQFilter(mateFilter);
                        } else {
                            this.getView().showErrorNotification("总成图册编码【" + number + "】未获取到满足条件的零件，请修改后重试！");
                            e.setCancel(true);
                        }
                    }
                }
//                else {
//                    this.getView().showErrorNotification("请先选择总成图册编码！");
//                    e.setCancel(true);
//                }
                break;
        }
    }

    @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("jzaddnew")) {
            int rowIndex = model.getEntryCurrentRowIndex("yem_es_materialinfo");
            DynamicObjectCollection yem_es_materialinfo = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            if (yem_es_materialinfo.size() > rowIndex) {
                DynamicObject materialinfo = yem_es_materialinfo.get(rowIndex);
                if (materialinfo != null) {
                    int row = model.createNewEntryRow("yem_retrofitting");
                    model.setValue("yem_resourceid1", materialinfo.getDynamicObject("yem_resourcenog"), row);
//                    model.setValue("yem_materiel1", materialinfo.getDynamicObject("yem_materiel"), row);
//                    model.setValue("yem_unit1", materialinfo.getDynamicObject("yem_unit"), row);
                    model.setValue("yem_qty1", materialinfo.getBigDecimal("yem_qty"), row);
                    model.setValue("yem_desc", materialinfo.getString("yem_remarks"), row);
                }
            }
        }
        if ("zyresource".equals(key)) {//资源确认//将确认人、确认时间更新到对应分录的对应字段，下单状态：更新为产品经理已确认
            this.getView().invokeOperation("save");
            DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
            //获取单据体控件
            EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
            //获取选中行，数组为行号，从0开始int[]
            int[] selectRows = entryGrid.getSelectRows();
            if (selectRows != null && selectRows.length > 0) {

                List del_id_s = new ArrayList();
                List sreloading = new ArrayList();
                List sourlist = new ArrayList();
                Map map = new HashMap<>();
                StringBuilder sb = new StringBuilder();
                for (int selectRow : selectRows) {
                    DynamicObject materiel = (DynamicObject) model.getValue("yem_materiel", selectRow);
                    if (YEM.isEmpty(materiel)) {
                        sb.append(String.format("第 %s 行，物料编码为空，请填写确认！！\n", selectRow + 1));
                    }
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    String seq = dynamicObject.getString("seq");
                    String yemIsreloading = dynamicObject.getString("yem_isreloading");
                    if (yemIsreloading == "") {
                        sreloading.add(seq);
                    } else if (yemIsreloading.equals("A")) {
                        DynamicObjectCollection yem_retrofitting = dynamicObject.getDynamicObjectCollection("yem_retrofitting");
                        if (yem_retrofitting.size() > 0) {
                            DynamicObject dynamicObject1 = yem_retrofitting.get(0).getDynamicObject("yem_materiel1");
                            if (dynamicObject1 == null) {
                                del_id_s.add(seq);
                            }
                        } else {
                            del_id_s.add(seq);
                        }
                    }
                    long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid");
                    if (yem_sourceentryid != 0) {
                        sourlist.add(yem_sourceentryid);
                        map.put(yem_sourceentryid, dynamicObject.getDynamicObject("yem_resourcenog"));
                    }
                }
                if (sb.length() > 0) {
                    throw new KDBizException(sb.toString());
                }
                if (sreloading.size() == 0) {
                    if (del_id_s.size() > 0) {
                        throw new KDBizException("选中行第【" + String.join("、", del_id_s) + "】行是否加装为【是】，请维护对应加装明细后重试！");
                    }
                } else {
                    throw new KDBizException("选中行【" + String.join("、", sreloading) + "】行，【是否进行加装】为空，请维护后重试");
                }

                // 加装方案说明必录校验
                checkProjectDesc(e);
                // 物料的长、宽、高必须维护(判断当前行物料信息上的数据)，否则不允许确认
                checkVolumeInfoInput();
                for (int selectRow : selectRows) {
                    model.setValue("yem_prod", BusinessDataServiceHelper.loadSingle(YEM.getCurrentUserId(), "bos_user"), selectRow);
                    model.setValue("yem_resource", new Date(), selectRow);
                    updateOriginFormImpactPrice(selectRow);

                }
                updateSalesOrderPrice(e, selectRows);
                lockresourceno();
                updateTaskConsole();
                GetTracktaskconsole();
                view.invokeOperation("save");
                view.invokeOperation("refresh");
            }
        }
        if ("zyunresource".equals(key)) {//资源取消确认
            DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
            //获取单据体控件
            List sourlist = new ArrayList();
            EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
            //获取选中行，数组为行号，从0开始int[]
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows != null && selectRows.length > 0) {
                //判断选中行是否已确认
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    String yem_productstat = dynamicObject.getString("yem_productstat");
                    String seq = dynamicObject.getString("seq");
                    if (!yem_productstat.equals("B")) {
                        model.setValue("yem_prod", null, selectRow);//
                        model.setValue("yem_resource", null, selectRow);//
                    } else {
                        sourlist.add(seq);
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                if (sourlist.size() > 0) {
                    throw new KDBizException("选中行第【" + String.join("、", sourlist) + "】行是【下单状态】为【产品经理已确认】，禁止取消确认资源！");
                }
            }
            lockresourceno();
            GetTracktaskconsole();
        }
        if ("order".equals(key)) {//下单确认
            List del_id_s = new ArrayList();
            DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
            //获取单据体控件
            EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
            //获取选中行，数组为行号，从0开始int[]
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows != null && selectRows.length > 0) {
                List newBigDecimal = new ArrayList<>();
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    DynamicObject yemMateriel = dynamicObject.getDynamicObject("yem_materiel");
                    if (yemMateriel != null) {
                        BigDecimal netweight = yemMateriel.getBigDecimal("netweight");
                        if (netweight.compareTo(BigDecimal.ZERO) == 0) {
                            String seq = dynamicObject.getString("seq");
                            newBigDecimal.add(seq);
//                            this.getView().showMessage("第【" + seq + "】行物料中净重为空，请稍后重试！");

                        }
                    }
                }
                if (!newBigDecimal.isEmpty()) {
                    view.showMessage("第【" + String.join("、", newBigDecimal) + "】行物料中净重为空，请维护后重试！");
                    return;
                }

                //判断选中行是否已确认
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    Date yemResource = dynamicObject.getDate("yem_resource");
                    String seq = dynamicObject.getString("seq");
                    if (yemResource == null) {
                        del_id_s.add(seq);
                    } else {
                        model.setValue("yem_orderholder", YEM.getCurrentUserId(), selectRow);//
                        model.setValue("yem_confirmationdate", new Date(), selectRow);//
                        model.setValue("yem_productstat", "B", selectRow);
                        Backcolor("A");
                    }
                }
                if (del_id_s.size() > 0) {
                    throw new KDBizException("选中行第【" + String.join("、", del_id_s) + "】行资源未确认，请确认后重试！");
                }
                SaveServiceHelper.save(new DynamicObject[]{dataEntity});
                updateSalesOrderPrice(e, selectRows);
                updateTaskConsole();
                GetTracktaskconsole();
            }


        }
        if ("unorder".equals(key)) {//取消下单
            List del_id_s = new ArrayList();
            DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
            //获取单据体控件
            EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
            //获取选中行，数组为行号，从0开始int[]
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows != null && selectRows.length > 0) {
                //判断选中行是否已确认
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    BigDecimal yem_hqty = dynamicObject.getBigDecimal("yem_hqty");
                    String seq = dynamicObject.getString("seq");
                    if (yem_hqty.compareTo(BigDecimal.ZERO) == 0) {
                        model.setValue("yem_orderholder", null, selectRow);//
                        model.setValue("yem_confirmationdate", null, selectRow);//
                        model.setValue("yem_productstat", "A", selectRow);//
                        Backcolor("B");
                    } else {
                        del_id_s.add(seq);
                    }
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            GetTracktaskconsole();
            if (del_id_s.size() > 0) {
                throw new KDBizException("选中行第【" + String.join("、", del_id_s) + "】行已执行备料，禁止取消确认！");
            }
        }
        if ("createsourceapply".equals(key)) {
            ZJUtils.createSourceApplys(view, model, "yem_es_materialinfo", "B");
        }
        if ("orderass".equals(key)) {
            DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_accessorygoods");//商品
            EntryGrid entryGrid = this.getControl("yem_es_accessorygoods");
            //获取选中行，数组为行号，从0开始int[]
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows != null && selectRows.length > 0) {
                //判断选中行是否已确认
                DynamicObject yemtracktaskconsole = BusinessDataServiceHelper.loadSingle(dataEntity.getLong("yem_gdrwkztid"), "yem_tracktaskconsole");
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    long yemTracktaskid = dynamicObject.getLong("yem_tracktaskid");
                    DynamicObjectCollection yemEsMaterialinfo = yemtracktaskconsole.getDynamicObjectCollection("yem_es_materialinfo");
                    if (yemEsMaterialinfo.size() > 0) {
                        for (int i = 0; i < yemEsMaterialinfo.size(); i++) {
                            DynamicObject dynamicObject1 = yemEsMaterialinfo.get(i);
                            if (yemTracktaskid == dynamicObject1.getLong("id")) {
                                dynamicObject1.set("yem_orderholder", YEM.getCurrentUserId());//
                                dynamicObject1.set("yem_confirmationdate", new Date());//
                                dynamicObject1.set("yem_productstat", "B");
                                DynamicObject yem_materiel2 = dynamicObject.getDynamicObject("yem_materiel2");
                                if (yem_materiel2 != null) {
                                    dynamicObject1.set("yem_materiel", dynamicObject.getDynamicObject("yem_materiel2"));
                                    dynamicObject1.set("yem_materialname", yem_materiel2.getString("name"));
                                    dynamicObject1.set("yem_specification", yem_materiel2.getString("modelnum"));
                                    dynamicObject1.set("yem_unit", yem_materiel2.getDynamicObject("baseunit"));
                                    dynamicObject1.set("yem_baseunit", yem_materiel2.getDynamicObject("baseunit"));
                                    dynamicObject1.set("yem_baseqty", dynamicObject.getBigDecimal("yem_baseqty1"));
                                }

                            }
                        }
                    }
                }

                SaveServiceHelper.save(new DynamicObject[]{yemtracktaskconsole});
                Updatematerielpj();
//                updateSalesOrderPrice(e, selectRows);
                GetTracktaskconsole();
                this.getView().showSuccessNotification("操作完成！");
            }
        }
        if ("unorderass".equals(key)) {
            DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_accessorygoods");//商品
            EntryGrid entryGrid = this.getControl("yem_es_accessorygoods");
            //获取选中行，数组为行号，从0开始int[]
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows != null && selectRows.length > 0) {
                //判断选中行是否已确认
                DynamicObject yemtracktaskconsole = BusinessDataServiceHelper.loadSingle(dataEntity.getLong("yem_gdrwkztid"), "yem_tracktaskconsole");
                for (int selectRow : selectRows) {
                    DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                    long yemTracktaskid = dynamicObject.getLong("yem_tracktaskid");
                    DynamicObjectCollection yemEsMaterialinfo = yemtracktaskconsole.getDynamicObjectCollection("yem_es_materialinfo");
                    if (yemEsMaterialinfo.size() > 0) {
                        for (int i = 0; i < yemEsMaterialinfo.size(); i++) {
                            DynamicObject dynamicObject1 = yemEsMaterialinfo.get(i);
                            if (yemTracktaskid == dynamicObject1.getLong("id")) {
                                dynamicObject1.set("yem_orderholder", null);//
                                dynamicObject1.set("yem_confirmationdate", null);//
                                dynamicObject1.set("yem_productstat", "A");
                            }
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{yemtracktaskconsole});
                GetTracktaskconsole();
                this.getView().showSuccessNotification("操作完成！");
            }
        }
    }

    /**
     * 更新跟单任务控制台（资源号）
     */
    private void updateTaskConsole() {
        IDataModel model = this.getModel();
        Long sourcebillid = (Long) model.getValue("yem_sourcebillid");
        QFilter qFilter = new QFilter("yem_sourcebillid", QCP.equals, sourcebillid);
        DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("id", QCP.equals, sourcebillid)});
        String selectfields = DynamicObjectUtil.getSelectfields("yem_tracktaskconsole");
        String entrySelectfields = DynamicObjectUtil.getEntrySelectfields(selectfields, "yem_tracktaskconsole", "yem_es_materialinfo");
        DynamicObject[] load = BusinessDataServiceHelper.load("yem_tracktaskconsole", entrySelectfields, qFilter.toArray());
        if (YEM.isEmpty(salesOrder)) return;
        for (DynamicObject object : load) {
            DynamicObjectCollection collection = object.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                long sourceentryid = dynamicObject.getLong("yem_sourceentryid");
                DynamicObject salesEntry = getSalesOrderSameEntry(salesOrder, sourceentryid);
                if (YEM.isNotEmpty(salesEntry)) {
                    DynamicObject resourcenog = salesEntry.getDynamicObject("yem_resourcenog");
                    dynamicObject.set("yem_resourcenog", resourcenog);
                    DynamicObject materiel = salesEntry.getDynamicObject("yem_materiel");
                    dynamicObject.set("yem_materiel", materiel);
                }
            }
        }

        if (load.length > 0) {
            SaveServiceHelper.update(load);
        }
    }

    /**
     * 通过合同ID找到对应分录行
     *
     * @param salesOrder
     * @param sourceentryid
     * @return
     */
    private DynamicObject getSalesOrderSameEntry(DynamicObject salesOrder, long sourceentryid) {
        DynamicObjectCollection collection = salesOrder.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject dynamicObject : collection) {
            long pkValue = (long) dynamicObject.getPkValue();
            if (pkValue == sourceentryid) {
                return dynamicObject;
            }
        }
        return null;
    }

    /**
     * 修改资源号，更新配件商品明细
     *
     * @param e
     */
    private void updatePartEntry(AfterDoOperationEventArgs e) {
//        OperationResult result = e.getOperationResult();
//        if (!result.isSuccess()) return;
//        IDataModel model = this.getModel();
//        DynamicObject dataEntity = model.getDataEntity(true);
//        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_accessorygoods");
//        long sourcebillid = dataEntity.getLong("yem_sourcebillid");
//        DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_es_salesorder");
//        DynamicObjectCollection salesEntry = salesOrder.getDynamicObjectCollection("yem_es_materialinfo");
//        for (DynamicObject proObj : collection) {
//            for (DynamicObject salesObj : salesEntry) {
//                long pkValue = (long) salesObj.getPkValue();
//                long source = proObj.getLong("yem_sourceentryid1");
//                if (source == pkValue) {
//                    DynamicObject resourcenog = salesObj.getDynamicObject("yem_resourcenog");
//                    if (YEM.isNotEmpty(resourcenog)) {
//
//                        proObj.set("yem_resourcenog1", resourcenog.getPkValue());
//                    }
//                }
//            }
//        }
//        IFormView view = this.getView();
//        SaveServiceHelper.update(dataEntity);
//        view.invokeOperation("refresh");
    }

    /**
     * 更新合同资源号
     * 业务：做合同时，资源号未出且存在需要关联资源号的配件，合同无法进行
     * <p>
     * 1、外销合同明细信息增加字段：关联整机行号（整数），配件的价格属于整机时，维护配件行的关联整机行号，维护后，计算整机的价格（同配件行选择资源号时的计算逻辑）；
     * 2、关联整机行号携带到产品经理下单确认的配件商品明细页签（该新增字段）；
     * 3、产品经理确认资源号时，整机行回填资源号逻辑不变，同时将  【配件商品明细中】 关联整机行号  和  【整机商品明细行号】一致的配件行回填  该整机行的资源号，存在多行整机分别对应多行配件的情况，需同步处理；
     * 4、产品经理根据业务在配件行填写的关联整机行号，维护该配件的关联资源号，资源确认时，将配件商品明细中的资源号回填到外销合同的关联行，目前配件商品明细没有回填功能；
     * 注：序号3和序号4两种方案待确认
     *
     * @param e
     * @param selectRows
     */
    private void updateSalesOrderPrice(AfterDoOperationEventArgs e, int[] selectRows) {
        Updatematerielpj();
        updatematerielzj();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        long sourcebillid = dataEntity.getLong("yem_sourcebillid");
        DynamicObject salesOrder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder", new QFilter[]{new QFilter("id", QCP.equals, sourcebillid)});
        if (YEM.isEmpty(salesOrder)) return;
        DynamicObjectCollection salesEntry = salesOrder.getDynamicObjectCollection("yem_es_materialinfo");
        //  整机行 - 关联配件行
        Map<Long, Long> map = new HashMap<>();

        for (int selectRow : selectRows) {
            DynamicObject proObj = collection.get(selectRow);
            long sourceentryid = proObj.getLong("yem_sourceentryid");
            for (DynamicObject salesObj : salesEntry) {
                long partPkId = (long) salesObj.getPkValue();
                long incompid = salesObj.getLong("yem_incompid");
                if (sourceentryid == incompid) {
                    map.put(incompid, partPkId);
                }
            }
        }

        // 需要更新的行号 - 更新的资源号
        Map<Integer, DynamicObject> update = new HashMap<>();

        for (Map.Entry<Long, Long> entry : map.entrySet()) {
            // 整机行
            Long key = entry.getKey();

            // 关联配件行
            Long value = entry.getValue();

            DynamicObject resource = getCompLineResourceNo(salesEntry, key);
            if (YEM.isNotEmpty(resource)) {
                for (DynamicObject object : salesEntry) {
                    long id = object.getLong("id");
                    if (id == value) {
                        int index = salesEntry.indexOf(object);
                        update.put(index, resource);
                    }
                }
            }
        }

        long billId = salesOrder.getLong("id");
        IFormView view = this.getView();
        FormShowParameter fsp = view.getFormShowParameter();
        String appId = fsp.getAppId();

        final String formId = "yem_es_salesorder";
        BillShowParameter para = new BillShowParameter();

        para.setFormId(formId);
        para.setPkId(billId);
        para.setAppId(appId);

        FormConfigFactory.createConfigInCurrentAppService(para);
        final SessionManager sm = SessionManager.getCurrent();
        final IFormView formView = sm.getView(para.getPageId());
        if (formView != null) {

            formView.getFormShowParameter().setAppId(appId);
            formView.getModel().createNewData();
            formView.updateView();

        } else {
            throw new KDBizException("创建对应合同视图失败！");
        }

        BillModel mode = (BillModel) formView.getModel();
        mode.setPKValue(billId);
        mode.load(billId);

        if (YEM.isEmpty(mode)) {
            throw new KDBizException("创建对应合同模型失败！");
        }

        for (Map.Entry<Integer, DynamicObject> entry : update.entrySet()) {
            Integer idx = entry.getKey();
            DynamicObject resourceNo = entry.getValue();
            mode.setValue("yem_resourcenog", resourceNo, idx);
        }
        formView.updateView();
        DynamicObject salesOrderUpdated = mode.getDataEntity(true);

        DynamicObjectCollection materialinfo = salesOrderUpdated.getDynamicObjectCollection("yem_es_materialinfo");

        for (Map.Entry<Long, Long> entry : map.entrySet()) {
            // 整机行
            Long key = entry.getKey();

            // 关联配件行
            Long value = entry.getValue();

            for (DynamicObject dynamicObject : materialinfo) {
                int currIdx = materialinfo.indexOf(dynamicObject);
                long id = dynamicObject.getLong("id");
                DynamicObject resourceNo = getCompLineResourceNo(salesEntry, key);
                DynamicObject productmodel = getCompLineProductModelNo(salesEntry, key);
                if (id == value) {
                    mode.setValue("yem_resourcenog", resourceNo, currIdx);
                    String resourceNum = "";
                    if (YEM.isNotEmpty(resourceNo)) {
                        resourceNum = resourceNo.getString("number");
                    }
                    int index = 0;
                    for (DynamicObject object : salesEntry) {
                        int idx = salesEntry.indexOf(object);
                        Long pkValue = (Long) object.getPkValue();
                        if (Objects.equals(pkValue, key)) {
                            index = idx;
                        }
                    }
                    String productmodelStr = "null";
                    if (YEM.isNotEmpty(productmodel)) {
                        productmodelStr = productmodel.getString("number");
                    }
                    final String KEY = (index + 1) + "_" + productmodelStr + "_" + resourceNum;

                    dynamicObject.set("yem_incomptext", KEY);
                }
            }
        }

        formView.updateView();

        salesOrderUpdated = mode.getDataEntity(true);

        DynamicObjectCollection shippingplan = salesOrderUpdated.getDynamicObjectCollection("yem_shippingplan_entry");

        DynamicObjectCollection es_materialinfo = salesOrderUpdated.getDynamicObjectCollection("yem_es_materialinfo");

        for (DynamicObject dynamicObject : es_materialinfo) {
            long detailId = (long) dynamicObject.getPkValue();
            for (DynamicObject object : shippingplan) {
                DynamicObjectCollection subCollection = object.getDynamicObjectCollection("yem_plandetail_entry");
                for (DynamicObject subObject : subCollection) {
                    long srcentryid = subObject.getLong("yem_srcentryid");
                    if (srcentryid == detailId) {
                        DynamicObject resourcenog = dynamicObject.getDynamicObject("yem_resourcenog");
                        if (YEM.isNotEmpty(resourcenog)) {

                            resourcenog = BusinessDataServiceHelper.loadSingle(resourcenog.getPkValue(), resourcenog.getDynamicObjectType().getName());
                            subObject.set("yem_resourcenog1", resourcenog);
                            // 资源配置描述
//                            subObject.set("yem_typeconfiguration1", resourcenog.getString("yem_zhdescription"));
                        }

                        DynamicObject materiel = dynamicObject.getDynamicObject("yem_materiel");

                        if (YEM.isNotEmpty(materiel)) {
                            materiel = BusinessDataServiceHelper.loadSingle(materiel.getPkValue(), materiel.getDynamicObjectType().getName());

                            subObject.set("yem_materiel2", materiel);
                            // 物料名称 规格型号 物料英文名称
                            subObject.set("yem_materialname1", materiel.getString("name"));
                            subObject.set("yem_materialenname1", materiel.getString("yem_nameen"));
                            subObject.set("yem_specification1", materiel.getString("modelnum"));
                            subObject.set("yem_unit2", materiel.getDynamicObject("baseunit"));
                            subObject.set("yem_baseunit1", materiel.getDynamicObject("baseunit"));
                        }
                    }
                }
            }
        }
        formView.updateView();
        salesOrderUpdated = mode.getDataEntity(true);
        SaveServiceHelper.update(salesOrderUpdated);
    }

    private DynamicObject getCompLineResourceNo(DynamicObjectCollection salesEntry, Long value) {
        for (DynamicObject object : salesEntry) {
            Long pkValue = (Long) object.getPkValue();
            if (Objects.equals(pkValue, value)) {
                return object.getDynamicObject("yem_resourcenog");
            }
        }
        return null;
    }

    private DynamicObject getCompLineProductModelNo(DynamicObjectCollection salesEntry, Long value) {
        for (DynamicObject object : salesEntry) {
            Long pkValue = (Long) object.getPkValue();
            if (Objects.equals(pkValue, value)) {
                return object.getDynamicObject("yem_productmodel");
            }
        }
        return null;
    }

    /**
     * // 物料的长、宽、高必须维护(判断当前行物料信息上的数据)，否则不允许确认
     */
    private void checkVolumeInfoInput() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObject transportmode = dataEntity.getDynamicObject("yem_transportmode");
        if (YEM.isEmpty(transportmode)) return;

        transportmode = BusinessDataServiceHelper.loadSingle(transportmode.getPkValue(), transportmode.getDynamicObjectType().getName());
        boolean checkvolume = transportmode.getBoolean("yem_checkvolume");
        if (checkvolume) return;

        StringBuilder sb = new StringBuilder();
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject object : collection) {
            int index = collection.indexOf(object);
            DynamicObject materiel = object.getDynamicObject("yem_materiel");
            if (YEM.isEmpty(materiel)) continue;
            Long pkValue = (Long) materiel.getPkValue();
            materiel = BusinessDataServiceHelper.loadSingle(pkValue, materiel.getDynamicObjectType().getName());
            BigDecimal length = materiel.getBigDecimal("length");
            BigDecimal width = materiel.getBigDecimal("width");
            BigDecimal height = materiel.getBigDecimal("height");
            if (YEM.isEmpty(length) || YEM.isEmpty(width) || YEM.isEmpty(height)) {
                sb.append(String.format("商品明细第 [ %s ] 行，物料 [ %s ] 的长宽高信息未维护，请及时维护!\n",
                        (index + 1),
                        materiel.getString("name"))
                );
            }
        }

        if (sb.length() > 0) {
            throw new KDBizException(sb.toString());
        }
    }


    /**
     * 资源确认时 更新源外销合同 影响调拨价
     *
     * @param selectRow
     */
    private void updateOriginFormImpactPrice(int selectRow) {
        IDataModel model = this.getModel();
        // 商品明细
        DynamicObjectCollection collection = model.getEntryEntity("yem_es_materialinfo");
        DynamicObject dynamicObject = collection.get(selectRow);

        DynamicObjectCollection prodMulticonfig = dynamicObject.getDynamicObjectCollection("yem_multiconfig");
        Map<String, String> strongPrise = new HashMap<>();
        for (DynamicObject object : prodMulticonfig) {
            String yem_configentryid = object.getString("yem_configentryid");
            strongPrise.put(yem_configentryid, object.getString("yem_impactprice1"));
        }

        // 外销合同id
        long sourcebillid = dynamicObject.getLong("yem_sourcebillid_d");
        // 外销合同分录id
        long sourceentryid = dynamicObject.getLong("yem_sourceentryid");
        DynamicObject esSalesorder = BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_es_salesorder");
        // 外销合同商品明细
        DynamicObjectCollection esMaterialinfo = esSalesorder.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject object : esMaterialinfo) {
            Long pkValue = (Long) object.getPkValue();
            if (pkValue == sourceentryid) {
                object.set("yem_impactprice", dynamicObject.getString("yem_impactprice"));
                // 对应多功能配置页签
                DynamicObjectCollection multiconfig = object.getDynamicObjectCollection("yem_multiconfig");
                for (int i = 0; i < multiconfig.size(); i++) {
                    DynamicObject dynamicObject1 = multiconfig.get(i);
                    String yem_configentryid = dynamicObject1.getString("yem_configentryid");
                    if (strongPrise.containsKey(yem_configentryid)) {
                        multiconfig.get(i).set("yem_impactprice1", strongPrise.get(yem_configentryid));
                    }
                }
            }
        }

        SaveServiceHelper.save(new DynamicObject[]{esSalesorder});
    }

    /**
     * 加装方案说明必录校验
     *
     * @param e
     */
    private void checkProjectDesc(AfterDoOperationEventArgs e) {
        DynamicObject dataEntity = this.getModel().getDataEntity();
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        for (int i = 0; i < collection.size(); i++) {
            // 是否进行加装为是
            if ("A".equals(collection.get(i).getString("yem_isreloading"))) {
                // 加装方案说明
                String projectdesc = collection.get(i).getString("yem_projectdesc");

                if (projectdesc == null || projectdesc.isEmpty()) {
                    this.getView().showErrorNotification("商品明细第" + (i + 1) + "行，加装方案说明为必填项");
                }
            }
        }
    }

    @Override
    public void entryRowClick(RowClickEvent evt) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        EntryGrid entryGrid = (EntryGrid) evt.getSource();
        String key = entryGrid.getKey();
        int row = evt.getRow();
        if ("yem_es_materialinfo".equals(key)) {
            if (row >= 0) {
                DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
                DynamicObject dynamicObject = entity.get(row);
                DynamicObject yemProd = dynamicObject.getDynamicObject("yem_prod");
                if (yemProd != null) {
                    view.setEnable(false, row, "yem_isreloading", "yem_resourcenog");
                    view.setEnable(false, "yem_retrofitting", "yem_advconbaritemap5", "yem_advconbaritemap6");
                } else {
                    view.setEnable(true, row, "yem_isreloading", "yem_resourcenog");
                    view.setEnable(true, "yem_retrofitting", "yem_advconbaritemap5", "yem_advconbaritemap6");
                }
            }
        }
    }

    /**
     * 赋值背景色
     *
     * @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);  //获取选中行的单据体数据
            Date yemResource = dynamicObject.getDate("yem_confirmationdate");
            if (Type.equals("A")) {
                if (yemResource != null) {
                    sreloading.add(i);
                }
            }
            if (Type.equals("B")) {
                if (yemResource == null) {
                    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());
            }
            if (Type.equals("A")) {
                entryGrid.setRowBackcolor("rgba(251,35,35,0.1)", selectRows);
            }
            if (Type.equals("B")) {
                entryGrid.setRowBackcolor("#ffffff", selectRows);
            }
        }
    }

    public List resourceno(Map map, int selectRows[]) {
        List list = new ArrayList();
        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
        if (selectRows != null && selectRows.length > 0) {
            for (int selectRow : selectRows) {
                DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
                String seq = dynamicObject.getString("seq");
                String yem_sourceentryid = dynamicObject.getString("yem_sourceentryid");
                DynamicObject yem_resourcenog = dynamicObject.getDynamicObject("yem_resourcenog");
                if (yem_resourcenog != null) {
                    String number = yem_resourcenog.getString("number");
                    String mapnumber = map.get(yem_sourceentryid).toString();
                    if (!number.equals(mapnumber)) {
                        String mag = "当前【" + seq + "】行对应的合同资源【" + mapnumber + "】已经下单确认过，不能进行调整资源，请调整合同数据！";
                        list.add(mag);
                    }
                }
            }
        }
        return list;
    }

    public void lockresourceno() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObjectCollection yem_es_materialinfo = this.getModel().getEntryEntity("yem_es_materialinfo");//商品
        for (int i = 0; i < yem_es_materialinfo.size(); i++) {
            DynamicObject dynamicObject = yem_es_materialinfo.get(i);
            DynamicObject yemProd = dynamicObject.getDynamicObject("yem_prod");
            if (yemProd != null) {
                view.setEnable(false, i, "yem_isreloading", "yem_resourcenog", "yem_materiel");
            } else {
                view.setEnable(true, i, "yem_isreloading", "yem_resourcenog", "yem_materiel");
            }
        }
        if (yem_es_materialinfo.size() > 0) {
            DynamicObject dynamicObject = yem_es_materialinfo.get(0);
            DynamicObject yemProd = dynamicObject.getDynamicObject("yem_prod");
            if (yemProd != null) {
                view.setEnable(false, "yem_retrofitting", "yem_advconbaritemap5", "yem_advconbaritemap6");
            } else {
                view.setEnable(true, 0, "yem_isreloading", "yem_resourcenog", "yem_materiel");
            }
        }

    }

    @Override
    public void hyperLinkClick(HyperLinkClickEvent e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String fieldName = e.getFieldName();
        int rowIndex = e.getRowIndex();
        switch (fieldName) {
            case "yem_sourceapplyno":
                ZJUtils.openSourceApply(view, model, rowIndex);
                break;
        }
    }

    /**
     * 获取配件跟单任务控制台数据
     */
    public void GetTracktaskconsole() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        String yemContractnumber = dataEntity.getString("yem_contractnumber");
        String billno = dataEntity.getString("billno");
        String[] split = billno.split("-");//EHTR-SXM231219-03-01-ZJ
        if (!YEM.isEmpty(yemContractnumber)) {
            QFilter qFilter = new QFilter("yem_billtype.number", QCP.equals, "yem_tracktaskconsole_pj");
            qFilter.and(new QFilter("yem_contractnumber", QCP.equals, yemContractnumber));
            if (split.length >= 3) {
                qFilter.and(new QFilter("yem_lotno", QCP.equals, split[3]));
            }
            DynamicObject yem_tracktaskconsole = BusinessDataServiceHelper.loadSingle("yem_tracktaskconsole", "id", new QFilter[]{qFilter});
            if (yem_tracktaskconsole != null) {
                DynamicObject yemtracktaskconsole = BusinessDataServiceHelper.loadSingle(yem_tracktaskconsole.getLong("id"), "yem_tracktaskconsole");
                if (yemtracktaskconsole != null) {
                    DynamicObjectCollection yemEsMaterialinfo = yemtracktaskconsole.getDynamicObjectCollection("yem_es_materialinfo");
                    if (yemEsMaterialinfo.size() > 0) {
                        SetAccessoryGoods(yemEsMaterialinfo, yemtracktaskconsole);
                    }
                }
            }
        }
    }

    /**
     * 配件商品明细赋值
     */
    public void SetAccessoryGoods(DynamicObjectCollection yemEsMaterialinfo, DynamicObject yemtracktaskconsole) {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yemEsAccessorygoods = dataEntity.getDynamicObjectCollection("yem_es_accessorygoods");
        yemEsAccessorygoods.clear();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        model.setValue("yem_gdrwkztid", yemtracktaskconsole.getLong("id"));
        model.deleteEntryData("yem_es_accessorygoods");
        for (int i = 0; i < yemEsMaterialinfo.size(); i++) {
            DynamicObject dynamicObject = yemEsMaterialinfo.get(i);
            int row = model.createNewEntryRow("yem_es_accessorygoods");
            model.setValue("yem_orderholder1", dynamicObject.getDynamicObject("yem_orderholder"), row);
            model.setValue("yem_confirmationdate1", dynamicObject.getDate("yem_confirmationdate"), row);
            model.setValue("yem_productstat1", dynamicObject.getString("yem_productstat"), row);

            model.setValue("yem_trackid", yemtracktaskconsole.getString("id"), row);
            model.setValue("yem_tracktaskid", dynamicObject.getLong("id"), row);
            model.setValue("yem_businesssort1", dynamicObject.getString("yem_businesssort"), row);
//            Accessorygoods.set("yem_ifreformg2", dynamicObject.getString("yem_ifreformg"));
//            Accessorygoods.set("yem_reformdesg2", dynamicObject.getString("yem_reformdesg"));
//            Accessorygoods.set("yem_projectdesc1", dynamicObject.getString("yem_projectdesc"));
//            Accessorygoods.set("yem_ifsupportg2", dynamicObject.getString("yem_ifsupportg"));
            model.setValue("yem_materialprop1", dynamicObject.getString("yem_materialprop"), row);
            model.setValue("yem_materiel2", dynamicObject.getDynamicObject("yem_materiel"), row);
            model.setValue("yem_isgift1", dynamicObject.getBoolean("yem_isgift"), row);
            model.setValue("yem_resourcenog1", dynamicObject.getDynamicObject("yem_resourcenog"), row);
            model.setValue("yem_materialname1", dynamicObject.getString("yem_materialname"), row);
//            model.setValue("yem_materialenname1", dynamicObject.getString("yem_materialenname"), row);
            model.setValue("yem_specification1", dynamicObject.getString("yem_specification"), row);
            model.setValue("yem_unit2", dynamicObject.getDynamicObject("yem_unit"), row);
            model.setValue("yem_qty2", dynamicObject.getBigDecimal("yem_qty"), row);
            model.setValue("yem_hqty1", dynamicObject.getBigDecimal("yem_hqty"), row);
            model.setValue("yem_nqty1", dynamicObject.getBigDecimal("yem_nqty"), row);
            model.setValue("yem_baseunit1", dynamicObject.getDynamicObject("yem_baseunit"), row);
            model.setValue("yem_baseqty1", dynamicObject.getBigDecimal("yem_baseqty"), row);
            model.setValue("yem_remarks1", dynamicObject.getString("yem_remarks"), row);
            model.setValue("yem_price1", dynamicObject.getBigDecimal("yem_price"), row);
            model.setValue("yem_amt1", dynamicObject.getBigDecimal("yem_amt"), row);
            model.setValue("yem_locamt1", dynamicObject.getBigDecimal("yem_locamt"), row);
//            model.setValue("yem_inventoryqty1", dynamicObject.getBigDecimal("yem_inventoryqty"), row);
//            model.setValue("yem_inventorydiff1", dynamicObject.getString("yem_inventorydiff"), row);
            model.setValue("yem_sourcebilltype_e1", dynamicObject.getString("yem_sourcebilltype_e"), row);
            model.setValue("yem_sourcebillno_d1", dynamicObject.getString("yem_sourcebillno_d"), row);
            model.setValue("yem_sourcebillid_d1", dynamicObject.getLong("yem_sourcebillid_d"), row);
            model.setValue("yem_sourceentryid1", dynamicObject.getLong("yem_sourceentryid"), row);
            model.setValue("yem_corebilltype_e1", dynamicObject.getString("yem_corebilltype_e"), row);
            model.setValue("yem_corebillno_d1", dynamicObject.getString("yem_corebillno_d"), row);
            model.setValue("yem_corebillid_d1", dynamicObject.getLong("yem_corebillid_d"), row);
            model.setValue("yem_coreentryid1", dynamicObject.getLong("yem_coreentryid"), row);
            model.setValue("yem_tracktaskentrryid1", dynamicObject.getLong("yem_tracktaskentrryid"), row);
        }
//        this.getView().updateView("yem_es_materialinfo");
    }


    /**
     * 更新外销合同、下单审批物料编码(配件信息)
     */
    public void Updatematerielpj() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        long yem_sourcebillid = dataEntity.getLong("yem_sourcebillid");//来源单据id(外销合同id)
        DynamicObjectCollection yem_es_accessorygoods = dataEntity.getDynamicObjectCollection("yem_es_accessorygoods");
        if (yem_sourcebillid > 0) {
            DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle(yem_sourcebillid, "yem_es_salesorder");
            if (yem_es_salesorder != null) {
                DynamicObjectCollection yem_es_materialinfo = yem_es_salesorder.getDynamicObjectCollection("yem_es_materialinfo");
                for (int i = 0; i < yem_es_accessorygoods.size(); i++) {
                    DynamicObject dynamicObject = yem_es_accessorygoods.get(i);
                    long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid1");
                    for (int j = 0; j < yem_es_materialinfo.size(); j++) {
                        DynamicObject dynamicObject1 = yem_es_materialinfo.get(j);
                        long id = dynamicObject1.getLong("id");
                        if (yem_sourceentryid == id) {
                            DynamicObject yem_materiel2 = dynamicObject.getDynamicObject("yem_materiel2");
                            dynamicObject1.set("yem_materiel", yem_materiel2);
                            if (yem_materiel2 != null) {
                                dynamicObject1.set("yem_materialname", yem_materiel2.getString("name"));
                                dynamicObject1.set("yem_materialenname", yem_materiel2.getString("yem_nameen"));
                                dynamicObject1.set("yem_specification", yem_materiel2.getString("modelnum"));
                                dynamicObject1.set("yem_unit", yem_materiel2.getDynamicObject("baseunit"));
                                dynamicObject1.set("yem_baseunit", yem_materiel2.getDynamicObject("baseunit"));
                            }
                            dynamicObject1.set("yem_materiel", dynamicObject.get("yem_materiel2"));

                            DynamicObject resourcenog1 = dynamicObject.getDynamicObject("yem_resourcenog1");
                            if (YEM.isNotEmpty(resourcenog1)) {

                                dynamicObject1.set("yem_resourcenog", dynamicObject.get("yem_resourcenog1"));
                                dynamicObject1.set("yem_tconfiguration", resourcenog1.getString("yem_zhdescription"));
                            }
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{yem_es_salesorder});
            }
        }
    }

    private void updatematerielzj() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        long yem_sourcebillid = dataEntity.getLong("yem_sourcebillid");//来源单据id(外销合同id)
        DynamicObjectCollection yem_es_accessorygoods = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        if (yem_sourcebillid > 0) {
            DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle(yem_sourcebillid, "yem_es_salesorder");
            if (yem_es_salesorder != null) {
                DynamicObjectCollection yem_es_materialinfo = yem_es_salesorder.getDynamicObjectCollection("yem_es_materialinfo");
                for (int i = 0; i < yem_es_accessorygoods.size(); i++) {
                    DynamicObject dynamicObject = yem_es_accessorygoods.get(i);
                    long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid");
                    for (int j = 0; j < yem_es_materialinfo.size(); j++) {
                        DynamicObject dynamicObject1 = yem_es_materialinfo.get(j);
                        long id = dynamicObject1.getLong("id");
                        if (yem_sourceentryid == id) {
                            DynamicObject yem_materiel2 = dynamicObject.getDynamicObject("yem_materiel");
                            dynamicObject1.set("yem_materiel", yem_materiel2);
                            if (yem_materiel2 != null) {
                                dynamicObject1.set("yem_materialname", yem_materiel2.getString("name"));
                                dynamicObject1.set("yem_materialenname", yem_materiel2.getString("yem_nameen"));
                                dynamicObject1.set("yem_specification", yem_materiel2.getString("modelnum"));
                                dynamicObject1.set("yem_unit", yem_materiel2.getDynamicObject("baseunit"));
                                dynamicObject1.set("yem_baseunit", yem_materiel2.getDynamicObject("baseunit"));
                            }
                            dynamicObject1.set("yem_materiel", dynamicObject.get("yem_materiel"));

                            DynamicObject resourcenog1 = dynamicObject.getDynamicObject("yem_resourcenog");
                            if (YEM.isNotEmpty(resourcenog1)) {

                                dynamicObject1.set("yem_resourcenog", dynamicObject.get("yem_resourcenog"));
                                dynamicObject1.set("yem_tconfiguration", resourcenog1.getString("yem_zhdescription"));
                            }
                        }
                    }
                }
                SaveServiceHelper.save(new DynamicObject[]{yem_es_salesorder});
            }
        }
    }

    /**
     * 更新外销合同、下单审批物料编码(配件信息)
     */
    public void Updatematerielzj() {
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        long yem_sourcebillid = dataEntity.getLong("yem_sourcebillid");//来源单据id(外销合同id)
        DynamicObjectCollection yem_es_accessorygoods = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        if (yem_sourcebillid > 0) {
            DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle(yem_sourcebillid, "yem_es_salesorder");
            if (yem_es_salesorder != null) {
                DynamicObjectCollection yem_es_materialinfo = yem_es_salesorder.getDynamicObjectCollection("yem_es_materialinfo");
                for (int i = 0; i < yem_es_accessorygoods.size(); i++) {
                    DynamicObject dynamicObject = yem_es_accessorygoods.get(i);
                    long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid1");
                    for (int j = 0; j < yem_es_materialinfo.size(); j++) {
                        DynamicObject dynamicObject1 = yem_es_materialinfo.get(i);
                        long id = dynamicObject1.getLong("id");
                        if (yem_sourceentryid == id) {
                            dynamicObject1.set("yem_materiel", dynamicObject.getDynamicObject("yem_materiel2"));
                        }
                    }
                }
                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 yem_es_materialinfo = yem_placeexamine.getDynamicObjectCollection("yem_es_materialinfo");
                    for (int i = 0; i < yem_es_accessorygoods.size(); i++) {
                        DynamicObject dynamicObject = yem_es_accessorygoods.get(i);
                        long yem_sourceentryid = dynamicObject.getLong("yem_sourceentryid1");
                        for (int j = 0; j < yem_es_materialinfo.size(); j++) {
                            DynamicObject dynamicObject1 = yem_es_materialinfo.get(i);
                            long id = dynamicObject1.getLong("id");
                            if (yem_sourceentryid == id) {
                                dynamicObject1.set("yem_materiel", dynamicObject.getDynamicObject("yem_materiel2"));
                            }
                        }
                    }
                    SaveServiceHelper.save(new DynamicObject[]{yem_placeexamine});
                }
            }
        }
    }
}
