package com.foreverwin.mesnac.dataimport.client;

import com.alibaba.fastjson.JSONObject;
import com.foreverwin.mesnac.common.constant.DataImportConstant;
import com.foreverwin.mesnac.common.util.StringUtil;
import com.foreverwin.mesnac.meapi.constant.KeywordConstant;
import com.foreverwin.modular.core.meext.MEServices;
import com.foreverwin.mesnac.dataimport.util.AppUtil;
import com.sap.me.common.BasicStatusEnum;
import com.sap.me.common.ObjectAliasEnum;
import com.sap.me.common.ObjectReference;
import com.sap.me.plant.*;

import java.lang.reflect.UndeclaredThrowableException;
import java.math.BigDecimal;
import java.util.List;

public class WorkCenterWSClient {

    //工作中心查询
    public static WorkCenterFullConfiguration find(JSONObject data) {
        try {
            String site = (String) data.get("site");
            String workCenter = data.getString("workCenter");

            ObjectReference request = new ObjectReference();
            request.setRef("WorkCenterBO:" + site + "," + workCenter.trim());
            WorkCenterConfigurationServiceInterface workCenterConfigurationService = MEServices.create("com.sap.me.plant", "WorkCenterConfigurationService", site);
            WorkCenterFullConfiguration op = workCenterConfigurationService.readWorkCenter(request);

            return op;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //工作中心新增
    public static String insert(JSONObject data) {

        try {
            String site = (String) data.get("site");
            WorkCenterConfiguration request = new WorkCenterConfiguration();
            request.setWorkCenter(data.getString("workCenter").trim());

            /**
             * 状态
             * 101-已启用
             * 102-已禁用
             */
            String status = data.getString("status");
            if (DataImportConstant.WORK_CENTER_WSCLIENT_STATUS.equalsIgnoreCase(status)) {
                request.setStatus(BasicStatusEnum.DISABLED);
            } else {
                request.setStatus(BasicStatusEnum.ENABLED);
            }

            /**
             * 工作中心类别
             * LEVEL0-无
             * LEVEL1-单元
             * LEVEL2-单元组
             * LEVEL3-生产线
             * LEVEL4-生产线组
             * LEVEL5-建筑物
             */
            String wcCategory = data.getString("wcCategory");
            if ((wcCategory != null && wcCategory.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_CATEGORY_1) || (wcCategory != null && wcCategory.equalsIgnoreCase("LINE")))) {
                request.setWorkCenterCategory(WorkCenterCategory.LINE);
            } else if ((wcCategory != null && wcCategory.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_CATEGORY_2) || (wcCategory != null && wcCategory.equalsIgnoreCase("LINE_GROUP")))) {
                request.setWorkCenterCategory(WorkCenterCategory.LINE_GROUP);
            } else if ((wcCategory != null && wcCategory.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_CATEGORY_3) || (wcCategory != null && wcCategory.equalsIgnoreCase("CELL")))) {
                request.setWorkCenterCategory(WorkCenterCategory.CELL);
            } else if ((wcCategory != null && wcCategory.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_CATEGORY_4) || (wcCategory != null && wcCategory.equalsIgnoreCase("CELL_GROUP")))) {
                request.setWorkCenterCategory(WorkCenterCategory.CELL_GROUP);
            } else if (wcCategory != null && wcCategory.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_CATEGORY_5)) {
                request.setWorkCenterCategory(WorkCenterCategory.BUILDING);
            } else {
                request.setWorkCenterCategory(WorkCenterCategory.NONE);
            }

            //工作中心类型
            String resourceType = data.getString("wcType");
            if ((resourceType != null && resourceType.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_TYPE_1) || (resourceType != null && resourceType.equalsIgnoreCase("FABRICATION")))) {
                request.setWorkCenterType(WorkCenterType.FABRICATION);
            } else if ((resourceType != null && resourceType.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_TYPE_2) || (resourceType != null && resourceType.equalsIgnoreCase("ASSEMBLY")))) {
                request.setWorkCenterType(WorkCenterType.ASSEMBLY);
            } else if ((resourceType != null && resourceType.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_TYPE_3) || (resourceType != null && resourceType.equalsIgnoreCase("SHIPPING")))) {
                request.setWorkCenterType(WorkCenterType.SHIPPING);
            } else if ((resourceType != null && resourceType.equalsIgnoreCase(DataImportConstant.WORK_CENTER_WSCLIENT_TYPE_4) || (resourceType != null && resourceType.equalsIgnoreCase("DISPATCH")))) {
                request.setWorkCenterType(WorkCenterType.DISPATCH);
            } else {
                request.setWorkCenterType(WorkCenterType.RECORD_CONTROL);
            }

            //描述
            String descriptionZH = data.getString("descriptionZH");
            if (StringUtil.notEmpty(descriptionZH)) {
                WorkCenterTranslation rl = new WorkCenterTranslation();
                rl.setLocale("zh");
                rl.setDescription(descriptionZH);
                request.getWorkCenterTranslationList().add(rl);
            }
            String descriptionEN = data.getString("descriptionEN");
            if (StringUtil.notEmpty(descriptionEN)) {
                WorkCenterTranslation rl = new WorkCenterTranslation();
                rl.setLocale("en");
                rl.setDescription(descriptionEN);
                request.getWorkCenterTranslationList().add(rl);
            }
            //request.setDescription(descriptionZH);

            //工作中心下属
            String memberSeq = data.getString("memberSeq");
            String memberType = data.getString("memberType");
            String resourceGBO = data.getString("memberGBO");
            if (AppUtil.isNotNull(resourceGBO) && AppUtil.isNotNull(memberType)) {
                List<WorkCenterMember> members = request.getWorkCenterMemberList();
                boolean exist = false;
                for (WorkCenterMember member : members) {
                    if (resourceGBO.equalsIgnoreCase(member.getResourceRef())) {
                        exist = true;
                        break;
                    }
                }
                if (!exist) {
                    WorkCenterMember newMember = new WorkCenterMember();
                    newMember.setSequence(new BigDecimal(memberSeq));
                    if (DataImportConstant.WORK_CENTER_WSCLIENT_RESRCE.equalsIgnoreCase(memberType)) {
                        newMember.setResourceRef("ResourceBO:" + site + "," + resourceGBO.trim());
                    } else {
                        if (isExistWorkCenter(site, resourceGBO)) {
                            newMember.setWorkCenterRef("WorkCenterBO:" + site + "," + resourceGBO.trim());
                        } else {
                            String errMsg = "WebService error！WorkCenterBO:" + resourceGBO + " not exist";
                            return errMsg;
                        }
                    }
                    members.add(newMember);
                    request.setWorkCenterMemberList(members);
                }
            }

            //releaseTo
            String releaseTo = data.getString("releaseTo");
            if (AppUtil.isNotNull(releaseTo)) {
                if (KeywordConstant.KW_COMMON_YES.equalsIgnoreCase(releaseTo)) {
                    request.setCanBeReleasedTo(true);
                }
            }

            //isERPWC
            String isERPWC = data.getString("isERPWC");
            if (AppUtil.isNotNull(isERPWC)) {
                String ERPWC = data.getString("ERPWC");
                request.setErpWorkCenter(true);
                request.setErpWorkCenterName(ERPWC);
            }

            WorkCenterConfigurationServiceInterface workCenterConfigurationService = MEServices.create("com.sap.me.plant", "WorkCenterConfigurationService", site);
            workCenterConfigurationService.createWorkCenter(request);

            String ref = "WorkCenterBO:" + site + "," + data.get("workCenter");
            CustomDataWSClient.update(data, ref, ObjectAliasEnum.WORK_CENTER.value());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            if(e instanceof UndeclaredThrowableException){
                return ((UndeclaredThrowableException)e).getUndeclaredThrowable().getMessage();
            }
            return e.getMessage();
        }
    }

    //工作中心更新
    public static String update(JSONObject data, WorkCenterFullConfiguration request) {
        try {
            String site = (String) data.get("site");
            String member = data.getString("memberGBO");
            String memberSeq = data.getString("memberSeq");
            String memberType = data.getString("memberType");
            if (AppUtil.isNotNull(member) && AppUtil.isNotNull(memberType)) {

                if (DataImportConstant.WORK_CENTER_WSCLIENT_RESRCE.equalsIgnoreCase(memberType)) {
                    //资源
                    String resourceBo = "ResourceBO:" + site + "," + member;

                    boolean exist = false;
                    List<WorkCenterMember> members = request.getWorkCenterMemberList();
                    for (WorkCenterMember memberModel : members) {
                        if (resourceBo.equalsIgnoreCase(memberModel.getResourceRef())) {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) {
                        WorkCenterMember newMember = new WorkCenterMember();
                        newMember.setSequence(new BigDecimal(memberSeq));
                        newMember.setResourceRef(resourceBo);
                        members.add(newMember);
                        request.setWorkCenterMemberList(members);
                    }
                } else {
                    //工作中心
                    String workCenterBo = "WorkCenterBO:" + site + "," + member;
                    if (!isExistWorkCenter(site, member)) {
                        String errMsg = "WebService error！ workCenter: " + member + " not exist";
                        return errMsg;
                    }

                    boolean exist = false;
                    List<WorkCenterMember> members = request.getWorkCenterMemberList();
                    for (WorkCenterMember memberModel : members) {
                        if (workCenterBo.equalsIgnoreCase(memberModel.getWorkCenterRef())) {
                            exist = true;
                            break;
                        }
                    }
                    if (!exist) {
                        WorkCenterMember newMember = new WorkCenterMember();
                        newMember.setSequence(new BigDecimal(memberSeq));
                        newMember.setWorkCenterRef(workCenterBo);
                        members.add(newMember);
                        request.setWorkCenterMemberList(members);
                    }
                }
            }


            //releaseTo
            String releaseTo = data.getString("releaseTo");
            if (AppUtil.isNotNull(releaseTo)) {
                if (KeywordConstant.KW_COMMON_YES.equalsIgnoreCase(releaseTo)) {
                    request.setCanBeReleasedTo(true);
                }
            }

            //isERPWC
            String isERPWC = data.getString("isERPWC");
            if (AppUtil.isNotNull(isERPWC)) {
                String ERPWC = data.getString("ERPWC");
                request.setErpWorkCenter(true);
                request.setErpWorkCenterName(ERPWC);
            }
            WorkCenterConfigurationServiceInterface workCenterConfigurationService = MEServices.create("com.sap.me.plant", "WorkCenterConfigurationService", site);
            workCenterConfigurationService.updateWorkCenter(request);

            String ref = "WorkCenterBO:" + site + "," + data.get("workCenter");
            CustomDataWSClient.update(data, ref, ObjectAliasEnum.WORK_CENTER.value());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            if(e instanceof UndeclaredThrowableException){
                return ((UndeclaredThrowableException)e).getUndeclaredThrowable().getMessage();
            }
            return e.getMessage();
        }
    }

    public static boolean isExistWorkCenter(String site, String id) {
        boolean isExist = false;
        JSONObject data = new JSONObject();
        data.put("site", site);
        data.put("workCenter", id);
        WorkCenterFullConfiguration config = find(data);
        if (config != null) {
            isExist = true;
        }
        return isExist;
    }
}
