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

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.yem.wm.utils.StringUtils;
import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.resource.ResManager;
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.exception.KDBizException;
import kd.bos.form.*;
import kd.bos.form.events.*;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.org.utils.DynamicObjectUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;


/**
 * @author 夜子
 * @ClassName EtcmanualList
 * @description: 设备电子目录列表插件
 * @date 2023年07月25日
 * @version: 1.0
 */
public class EtcmanualList  extends AbstractListPlugin {

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate) args.getSource();
        String itemKey = formOperate.getOperateKey();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        ListSelectedRowCollection SelectedDataCol= formOperate.getListSelectedData();
        if(SelectedDataCol.size()>1){
            String essage = "请选择一行信息！";
            this.getView().showMessage(essage);
            args.setCancel(true);

        }
        if ("createrevehicle".equals(itemKey)) {
//            for(ListSelectedRow SelectedData:SelectedDataCol) {
//                DynamicObject bill = BusinessDataServiceHelper.loadSingle(SelectedData.getPrimaryKeyValue(), "yem_em_equipmentlist");
//                if(bill.getBoolean("yem_resourc")){
//                    String essage = "当前选择信息为资源号信息行,请选择基本车型电子目录信息行！";
//                    this.getView().showMessage(essage);
//                    args.setCancel(true);
//                }
//            }
            this.getView().showLoading(new LocaleString("加载中"));
        }
        if ("modifyevehicle".equals(itemKey)) {
            for(ListSelectedRow SelectedData:SelectedDataCol) {
                DynamicObject bill = BusinessDataServiceHelper.loadSingle(SelectedData.getPrimaryKeyValue(), "yem_em_equipmentlist");
                if(!bill.getBoolean("yem_resourc")){
                    String essage = "基础车型行不允许修改,请选择资源号信息行！";
                    this.getView().showMessage(essage);
                    args.setCancel(true);
                }
            }

        }
        if ("deleteevehicle".equals(itemKey)) {
            for(ListSelectedRow SelectedData:SelectedDataCol) {
                DynamicObject bill = BusinessDataServiceHelper.loadSingle(SelectedData.getPrimaryKeyValue(), "yem_em_equipmentlist");
                if(!bill.getBoolean("yem_resourc")){
                    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();
        FormOperate formOperate = (FormOperate) e.getSource();
        ListSelectedRowCollection SelectedDataCol= formOperate.getListSelectedData();
        if (StringUtils.isNotEmpty(operateKey)&&isSuccess) {
            if ("createrevehicle".equals(operateKey)) {
                for(ListSelectedRow SelectedData:SelectedDataCol) {
                    DynamicObject OldEquipmentlis = BusinessDataServiceHelper.loadSingle(SelectedData.getPrimaryKeyValue(), "yem_em_equipmentlist");
                    long OldEquipmentListID= OldEquipmentlis.getLong("id");
                    long NewEquipmentListID= creatEequipmentList_res(OldEquipmentlis);

                    IFormView view = this.getView();
                    FormShowParameter fsp = new FormShowParameter();
                    fsp.setStatus(OperationStatus.EDIT);
                    fsp.getOpenStyle().setShowType(ShowType.Modal);
                    Map<String, Object> values = new HashMap<>();
                    values.put("NewEquipmentListID", NewEquipmentListID);
                    values.put("type", "creater");
                    fsp.setCustomParams(values);
                    CloseCallBack callBack = new CloseCallBack(this, "createReVehicle");
                    fsp.setCloseCallBack(callBack);
                    fsp.setFormId("yem_createresource");
                    view.showForm(fsp);

                }
                this.getView().hideLoading(true);
            }
            if ("modifyevehicle".equals(operateKey)) {
                for (ListSelectedRow SelectedData : SelectedDataCol) {
                    DynamicObject bill = BusinessDataServiceHelper.loadSingle(SelectedData.getPrimaryKeyValue(), "yem_em_equipmentlist");
                    long NewEquipmentListID = bill.getLong("id");

                    IFormView view = this.getView();
                    FormShowParameter fsp = new FormShowParameter();
                    fsp.setStatus(OperationStatus.EDIT);
                    fsp.getOpenStyle().setShowType(ShowType.Modal);
                    Map<String, Object> values = new HashMap<>();
                    values.put("NewEquipmentListID", NewEquipmentListID);
                    values.put("type", "modif");
                    fsp.setCustomParams(values);
                    CloseCallBack callBack = new CloseCallBack(this, "createReVehicle");
                    fsp.setCloseCallBack(callBack);
                    fsp.setFormId("yem_createresource");
                    view.showForm(fsp);;
                }
            }
            if ("deleteevehicle".equals(operateKey)) {
                for (ListSelectedRow SelectedData : SelectedDataCol) {
                    DynamicObject bill = BusinessDataServiceHelper.loadSingle(SelectedData.getPrimaryKeyValue(), "yem_em_equipmentlist");
                    long etcId = bill.getLong("id");

                    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[]{etcId}, delteOption);
                    if (!equipmentlist_delte.isSuccess()) {
                        String detailMessage1 = equipmentlist_delte.getMessage();
                        for (IOperateInfo errInfo1 : equipmentlist_delte.getAllErrorOrValidateInfo()) {
                            detailMessage1 = detailMessage1+errInfo1.getMessage();
                        }
                        this.getView().showMessage(detailMessage1);
                    }

                }

                this.getView().invokeOperation("refresh");
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);
        String actionId = closedCallBackEvent.getActionId();
        Object returnData = closedCallBackEvent.getReturnData();
        if (StringUtils.isNotEmpty(actionId)) {
            if ("createReVehicle".equals(actionId)) {
                this.getView().invokeOperation("refresh");
            }
        }
    }

    /**
     * @MethodName 生成资源号电子目录明细
     * @Author  SC
     * @Description
     * @Date 14:17 2023/7/27
     * @Param DynamicObject Oldequipmentlis 原始电子目录
     **/
    private Long creatEequipmentList_res(DynamicObject Oldequipmentlis) {
        long NewEquipmentListID ;
        String OldEqpLumber = Oldequipmentlis.getString("number");
        DynamicObject userObj = BusinessDataServiceHelper.loadSingle(RequestContext.get().getCurrUserId(), "bos_user");
        DynamicObject equipmentlist = BusinessDataServiceHelper.newDynamicObject("yem_em_equipmentlist");
        DynamicObjectUtils.copy(Oldequipmentlis,equipmentlist);
        equipmentlist.set("creator", userObj);
        equipmentlist.set("createtime", new Date());
        equipmentlist.set("modifier", userObj);
        equipmentlist.set("modifytime", new Date());
        equipmentlist.set("yem_resourc", true);
        //重新获取编码
        String timeStr1= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyMMddHHmmss"));
        String numberEqpLumbe = OldEqpLumber +"_"+timeStr1;
        equipmentlist.set("number", numberEqpLumbe);
        //来源设备电子目录明细ID
        equipmentlist.set("yem_oldequipmentlistid", Oldequipmentlis.getLong("id"));

        DynamicObjectCollection componentEntryCol = equipmentlist.getDynamicObjectCollection("yem_em_component");
        for(DynamicObject componentEntry:componentEntryCol){
            boolean yem_isepc_c = componentEntry.getBoolean("yem_isepc_c");
            String yem_number_c =  componentEntry.getString("yem_number_c");
            String yem_longnumber_c =  componentEntry.getString("yem_longnumber_c");
            String new_number_c = yem_number_c +"_"+timeStr1;
            if(yem_isepc_c){
                componentEntry.set("yem_number_c",numberEqpLumbe);
                componentEntry.set("yem_cnumber_c",numberEqpLumbe);
            }else{
                componentEntry.set("yem_number_c",new_number_c);
            }
            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{
                    if(i!=cnumberCOl.length-1){
                        newlongnumber_c.append(cnumber);
                    }else{
                        newlongnumber_c.append(new_number_c); //最后一行赋值新的编码
                    }
                }
                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){
                String yem_number_p =  partEntry.getString("yem_number_p");
                String newnumber_p = yem_number_p +"_"+timeStr1;
                partEntry.set("yem_number_p",newnumber_p);
            }
        }
        OperationResult equipmentlist_save = OperationServiceHelper.executeOperate("save", "yem_em_equipmentlist",
                new DynamicObject[] { equipmentlist }, null);
        if (!equipmentlist_save.isSuccess()) {
            this.getView().hideLoading(false);
            StringBuilder detailMessage1 = new StringBuilder(equipmentlist_save.getMessage());
            for (IOperateInfo errInfo1 : equipmentlist_save.getAllErrorOrValidateInfo()) {
                detailMessage1.append(errInfo1.getMessage());
            }
            throw new KDBizException(ResManager.loadKDString("生成新的产品资源失败：" ,
                    "EtcmanualList_1", "creatEequipmentList_res")+detailMessage1);
        }else{
            NewEquipmentListID = Long.parseLong(equipmentlist_save.getSuccessPkIds().get(0).toString());
            DynamicObject NewEquipment = BusinessDataServiceHelper.loadSingle(NewEquipmentListID, "yem_em_equipmentlist");
            //处理pid和主数据内码问题
            DynamicObjectCollection NewcomponentEntryCol = NewEquipment.getDynamicObjectCollection("yem_em_component");
            for(DynamicObject componentEntry:NewcomponentEntryCol){
                long Oldmasterid_c = componentEntry.getLong("yem_masterid_c");
                componentEntry.set("yem_masterid_c",componentEntry.getPkValue());
                for(DynamicObject componentNexEntry:NewcomponentEntryCol){
                    long pid = componentNexEntry.getLong("pid");
                    if(Oldmasterid_c == pid){
                        componentNexEntry.set("pid",componentEntry.getPkValue());
                    }
                }

                DynamicObjectCollection partEntryCol = componentEntry.getDynamicObjectCollection("yem_em_part");
                for(DynamicObject partEntry:partEntryCol){
                    partEntry.set("yem_masterid_p",partEntry.getPkValue());

                    partEntry.set("yem_equipmentlistid",NewEquipmentListID);
                }
            }

            SaveServiceHelper.save(new DynamicObject[] { NewEquipment });
        }
        return NewEquipmentListID;
    }

}
