package com.foreverwin.mesnac.dataimport.client;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.foreverwin.mesnac.common.constant.DataImportConstant;
import com.foreverwin.mesnac.common.enums.HandleEnum;
import com.foreverwin.mesnac.dataimport.util.AppUtil;
import com.foreverwin.mesnac.meapi.model.WorkCenter;
import com.foreverwin.mesnac.meapi.model.WorkCenterMember;
import com.foreverwin.mesnac.meapi.service.WorkCenterMemberService;
import com.foreverwin.mesnac.meapi.service.WorkCenterService;
import com.foreverwin.modular.core.meext.MEServices;
import com.foreverwin.modular.core.util.I18nUtil;
import com.foreverwin.modular.core.util.SpringUtil;
import com.sap.me.common.ObjectAliasEnum;
import com.sap.me.common.ObjectReference;
import com.sap.me.plant.*;

import java.lang.reflect.UndeclaredThrowableException;
import java.util.ArrayList;
import java.util.List;


/**
 * 资源主数据操作类
 *
 *
 * @author Leon
 * @date 2021/7/6
 */
public class ResourceWSClient {

    /**
     * 查询资源
     * @param data
     * @return
     */
    public static ResourceFullConfiguration find(JSONObject data) {
        try {
            String site = (String) data.get("site");
            String resource = data.getString("resource").toUpperCase();
            String resourceBo = HandleEnum.RESOURCE.getHandle(site, resource);

            ObjectReference request = new ObjectReference();
            request.setRef(resourceBo);

            //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            ResourceConfigurationServiceInterface resourceConfigurationService = MEServices.create("com.sap.me.plant", "ResourceConfigurationService", site);
            ResourceFullConfiguration op = resourceConfigurationService.readResource(request);

            return op;
        } catch (Exception e) {
            //---------
        }

        return null;
    }

