package com.yem.em.bd.etcmanual.dynamic;

import com.yem.em.utils.CommonEmUtils;
import com.yem.wm.utils.StringUtils;
import kd.bos.base.BaseShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.*;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.TreeView;
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.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.BillList;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.*;

/**
 * @author 夜子
 * @ClassName CreateResource
 * @description: 创建资源号
 * @date 2023年07月27日
 * @version: 1.0
 */
public class CreateResource  extends AbstractFormPlugin implements BeforeF7SelectListener {


    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> values = showParameter.getCustomParams();
        long OldEquipmentListID;
        long NewEquipmentListID = 0L;
        String type = "";
        if (null != values && values.size() > 0) {
            if(values.get("NewEquipmentListID")!=null){
                NewEquipmentListID = (long) values.get("NewEquipmentListID");
            }
            if(values.get("type")!=null){
                type = (String) values.get("type");
                this.getModel().setValue("yem_type", type);
            }
        }
        if(NewEquipmentListID!=0L){
            DynamicObject NewEquipment = BusinessDataServiceHelper.loadSingle(NewEquipmentListID, "yem_em_equipmentlist");

            //来源资源车型
            OldEquipmentListID = NewEquipment.getLong("yem_oldequipmentlistid");
            if(OldEquipmentListID!=0L){
                DynamicObject OldEquipment = BusinessDataServiceHelper.loadSingle(OldEquipmentListID, "yem_em_equipmentlist");
                this.getModel().setValue("yem_etcmanual", OldEquipment);
            }else{
                this.getView().setVisible(false,"yem_etcmanual");
            }
            if("modif".equals(type)){
                this.getModel().setValue("yem_resourcenum", NewEquipment.getString("number"));
                this.getModel().setValue("yem_resourcename", NewEquipment.getString("name"));
                this.getModel().setValue("yem_basemodelib", NewEquipment.get("yem_basemodelib"));
            }

            showEpcdynamic(NewEquipmentListID,null);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        Button btnok = this.getView().getControl("btnok");
        btnok.addClickListener(this);
        Button btncancel = this.getView().getControl("btncancel");
        btncancel.addClickListener(this);
        BasedataEdit yem_basemodelib = this.getView().getControl("yem_basemodelib");
        if (yem_basemodelib != null) {
            yem_basemodelib.addBeforeF7SelectListener(this);
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String key = e.getProperty().getName();
        DynamicObject bill =   this.getModel().getDataEntity(true);
        ListShowParameter ListshowParameter = (ListShowParameter) e.getFormShowParameter();
        if (key.equals("yem_basemodelib")) {
            FormShowParameter showParameter = this.getView().getFormShowParameter();
            Map<String, Object> values = showParameter.getCustomParams();
            long NewEquipmentListID = 0L;
            String type = "";
            if (null != values && values.size() > 0) {
                if(values.get("type")!=null){
                    type = (String) values.get("type");
                    this.getModel().setValue("yem_type", type);
                }
                if("modif".equals(type)){
                    if(values.get("NewEquipmentListID")!=null){
                        NewEquipmentListID = (long) values.get("NewEquipmentListID");
                    }
                }
            }

            List<Long> UsebasemodelibIDl =  CommonEmUtils.getUseEtcmanualist(NewEquipmentListID,false);
            QFilter q1 =  new QFilter("id", QFilter.not_in, UsebasemodelibIDl);
            ListshowParameter.getListFilterParameter().setFilter(q1);
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate) args.getSource();
        String itemKey = formOperate.getOperateKey();

        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> valuesOld = showParameter.getCustomParams();
        long NewEquipmentListID = 0L;
        if (null != valuesOld && valuesOld.size() > 0) {
            if(valuesOld.get("NewEquipmentListID")!=null){
                NewEquipmentListID = (long) valuesOld.get("NewEquipmentListID");
            }
        }

        String childPageId = this.getPageCache().get("childpageid");
        IFormView  childView = this.getView().getView(childPageId);
        TreeView treeView = childView.getControl("yem_treeviewap");
        Map<String, Object>  treeMap= treeView.getTreeState().getFocusNode();
        BillList billList = childView.getControl("yem_billlistap");
        ListSelectedRowCollection rowList = billList.getCurrentListAllRowCollection();
        ListSelectedRow ss = billList.getCurrentSelectedRowInfo();
        if ("addcomponent".equals(itemKey)) {
            if(NewEquipmentListID==0L){
                String essage = "资源车型异常，请联系管理员！";
                this.getView().showMessage(essage);
                args.setCancel(true);
            }
            if(treeMap==null){
                String essage = "请选择新增父节点（部件）！";
                this.getView().showMessage(essage);
                args.setCancel(true);
            }
        }
        if ("modifcomponent".equals(itemKey)) {
            if(treeMap==null){
                String essage = "请选择修改数据！";
                this.getView().showMessage(essage);
                args.setCancel(true);
            }
            if(treeMap!=null){
                if(StringUtils.isEmpty((String) treeMap.get("parentid"))){
                    String essage = "顶级节点数据不允许修改！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }
            }
        }
        if ("deletecomponent".equals(itemKey)) {
            if(treeMap==null){
                String essage = "请选择需删除数据！";
                this.getView().showMessage(essage);
                args.setCancel(true);
            }
            if(treeMap!=null){
                if(StringUtils.isEmpty((String) treeMap.get("parentid"))){
                    String essage = "顶级节点不允许删除！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }

                if(rowList.size()>0){
                    String essage = "请先删除对用零件明细！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }

                if((boolean)treeMap.get("isParent")){
                    String essage = "请先删除下级！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }

            }
        }
        if ("addpart".equals(itemKey)||"modifpart".equals(itemKey)||"deletepart".equals(itemKey)) {
            if(treeMap==null){
                String essage = "请选择部件节点！";
                this.getView().showMessage(essage);
                args.setCancel(true);
            }
            if(treeMap!=null){
                if(StringUtils.isEmpty((String) treeMap.get("parentid"))){
                    String essage = "请选择下级部件节点！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }
            }
            if ("modifpart".equals(itemKey)) {
                if(ss==null){
                    String essage = "请选择需修改零件数据！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }
            }
            if ("deletepart".equals(itemKey)) {
                if(ss==null){
                    String essage = "请选择需删除零件数据！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        boolean isSuccess = false;
        if (e.getOperationResult() != null) {
            isSuccess = e.getOperationResult().isSuccess();
        }
        String operateKey = e.getOperateKey();

        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> valuesOld = showParameter.getCustomParams();
        long NewEquipmentListID = 0L;
        if (null != valuesOld && valuesOld.size() > 0) {
            if(valuesOld.get("NewEquipmentListID")!=null){
                NewEquipmentListID = (long) valuesOld.get("NewEquipmentListID");
            }
        }

        String childPageId = this.getPageCache().get("childpageid");
        IFormView  childView = this.getView().getView(childPageId);
        TreeView treeView = childView.getControl("yem_treeviewap");
        Map<String, Object>  treeMap= treeView.getTreeState().getFocusNode();
        BillList billList = childView.getControl("yem_billlistap");
        ListSelectedRow ss = billList.getCurrentSelectedRowInfo();

        IFormView view = this.getView();
        BaseShowParameter  fsp = new BaseShowParameter();
        fsp.setStatus(OperationStatus.ADDNEW);
        fsp.getOpenStyle().setShowType(ShowType.Modal);
        StyleCss styleCss = new StyleCss();
        styleCss.setWidth("1200");
        styleCss.setHeight("800");
        fsp.getOpenStyle().setInlineStyleCss(styleCss);
        if (StringUtils.isNotEmpty(operateKey)&&isSuccess&&NewEquipmentListID!=0L) {
            if ("addcomponent".equals(operateKey)) {
                Map<String, Object> values = new HashMap<>();
                values.put("Nsttype", "creater");
                values.put("pid",Long.valueOf(treeMap.get("id").toString()));
                values.put("equipmentlistid", NewEquipmentListID);

                fsp.setCustomParams(values);
                CloseCallBack callBack = new CloseCallBack(this, "addcomponent");
                fsp.setCloseCallBack(callBack);
                fsp.setFormId("yem_em_component");
                view.showForm(fsp);

            }
            if ("modifcomponent".equals(operateKey)) {

                Map<String, Object> values = new HashMap<>();
                values.put("Nsttype", "modif");
                fsp.setCustomParams(values);
                CloseCallBack callBack = new CloseCallBack(this, "modifcomponent");
                fsp.setCloseCallBack(callBack);
                fsp.setFormId("yem_em_component");
                fsp.setPkId(treeMap.get("id"));
                view.showForm(fsp);

            }
            if ("deletecomponent".equals(operateKey)) {
                OperationResult componen_delte = OperationServiceHelper.executeOperate("delete", "yem_em_component",new Object[]{treeMap.get("id")}, null);
                if (!componen_delte.isSuccess()) {
                    String detailMessage1 = componen_delte.getMessage();
                    for (IOperateInfo errInfo1 : componen_delte.getAllErrorOrValidateInfo()) {
                        detailMessage1 =detailMessage1+ errInfo1.getMessage();
                    }
                    this.getView().showMessage(detailMessage1);
                }else{
                    this.getView().showSuccessNotification("删除成功！");
                    showEpcdynamic(NewEquipmentListID,treeMap);
                }
            }
            if ("addpart".equals(operateKey)) {
                Map<String, Object> values = new HashMap<>();
                values.put("Nsttype", "creater");
                values.put("pid",Long.valueOf(treeMap.get("id").toString()));
                values.put("equipmentlistid", NewEquipmentListID);

                fsp.setCustomParams(values);
                CloseCallBack callBack = new CloseCallBack(this, "addpart");
                fsp.setCloseCallBack(callBack);
                fsp.setFormId("yem_em_part");
                view.showForm(fsp);
            }
            if ("modifpart".equals(operateKey)) {
                Map<String, Object> values = new HashMap<>();
                values.put("Nsttype", "modif");
                fsp.setCustomParams(values);
                CloseCallBack callBack = new CloseCallBack(this, "modifpart");
                fsp.setCloseCallBack(callBack);
                fsp.setFormId("yem_em_part");
                fsp.setPkId(ss.getPrimaryKeyValue());
                view.showForm(fsp);
            }
            if ("deletepart".equals(operateKey)) {

                OperationResult part_delte = OperationServiceHelper.executeOperate("delete", "yem_em_part",new Object[]{ss.getPrimaryKeyValue()}, null);
                if (!part_delte.isSuccess()) {
                    String detailMessage1 = part_delte.getMessage();
                    for (IOperateInfo errInfo1 : part_delte.getAllErrorOrValidateInfo()) {
                        detailMessage1 =detailMessage1+ errInfo1.getMessage();
                    }
                    this.getView().showMessage(detailMessage1);
                }else{
                    this.getView().showSuccessNotification("删除成功！");
                    showEpcdynamic(NewEquipmentListID,treeMap);
                }
            }
        }
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        Control source = (Control) evt.getSource();
        String key = source.getKey();
        Map<String, Object> values = new HashMap<>();
        if("btnok".equals(key)) {
            String yem_resourcenum= dataEntity.getString("yem_resourcenum");
            String yem_resourcename= dataEntity.getString("yem_resourcename");
            boolean isOk=true;
            StringBuilder msgStr = new StringBuilder();
            if (StringUtils.isEmpty(yem_resourcenum)) {
                msgStr.append("资源编号不能为空！");
                isOk=false;
            }
            if (StringUtils.isEmpty(yem_resourcename)) {
                msgStr.append("资源名称不能为空！");
                isOk=false;
            }
            if(!isOk) {
                this.getView().showErrorNotification(msgStr.toString());
            }else {
                this.getView().setReturnData("success");
                this.getView().close();
            }
        }
        if("btncancel".equals(key)) {
            this.getView().returnDataToParent(null);
            this.getView().close();
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);
        String actionId = closedCallBackEvent.getActionId();
        String childPageId = this.getPageCache().get("childpageid");
        IFormView  childView = this.getView().getView(childPageId);
        TreeView treeView = childView.getControl("yem_treeviewap");
        Map<String, Object>  treeMap= treeView.getTreeState().getFocusNode();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> values = showParameter.getCustomParams();
        long NewEquipmentListID = 0L;
        if (null != values && values.size() > 0) {
            if(values.get("NewEquipmentListID")!=null){
                NewEquipmentListID = (long) values.get("NewEquipmentListID");
            }
        }

        if (StringUtils.isNotEmpty(actionId)) {
            if ("addcomponent".equals(actionId)||"modifcomponent".equals(actionId)||"addpart".equals(actionId)||"modifpart".equals(actionId)) {
                if(NewEquipmentListID!=0L){
                    showEpcdynamic(NewEquipmentListID,treeMap);
                }
            }
        }
    }

    @Override
    public void beforeClosed(BeforeClosedEvent e) {
        super.beforeClosed(e);
        IFormView view = (IFormView) e.getSource();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> values = showParameter.getCustomParams();
        long NewEquipmentListID = 0L;
        String type = "";
        if (null != values && values.size() > 0) {
            if(values.get("NewEquipmentListID")!=null){
                NewEquipmentListID = (long) values.get("NewEquipmentListID");
            }
            if(values.get("type")!=null){
                type = (String) values.get("type");
            }
        }
        Object ReturnData=  view.getReturnData();
        if("success".equals(ReturnData)){
            String numberEqpLumbe = dataEntity.getString("yem_resourcenum");
            String yem_resourcename = dataEntity.getString("yem_resourcename");
            DynamicObject yem_basemodelib = dataEntity.getDynamicObject("yem_basemodelib");
            DynamicObject equipmentlis = BusinessDataServiceHelper.loadSingle(NewEquipmentListID, "yem_em_equipmentlist");
            String OldEqpLumber = equipmentlis.getString("number");
            //处理产品资源号问题
            equipmentlis.set("number",numberEqpLumbe);
            equipmentlis.set("name",yem_resourcename);
            equipmentlis.set("yem_basemodelib",yem_basemodelib);
            DynamicObjectCollection componentEntryCol = equipmentlis.getDynamicObjectCollection("yem_em_component");
            for(DynamicObject componentEntry:componentEntryCol){
                componentEntry.set("yem_basemodelib_c",yem_basemodelib);
                boolean yem_isepc_c = componentEntry.getBoolean("yem_isepc_c");
                String yem_longnumber_c =  componentEntry.getString("yem_longnumber_c");
                if(yem_isepc_c){
                    componentEntry.set("yem_number_c",numberEqpLumbe);
                    componentEntry.set("yem_cnumber_c",numberEqpLumbe);
                    componentEntry.set("yem_comname_c",yem_resourcename);
                }
                StringBuilder newlongnumber_c = new StringBuilder();
                String[] cnumberCOl = yem_longnumber_c.split("\\.");
                for(int i = 0 ; i<cnumberCOl.length;i++){
                    String cnumber = cnumberCOl[i];
                    if(cnumber.equals(OldEqpLumber)){
                        newlongnumber_c.append(numberEqpLumbe);
                    }else{
                        newlongnumber_c.append(cnumber);
                    }
                    if(i!=cnumberCOl.length-1){
                        newlongnumber_c.append(".");
                    }
                }
                componentEntry.set("yem_longnumber_c",newlongnumber_c);

                DynamicObjectCollection partEntryCol = componentEntry.getDynamicObjectCollection("yem_em_part");
                for(DynamicObject partEntry:partEntryCol){
                    partEntry.set("yem_basemodelib_p",yem_basemodelib);
                }
            }

            SaveServiceHelper.save(new DynamicObject[] { equipmentlis });
        }else if("fail".equals(ReturnData)){
            if("creater".equals(type)){

                OperateOption delteOption = OperateOption.create();
                delteOption.setVariableValue(OperateOptionConst.IGNOREWARN, String.valueOf(true)); // 不执行警告级别校验器
                delteOption.setVariableValue(OperateOptionConst.IGNOREINTERACTION, String.valueOf(true)); // 不显示交互提示，自动执行到底
                delteOption.setVariableValue(OperateOptionConst.STRICTVALIDATION, String.valueOf(false)); // 全部校验通过才保存
                OperationResult equipmentlist_delte = OperationServiceHelper.executeOperate("delete", "yem_em_equipmentlist",new Object[]{NewEquipmentListID}, delteOption);
                if (!equipmentlist_delte.isSuccess()) {
                    String detailMessage1 = equipmentlist_delte.getMessage();
                    for (IOperateInfo errInfo1 : equipmentlist_delte.getAllErrorOrValidateInfo()) {
                        detailMessage1 = detailMessage1+errInfo1.getMessage();
                    }
                    this.getView().showMessage(detailMessage1);
                }
            }

        }else{
            e.setCancel(true);
            if(StringUtils.isNotEmpty(type)&&NewEquipmentListID!=0L){
                String confirmTip = "页面即将关闭，是否保存当前数据？";
                if(type.equals("creater")){
                    confirmTip = "页面即将关闭，是否保存当前新增资源明细？";
                }
                if(type.equals("modif")){
                    confirmTip = "页面即将关闭，是否保存当前修改吗";
                }
                ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener(type, this);
                this.getView().showConfirm(confirmTip, MessageBoxOptions.YesNo, ConfirmTypes.Default, confirmCallBacks);
                //确认或取消之前取消后续操作
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        String key = messageBoxClosedEvent.getCallBackId();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if ("creater".equals(key)||"modif".equals(key)){
            // 判断如果是确认按钮
            if (messageBoxClosedEvent.getResult() == MessageBoxResult.Yes) {
                boolean issuccess = true;
                if(dataEntity.get("yem_resourcenum")==null){
                    String essage = "资源编号不能为空!";
                    issuccess = false;
                    this.getView().showMessage(essage);
                }
                if(dataEntity.get("yem_resourcename")==null){
                    String essage = "资源名称不能为空!";
                    issuccess = false;
                    this.getView().showMessage(essage);
                }
                if(dataEntity.get("yem_basemodelib")==null){
                    String essage = "产品资源号不能为空!";
                    issuccess = false;
                    this.getView().showMessage(essage);
                }
                if(issuccess){
                    this.getView().setReturnData("success");
                    this.getView().close();
                }
            }else{
                this.getView().setReturnData("fail");
                this.getView().close();
            }
        }

    }

    public void showEpcdynamic(long NewEquipmentListID, Map<String, Object>  treeMap){
        DynamicObject NewEquipment = BusinessDataServiceHelper.loadSingle(NewEquipmentListID, "yem_em_equipmentlist");
        FormShowParameter bsp = new FormShowParameter();
        bsp.setFormId("yem_em_epcdynamic");
        OpenStyle openStyle = new OpenStyle();
        openStyle.setShowType(ShowType.InContainer);
        openStyle.setTargetKey("yem_flexpanelap1");
        Map<String, Object> entryInfo = new HashMap<String, Object>();
        entryInfo.put("etcId", NewEquipment.getString("id"));
        entryInfo.put("number", NewEquipment.getString("number"));
        entryInfo.put("name", NewEquipment.getString("name"));
        entryInfo.put("orgId", NewEquipment.getDynamicObject("createorg").getLong("id"));
        entryInfo.put("treeMap", treeMap);
        bsp.setCustomParams(entryInfo);
        bsp.setHasRight(true);
        bsp.setStatus(OperationStatus.VIEW);
        bsp.setOpenStyle(openStyle);
        this.getPageCache().put("childpageid", bsp.getPageId());
        this.getView().showForm(bsp);
    }

}
