package com.yem.em.ass.cmmptable.form;

import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;
import com.yem.em.utils.AtlasUtils;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

import static com.yem.em.utils.AtlasUtils.seelctDyn;

/**
 * @author zhouc
 * @date 2023/11/2 18:04
 * @className CMMPTableFormEdit
 * @description CMMP部件明细表表单插件
 */
public class CMMPTableFormEdit extends AbstractFormPlugin {
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        ChangeData[] changeData = e.getChangeSet();
        Object newValue = changeData[0].getNewValue();
        int row = changeData[0].getRowIndex();
        String key = e.getProperty().getName();
        int enrow = this.getModel().getEntryCurrentRowIndex("yem_entryentity");
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        if ("yem_asscomponent".equals(key)) {
            String yem_ccode = (String) model.getValue("yem_ccode", row);
            DynamicObject yem_asscomponent = (DynamicObject) model.getValue("yem_asscomponent", row);
            if (yem_asscomponent != null) {
                if (yem_ccode.length() > 0) {
                    model.setValue("yem_assname", yem_asscomponent.getString("name"), row);
                    model.setValue("yem_assqty", new BigDecimal(1), row);
                    QFilter qFilter = new QFilter("number", QCP.equals, yem_asscomponent.getString("number"));
                    DynamicObject yem_em_assatlasdet = BusinessDataServiceHelper.loadSingle("yem_em_assatlasdet", "id,name,number", qFilter.toArray());
                    if (yem_em_assatlasdet != null) {
                        model.setValue("yem_assatlasdet", yem_em_assatlasdet, row);
                    } else {
                        model.setValue("yem_assatlasdet", null, row);
                    }
                } else {
//                    model.setValue("yem_ccode", yem_asscomponent.getString("number"), row);
//                    model.setValue("yem_ccodename", yem_asscomponent.getString("name"), row);
                    model.setValue("yem_assname", yem_asscomponent.getString("name"), row);
//                    model.setValue("yem_qty", new BigDecimal(1), row);
                    model.setValue("yem_assqty", new BigDecimal(1), row);
                    QFilter qFilter = new QFilter("number", QCP.equals, yem_asscomponent.getString("number"));
                    DynamicObject yem_em_assatlasdet = BusinessDataServiceHelper.loadSingle("yem_em_assatlasdet", "id,name,number", qFilter.toArray());
                    if (yem_em_assatlasdet != null) {
                        model.setValue("yem_assatlasdet", yem_em_assatlasdet, row);
                    } else {
                        model.setValue("yem_assatlasdet", null, row);
                    }
                }
                model.setValue("yem_isnormal", true, row);
            } else {
                model.setValue("yem_assname", null, row);
                model.setValue("yem_assqty", null, row);
                model.setValue("yem_isnormal", false, row);
                model.setValue("yem_assatlasdet", null, row);
            }
        }
        if ("yem_assatlasdet".equals(key)) {
            DynamicObject yem_assatlasdet = (DynamicObject) model.getValue("yem_assatlasdet", row);
            if (yem_assatlasdet != null) {
                model.setValue("yem_isassatlasdet", true, row);
            } else {
                model.setValue("yem_isassatlasdet", false, row);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        //匹配总成部件
        if ("asscomponent".equals(operateKey)) {
            List list = new ArrayList<>();
            DynamicObjectCollection dynamicObjectCollection = dataEntity.getDynamicObjectCollection("yem_entryentity");
            for (int i = 0; i < dynamicObjectCollection.size(); i++) {
                DynamicObject dynamicObject = dynamicObjectCollection.get(i);
                String yem_ccode = dynamicObject.getString("yem_ccode");
                list.add(yem_ccode);
            }
            Map<String, String> getcomponentid = AtlasUtils.Getcomponentid(list);
            Map<String, String> getassatlasdet = AtlasUtils.Getassatlasdet(list);
            for (int i = 0; i < dynamicObjectCollection.size(); i++) {
                DynamicObject dynamicObject = dynamicObjectCollection.get(i);
                String yem_ccode = dynamicObject.getString("yem_ccode");
                if (getcomponentid.get(yem_ccode) != null) {
                    DynamicObject component = BusinessDataServiceHelper.loadSingle(getcomponentid.get(yem_ccode), "bd_material");
                    dynamicObject.set("yem_asscomponent", component);
                    dynamicObject.set("yem_isnormal", true);
                    dynamicObject.set("yem_assname", component.getString("name"));
                    dynamicObject.set("yem_assqty", new BigDecimal(1));
                }
                if (getassatlasdet.get(yem_ccode) != null) {
                    DynamicObject component = BusinessDataServiceHelper.loadSingle(getassatlasdet.get(yem_ccode), "yem_em_assatlasdet");
                    dynamicObject.set("yem_assatlasdet", component);
                    dynamicObject.set("yem_isassatlasdet", true);
                } else {
                    dynamicObject.set("yem_isassatlasdet", false);
                }
            }
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            this.getView().updateView("yem_entryentity");
            this.getView().showSuccessNotification("获取成功！");
        }
        if ("getcmmp".equals(operateKey)) {
            String yem_producttype = dataEntity.getString("yem_producttype");
            if (yem_producttype == null || yem_producttype.length() == 0) {
                this.getView().showErrorNotification("请选择产品类型后重试！");
                return;
            }
            DynamicObject yem_bd_productsgroup = seelctDyn("yem_bd_productsgroup", "number", yem_producttype);
            QFilter qFilter = new QFilter("number", QCP.equals, "110");
            DynamicObject bos_org = BusinessDataServiceHelper.loadSingle("bos_org", "id", qFilter.toArray());
            DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
            yem_entryentity.clear();
            String sql = "select distinct " + AtlasUtils.Queryfield("ccode", "qty") + "  from VIEW_BASE_ITEMSTRUC_WM where pcode='" + dataEntity.getString("number") + "'";
            List<Map> fromCmmp = RequestCmmp.getFromCmmp(bos_org.getLong("id"), sql, yem_bd_productsgroup.getLong("id"));
            Map<String, String> stringStringMap = AtlasUtils.GetasscomponentName(fromCmmp, "Ass");
            List list = new ArrayList<>();
            for (int k = 0; k < fromCmmp.size(); k++) {
                Map map = fromCmmp.get(k);
                if (map != null) {
                    DynamicObject dynamicObject = yem_entryentity.addNew();
                    list.add(map.get("ccode").toString());
                    String ccode = map.get("ccode").toString();
                    dynamicObject.set("yem_ccode", ccode);
                    dynamicObject.set("yem_ccodename", stringStringMap.get(ccode));
                    dynamicObject.set("yem_qty", map.get("qty").toString());
                    dynamicObject.set("yem_creationtime", new Date());
                }
            }
            Map<String, String> getcomponentid = AtlasUtils.Getcomponentid(list);
            Map<String, String> getassatlasdet = AtlasUtils.Getassatlasdet(list);
            for (int i = 0; i < yem_entryentity.size(); i++) {
                DynamicObject dynamicObject = yem_entryentity.get(i);
                String yem_ccode = dynamicObject.getString("yem_ccode");
                if (getcomponentid.get(yem_ccode) != null) {
                    DynamicObject component = BusinessDataServiceHelper.loadSingle(getcomponentid.get(yem_ccode), "bd_material");
                    dynamicObject.set("yem_asscomponent", component);
                    dynamicObject.set("yem_isnormal", true);
                    dynamicObject.set("yem_assname", component.getString("name"));
                    dynamicObject.set("yem_assqty", new BigDecimal(1));
                }
                if (getassatlasdet.get(yem_ccode) != null) {
                    DynamicObject component = BusinessDataServiceHelper.loadSingle(getassatlasdet.get(yem_ccode), "yem_em_assatlasdet");
                    dynamicObject.set("yem_assatlasdet", component);
                    dynamicObject.set("yem_isassatlasdet", true);
                } else {
                    dynamicObject.set("yem_isassatlasdet", false);
                }
            }
            this.getView().updateView("yem_entryentity");
            this.getView().showSuccessNotification("获取成功！");
        }
        if ("comparison".equals(operateKey)) {
            Map mapentryentity = new HashMap<>();
            Map mapexcelimport = new HashMap<>();
            DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
            for (int i = 0; i < yem_entryentity.size(); i++) {
                DynamicObject dynamicObject = yem_entryentity.get(i);
                mapentryentity.put(dynamicObject.getString("yem_ccode"), dynamicObject.getString("yem_ccodename"));
            }
            DynamicObjectCollection yem_excelimport = dataEntity.getDynamicObjectCollection("yem_excelimport");
            for (int j = 0; j < yem_excelimport.size(); j++) {
                DynamicObject dynamicObject = yem_excelimport.get(j);
                mapexcelimport.put(dynamicObject.getString("yem_assemblyno"), dynamicObject.getString("yem_assemblyname"));
            }
            MapDifference difference = Maps.difference(mapentryentity, mapexcelimport);
            if (difference.areEqual()) {
                dataEntity.set("yem_comparison", "A");
                dataEntity.set("yem_comparisonmag", "CMMP部件与导入一级部件相同！！");
                this.getView().showSuccessNotification("CMMP部件与导入一级部件相同！！");
            } else {
                dataEntity.set("yem_comparison", "B");
                StringBuffer yem_comparison = new StringBuffer();
                Map OnLeft = difference.entriesOnlyOnLeft();//BOM中没有
                Map Differing = difference.entriesDiffering();//名称不同
                Map InCommon = difference.entriesInCommon();//所有相同
                Map OnRight = difference.entriesOnlyOnRight();//CMMPno
                yem_comparison.append("根据资源号：【" + dataEntity.getString("number") + "】，对比结果如下：").append("\r\n");
                yem_comparison.append("  CMMP部件与一级部件总成对比相同条数为【" + InCommon.size() + "】条").append("\r\n");
                if (Differing.size() > 0) {
                    yem_comparison.append("  CMMP部件与一级部件总成对比编码相同名称不同的条数为【" + Differing.size() + "】条,详情如下：").append("\r\n");
                    yem_comparison.append("  " + Differing.toString()).append("\r\n");
                }
                if (OnLeft.size() > 0) {
                    yem_comparison.append("  CMMP部件中有，一级部件总成中没有的条数为【" + OnLeft.size() + "】条,详情如下：").append("\r\n");
                    yem_comparison.append("  " + OnLeft.toString()).append("\r\n");
                }
                if (OnRight.size() > 0) {
                    yem_comparison.append("  一级部件总成中有，CMMP总成中没有的条数为【" + OnRight.size() + "】条,详情如下：").append("\r\n");
                    yem_comparison.append("  " + OnRight.toString()).append("\r\n");
                }
                dataEntity.set("yem_comparisonmag", yem_comparison);
                this.getView().showSuccessNotification("对比完成，请查看对比结果页签！");
            }
            this.getView().updateView("yem_comparison");
            this.getView().updateView("yem_comparisonmag");
        }
        if ("isdisable".equals(operateKey)) {
            EntryGrid entryGrid = this.getControl("yem_entryentity");
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows.length > 0) {
                for (int row : selectRows) {
                    this.getView().getModel().setValue("yem_disablestat", "B", row);
                    this.getView().getModel().setValue("yem_disableuser", YEM.getCurrentUserId(), row);
                    this.getView().getModel().setValue("yem_disabledate", new Date(), row);
                }
                this.getView().invokeOperation("save");
                this.getView().showSuccessNotification("操作完成");
            } else {
                this.getView().showErrorNotification("请至少选择一行进行操作！");
            }
        }
        if ("notisdisable".equals(operateKey)) {
            EntryGrid entryGrid = this.getControl("yem_entryentity");
            int selectRows[] = entryGrid.getSelectRows();
            if (selectRows.length > 0) {
                for (int row : selectRows) {
                    this.getView().getModel().setValue("yem_disablestat", "A", row);
                    this.getView().getModel().setValue("yem_disableuser", null, row);
                    this.getView().getModel().setValue("yem_disabledate", null, row);
                }
                this.getView().invokeOperation("save");
                this.getView().showSuccessNotification("操作完成");
            } else {
                this.getView().showErrorNotification("请至少选择一行进行操作！");
            }
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        AbstractOperate operate = (AbstractOperate) args.getSource();
        String key = operate.getOperateKey();
        if ("asscomponent".equals(key)) {
            Boolean result = false;
            DynamicObjectCollection yem_entryentity = dataEntity.getDynamicObjectCollection("yem_entryentity");
            for (int i = 0; i < yem_entryentity.size(); i++) {
                DynamicObject object = yem_entryentity.get(i);
                int seq = i + 1;
                boolean yem_isadd = object.getBoolean("yem_isadd");
                if (yem_isadd) {
                    this.getView().showErrorNotification("部件详情第【" + seq + "】行为变更【新增】行，禁止获取CMMP部件！");
                    args.cancel = true;
                }
                boolean yem_isdelete = object.getBoolean("yem_isdelete");
                if (yem_isdelete) {
                    this.getView().showErrorNotification("部件详情第【" + seq + "】行为变更【删除】行，禁止获取CMMP部件！");
                    args.cancel = true;
                }
                boolean yem_partisreplace = object.getBoolean("yem_partisreplace");
                if (yem_partisreplace) {
                    this.getView().showErrorNotification("部件详情第【" + seq + "】行【已发生替换】，禁止获取CMMP部件！");
                    args.cancel = true;
                }
            }
        }
    }
}