    /**
     * 新增资源主数据
     * @param data
     * @return
     */
    public static String insert(JSONObject data) {
        try {
            String site = (String) data.get("site");
            String resource = data.getString("resource").toUpperCase();
            String resourceRef = HandleEnum.RESOURCE.getHandle(site, resource);

            //资源主数据对象
            CreateResourceRequest request = new CreateResourceRequest();
            request.setResource(resource);
            request.setDescription(data.getString("description"));

            //缺省操作
            String defaultOperation = data.getString("defaultOperation");
            if (defaultOperation != null && defaultOperation.trim().length() > 0) {
                String objRef = "OperationBO:" + site + "," + defaultOperation + ",#";
                request.setOperationRef(objRef);
            }

            //资源类型
            String resourceType = data.getString("resourceType");
            if (resourceType != null && resourceType.trim().length() > 0) {
                String resourceTypeBO = ("ResourceTypeBO:" + site + "," + resourceType);
                ResourceTypeResourceReference resType = new ResourceTypeResourceReference();
                resType.setRef(resourceTypeBO);

                List<ResourceTypeResourceReference> resourceTypeResourceList = new ArrayList();
                resourceTypeResourceList.add(resType);
                request.setResourceTypeResourceList(resourceTypeResourceList);
                /**String errorMessage = resourceToWorkCenter(resourceRef, resourceType, site);
                if (errorMessage != null) {
                    return errorMessage;
                }**/
            }

            /**
             * 状态
             * 301-已启用
             * 302-已禁用
             * 303-保留
             * 1-生产
             * 2-备用
             * 3-工程
             * 4-预定停机
             * 5-非预定停机
             * 6-非预定
             */
            String _status = (String) data.get("status");
            if (_status != null) {
                _status = _status.substring(0, _status.indexOf(":"));
                String statusRef = "StatusBO:" + site + "," + "301";
                if ("0".equalsIgnoreCase(_status) || "301".equalsIgnoreCase(_status)) {
                    statusRef = "StatusBO:" + site + "," + "301";
                } else if ("2".equalsIgnoreCase(_status) || "302".equalsIgnoreCase(_status)) {
                    statusRef = "StatusBO:" + site + "," + "302";
                } else if ("1".equalsIgnoreCase(_status) || "303".equalsIgnoreCase(_status)) {
                    statusRef = "StatusBO:" + site + "," + "303";
                }
                request.setStatusRef(statusRef);
            }

            /**
             * SetupStateEnum SetupStateEnum.NOTSETUP
             * 设置状态
             * O-未确认
             * B-正在细分
             * N-未设置
             * T-正在设置
             * S-设置
             */
            String _setupStatus = data.getString("setupStatus");
            if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_1.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.OPEN);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_2.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.BREAKDOWN);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_3.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.SETTINGUP);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_4.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.SETUP);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_5.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.NOTSETUP);
            } else {
                request.setSetupState(SetupStateEnum.OPEN);
            }

            //流程资源
            String _processResource = data.getString("processResource");
            if (DataImportConstant.RESOURCE_WSCLIENT_PROCESS_RESOURCE.equalsIgnoreCase(_processResource)) {
                request.setProcessResource(true);
            } else {
                request.setProcessResource(false);
            }

            ResourceConfigurationServiceInterface resourceConfigurationService = MEServices.create("com.sap.me.plant", "ResourceConfigurationService", site);
            //资源创建
            resourceConfigurationService.createResource(request);
            //自定义字段保存
            CustomDataWSClient.update(data, resourceRef, ObjectAliasEnum.RESOURCE.value());

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof UndeclaredThrowableException) {
                return ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage();
            }
            return e.getMessage();
        }
    }

    /**
     * 更新资源主数据
     * @param data
     * @param request
     * @return
     */
    public static String update(JSONObject data, ResourceFullConfiguration request) {

        try {
            String site = (String) data.get("site");
            String resource = data.getString("resource").toUpperCase();
            request.setDescription(data.getString("description"));
            String defaultOperation = (String) data.get("defaultOperation");

            if (AppUtil.isNotNull(defaultOperation)) {
                String objRef = "OperationBO:" + site + "," + defaultOperation + ",#";
                request.setOperationRef(objRef);
            }

            String _status = (String) data.get("status");
            if (_status != null) {
                _status = _status.substring(0, _status.indexOf(":"));
                String statusRef = "StatusBO:" + site + "," + "301";
                if ("0".equalsIgnoreCase(_status) || "301".equalsIgnoreCase(_status)) {
                    statusRef = "StatusBO:" + site + "," + "301";
                } else if ("2".equalsIgnoreCase(_status) || "302".equalsIgnoreCase(_status)) {
                    statusRef = "StatusBO:" + site + "," + "302";
                } else if ("1".equalsIgnoreCase(_status) || "303".equalsIgnoreCase(_status)) {
                    statusRef = "StatusBO:" + site + "," + "303";
                }
                request.setStatusRef(statusRef);
            }

            //SetupStateEnum SetupStateEnum.NOTSETUP;
            String _setupStatus = data.getString("setupStatus");
            if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_1.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.OPEN);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_2.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.BREAKDOWN);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_3.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.SETTINGUP);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_4.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.SETUP);
            } else if (DataImportConstant.RESOURCE_WSCLIENT_SETUP_STATUS_5.equalsIgnoreCase(_setupStatus)) {
                request.setSetupState(SetupStateEnum.NOTSETUP);
            }

            String _processResource = data.getString("processResource");
            if (DataImportConstant.RESOURCE_WSCLIENT_PROCESS_RESOURCE.equalsIgnoreCase(_processResource)) {
                request.setProcessResource(true);
            } else {
                request.setProcessResource(false);
            }

            String resourceType = data.getString("resourceType");
            if (resourceType != null && resourceType.trim().length() > 0) {
                List<ResourceTypeResource> resourceTypeResourceList = request.getResourceTypeResourceList();
                String addRef = "ResourceTypeBO:" + site + "," + resourceType;
                boolean exist = false;
                for (ResourceTypeResource rf : resourceTypeResourceList) {
                    if (addRef.equalsIgnoreCase(rf.getResourceTypeRef())) {
                        exist = true;
                        break;
                    }
                }
                if (!exist) {
                    resourceTypeResourceList.clear();
                    ResourceTypeResource resType = new ResourceTypeResource();
                    String resourceTypeBO = ("ResourceTypeBO:" + site + "," + resourceType);
                    resType.setResourceTypeRef(resourceTypeBO);
                    resourceTypeResourceList.add(resType);
                    request.setResourceTypeResourceList(resourceTypeResourceList);
                }

                /**String errorMessage = resourceToWorkCenter(ref, resourceType, site);
                if (errorMessage != null) {
                    return errorMessage;
                }**/
            }

            ResourceConfigurationServiceInterface resourceConfigurationService = MEServices.create("com.sap.me.plant", "ResourceConfigurationService", site);
            resourceConfigurationService.updateResource(request);

            String ref = "ResourceBO:" + site + "," + resource;
            CustomDataWSClient.update(data, ref, ObjectAliasEnum.RESOURCE.value());

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof UndeclaredThrowableException) {
                return ((UndeclaredThrowableException) e).getUndeclaredThrowable().getMessage();
            }
            return e.getMessage();
        }
    }


    private static String resourceToWorkCenter(String ref, String resourceType, String site) {
        WorkCenterService workCenterService = SpringUtil.getBean(WorkCenterService.class);
        WorkCenter workCenter = new WorkCenter();
        workCenter.setSite(site);
        workCenter.setWorkCenter(resourceType);

        List<WorkCenter> workCenterList = workCenterService.selectList(workCenter);
        if (workCenterList.size() > 0) {
            String workCenterBo = workCenterList.get(0).getHandle();

            WorkCenterMemberService workCenterMemberService = SpringUtil.getBean(WorkCenterMemberService.class);
            QueryWrapper<WorkCenterMember> queryWrapper = new QueryWrapper();
            queryWrapper.eq("WORK_CENTER_OR_RESOURCE_GBO", ref);
            List<com.foreverwin.mesnac.meapi.model.WorkCenterMember> workCenterMemberList = workCenterMemberService.selectList(queryWrapper);
            if (workCenterMemberList != null && workCenterMemberList.size() > 0 ) {
                if(!workCenterBo.equals(workCenterMemberList.get(0).getWorkCenterBo())){
                    workCenterMemberService.remove(queryWrapper);
                }else{
                    return null;
                }
            }
            Integer maxSeq = workCenterMemberService.selectMaxSeq(workCenterBo);
            if (maxSeq == null) {
                maxSeq = 0;
            }
            maxSeq = maxSeq + 10;

            com.foreverwin.mesnac.meapi.model.WorkCenterMember workCenterMember = new com.foreverwin.mesnac.meapi.model.WorkCenterMember();
            workCenterMember.setWorkCenterBo(workCenterBo);
            workCenterMember.setWorkCenterOrResourceGbo(ref);
            workCenterMember.setSequence(maxSeq.longValue());
            workCenterMember.setHandle("WorkCenterMemberBO:" + workCenterBo + "," + ref);
            workCenterMemberService.save(workCenterMember);
            return null;
        } else {
            return (I18nUtil.getI18nText("dataimport.resourceWSClient.workCenterNotExistent"));
        }
    }
}
