package com.yem.em.dynamic;

import com.yem.em.utils.SubRelationUtils;
import com.yem.wm.utils.StringUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.TreeView;
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.QueryServiceHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author zhouc
 * @date 2023/9/4 11:04
 * @className PartUnfoldDynamicEdit
 * @description 设备零件展开动态表单插件
 */
public class PartUnfoldDynamicEdit extends AbstractFormPlugin {
    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        IDataModel model = this.getModel();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
        if (customParas != null) {
            if (customParas.containsKey("pkId")) {
                String pkId = customParas.get("pkId").toString();
                getpartunfold(pkId, showParameter);
            }
        }
    }

    public void getpartunfold(String pkId, FormShowParameter showParameter) {
        //是否整机
        boolean isComplete = false;
        String yem_replacement = "Sub";
        String pageId = showParameter.getParentPageId();
        IFormView assepcdynamic = this.getView().getView(pageId);//设备电子目录
        Map<String, Object> customParas = assepcdynamic.getFormShowParameter().getCustomParams();
        if (customParas.containsKey("type")) {
            String type = customParas.get("type").toString();
            if (type.equals("atlas")) {
                yem_replacement = "Sub";
            }
            if (type.equals("assets")) {
                yem_replacement = "Par";
            }
        }
        Date yem_completetime = null;
        if (customParas.containsKey("yem_analysistdate")) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
                yem_completetime = sdf.parse(customParas.get("yem_analysistdate").toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if (customParas.containsKey("complete")) {
            if (customParas.get("complete") != null) {
                isComplete = true;
            }
        }

        String parentPage = getParentPage(showParameter);
        Map<String, Object> getnumber = getnumber(showParameter);
        if (getnumber == null) {
            return;
        }
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        //1.根据设备零件明细(新)id获取零件编码
        String yem_pnumber = "", subnumber = "", parnumber = "";
        QFilter qFilter = new QFilter("id", QCP.equals, Long.valueOf(pkId));
        DynamicObject yem_em_part = BusinessDataServiceHelper.loadSingle("yem_em_assatlaspartdet", "id,name,number", qFilter.toArray());
        if (yem_em_part != null) {
            yem_pnumber = yem_em_part.getString("number");//零件编码
        }

        if (getnumber.size() > 0) {
            subnumber = getnumber.get("id").toString();
            parnumber = getnumber.get("parentid").toString();
        }
        //2.根据
        if (StringUtils.isNotEmpty(yem_pnumber)) {
            Map<String, String> map = new HashMap<>();
            Map<String, String> verifymap = new HashMap<>();
            /**
             * 替换关系
             */
            DynamicObjectCollection emsubstitution = SubRelationUtils.queryAssemblyrepAll(subnumber, yem_pnumber, "Sub", isComplete, yem_completetime);
            if (emsubstitution != null && emsubstitution.size() > 0) {
                map = SetAssignMap(emsubstitution, parnumber);
            }
            /**
             * 根据原零件编码查询总成间替换关系，
             * 获取原子项信息 通过原子项信息获替换关系
             */
            if (map.size() > 0) {
                DynamicObjectCollection sub = SubRelationUtils.queryreplacetoass(map, "Sub", isComplete, yem_replacement, yem_completetime);
                if (sub != null && sub.size() > 0) {
                    SetAssign(sub);
                }
            }
            /**
             * 总成间替换关系，
             */
            DynamicObjectCollection assemtopart = SubRelationUtils.queryassemtopartAll(parnumber, subnumber, yem_pnumber, "rep", yem_replacement, isComplete, yem_completetime);
            if (assemtopart != null && assemtopart.size() > 0) {
                SetAssign(assemtopart);
            }
        }
        view.updateView("yem_entryentity");
    }

    public String getParentPage(FormShowParameter showParameter) {
        String formId = null;
        String pageId = showParameter.getParentPageId();
        IFormView assepcdynamic = this.getView().getView(pageId);//设备电子目录
        FormShowParameter assepcdynamicformShowParameter = assepcdynamic.getFormShowParameter();
        IFormView ass = this.getView().getView(assepcdynamicformShowParameter.getParentPageId());//设备电子目录
        formId = ass.getFormShowParameter().getFormId();
        return formId;
    }

    public Map<String, Object> getnumber(FormShowParameter showParameter) {
        Map<String, Object> focusNode = new HashMap<>();
        String pageId = showParameter.getParentPageId();
        IFormView assepcdynamic = this.getView().getView(pageId);
        TreeView treeView = assepcdynamic.getControl("yem_treeviewap");
        focusNode = treeView.getTreeState().getFocusNode();

        return focusNode;
    }

    /**
     * 设备零件展开 动态表单赋值
     *
     * @param assemtopart 数据结果集合
     */
    public void SetAssign(DynamicObjectCollection assemtopart) {
        IDataModel model = this.getModel();
        if (assemtopart != null && assemtopart.size() > 0) {
            Stream<DynamicObject> distinct = assemtopart.stream().distinct();
            distinct.forEach((DynamicObject obj) -> {
                String yem_praonumber = obj.getString("yem_entryentity.yem_praonumber");
                String yem_onumber = obj.getString("yem_entryentity.yem_onumber");
                String yem_repno = obj.getString("yem_entryentity.yem_repno");
                String yem_repnumber = obj.getString("yem_entryentity.yem_repnumber");
                Boolean verify = verify(yem_praonumber, yem_onumber, yem_repno, yem_repnumber);
                if (!verify) {
                    int row = model.createNewEntryRow("yem_entryentity");
                    model.setValue("yem_praonumber", obj.getString("yem_entryentity.yem_praonumber"), row);
                    model.setValue("yem_praoname", obj.getString("yem_entryentity.yem_praoname"), row);
                    model.setValue("yem_onumber", obj.getString("yem_entryentity.yem_onumber"), row);
                    model.setValue("yem_oname", obj.getString("yem_entryentity.yem_oname"), row);
                    model.setValue("yem_oenname", obj.getString("yem_entryentity.yem_oenname"), row);
                    model.setValue("yem_oqty", obj.getBigDecimal("yem_entryentity.yem_oqty"), row);
                    model.setValue("yem_repno", obj.getString("yem_entryentity.yem_repno"), row);
                    model.setValue("yem_repnoname", obj.getString("yem_entryentity.yem_repnoname"), row);
                    model.setValue("yem_repnumber", obj.getString("yem_entryentity.yem_repnumber"), row);
                    model.setValue("yem_repname", obj.getString("yem_entryentity.yem_repname"), row);
                    model.setValue("yem_repenname", obj.getString("yem_entryentity.yem_repenname"), row);
                    model.setValue("yem_repenqty", obj.getBigDecimal("yem_entryentity.yem_repenqty"), row);
                    model.setValue("yem_replace", obj.getString("yem_entryentity.yem_replace"), row);
                    model.setValue("yem_replacedate", obj.getDate("yem_entryentity.yem_completetime"), row);
                    model.setValue("yem_technology", obj.getDate("yem_entryentity.yem_technology"), row);
                    model.setValue("yem_trackingno", obj.getString("yem_entryentity.yem_trackingno"), row);
                    model.setValue("yem_remark", obj.getString("yem_entryentity.yem_remark"), row);
                    model.setValue("yem_alternatesource", "B", row);
                }
            });
        }
    }

    /**
     * 设备零件展开动态表单赋值
     *
     * @param assemtopart 数据结果集合
     */
    public Map<String, String> SetAssignMap(DynamicObjectCollection assemtopart, String Parnumber) {
        Map<String, String> map = new HashMap<>();
        IDataModel model = this.getModel();
        if (assemtopart != null && assemtopart.size() > 0) {
            if (assemtopart.size() > 0) {
                Stream<DynamicObject> distinct = assemtopart.stream().distinct();
                distinct.forEach((DynamicObject obj) -> {
                    String yem_praonumber = obj.getString("yem_entryentity.yem_praonumber");
                    String yem_onumber = obj.getString("yem_entryentity.yem_onumber");
                    String yem_repno = obj.getString("yem_entryentity.yem_repno");
                    String yem_repnumber = obj.getString("yem_entryentity.yem_repnumber");
                    Boolean verify = verify(yem_praonumber, yem_onumber, yem_repno, yem_repnumber);
                    if (!verify) {
                        int row = model.createNewEntryRow("yem_entryentity");
                        String mapkey = obj.getString("yem_entryentity.yem_praonumber") + "_" + obj.getString("yem_entryentity.yem_onumber");
                        if (!map.containsKey(mapkey)) {
                            map.put(mapkey, Parnumber);
                        }
                        model.setValue("yem_praonumber", obj.getString("yem_entryentity.yem_praonumber"), row);
                        model.setValue("yem_praoname", obj.getString("yem_entryentity.yem_praoname"), row);
                        model.setValue("yem_onumber", obj.getString("yem_entryentity.yem_onumber"), row);
                        model.setValue("yem_oname", obj.getString("yem_entryentity.yem_oname"), row);
                        model.setValue("yem_oenname", obj.getString("yem_entryentity.yem_oenname"), row);
                        model.setValue("yem_oqty", obj.getBigDecimal("yem_entryentity.yem_oqty"), row);
                        model.setValue("yem_repno", obj.getString("yem_entryentity.yem_repno"), row);
                        model.setValue("yem_repnoname", obj.getString("yem_entryentity.yem_repnoname"), row);
                        model.setValue("yem_repnumber", obj.getString("yem_entryentity.yem_repnumber"), row);
                        model.setValue("yem_repname", obj.getString("yem_entryentity.yem_repname"), row);
                        model.setValue("yem_repenname", obj.getString("yem_entryentity.yem_repenname"), row);
                        model.setValue("yem_repenqty", obj.getBigDecimal("yem_entryentity.yem_repenqty"), row);
                        model.setValue("yem_replace", obj.getString("yem_entryentity.yem_replace"), row);
                        model.setValue("yem_replacedate", obj.getDate("yem_entryentity.yem_completetime"), row);
                        model.setValue("yem_technology", obj.getDate("yem_entryentity.yem_technology"), row);
                        model.setValue("yem_trackingno", obj.getString("yem_entryentity.yem_trackingno"), row);
                        model.setValue("yem_remark", obj.getString("yem_entryentity.yem_remark"), row);
                        model.setValue("yem_alternatesource", "A", row);
                    }
                });
            }
        }
        return map;
    }

    public Boolean verify(String yem_praonumber, String yem_onumber, String yem_repno, String yem_repnumber) {
        String key = yem_praonumber + "" + yem_onumber + "" + yem_repno + "" + yem_repnumber;
        Boolean retr = false;
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_partunfold = dataEntity.getDynamicObjectCollection("yem_entryentity");
        if (yem_partunfold.size() > 0) {
            for (int i = 0; i < yem_partunfold.size(); i++) {
                DynamicObject object = yem_partunfold.get(i);
                String praonumber = object.getString("yem_praonumber");
                String onumber = object.getString("yem_onumber");
                String repno = object.getString("yem_repno");
                String repnumber = object.getString("yem_repnumber");
                String key1 = praonumber + "" + onumber + "" + repno + "" + repnumber;
                if (key.equals(key1)) {
                    retr = true;
                }
            }
        }
        return retr;
    }
}
