import com.dassault_systemes.enovia.enterprisechangemgt.common.ChangeAction;
import com.matrixone.apps.domain.util.ContextUtil;
import com.matrixone.apps.domain.util.FrameworkException;
import com.matrixone.apps.domain.util.MapList;
import com.matrixone.apps.domain.util.MqlUtil;
import matrix.db.Context;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Logger;


public class AegChange_mxJPO {

    private static final Logger LOGGER = Logger.getLogger(AegChange_mxJPO.class.getName());

    private static final SimpleDateFormat NEW_DATE_FORMAT=new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());

    private static final SimpleDateFormat ORIGINAL_DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a", Locale.US);

    public void getPersonInfo(Context context, String[] args) throws Exception {
        String TitleValue = "";
        String DateValue = "";
        String ChangeActionId = "";
        String PersonName = "";
        String ChineseName = "";

        String InboxTaskId = args[0];

        String getObjectRouteType = "print bus " + InboxTaskId + " select from[Route Task].to.to[Object Route].from.type from[Route Task].to.to[Object Route].from.id dump | ";
        String objectRouteType = MqlUtil.mqlCommand(context, getObjectRouteType);
        LOGGER.info("isChangeAction === > " + objectRouteType);

        String[] caInfo = objectRouteType.split("\\|");

        if(caInfo.length == 2){

            String isChangeAction = caInfo[0];
            String caID = caInfo[1];

            // 首先判断该变更类型是否为CA
            if("Change Action".equals(isChangeAction)){

                LOGGER.info("isChangeAction ===> " + isChangeAction);
                LOGGER.info("caID  ====> " + caID);

                ChangeAction changeAction = new ChangeAction(caID);

                //获取已实现的更改
                MapList mapList = changeAction.getRealizedChanges(context);
                Boolean isDrawingFlag = false;

                //判断已实现的更改的类型有没有为 "Drawing" 的
                for (int i = 0; i < mapList.size(); i++) {
                    Map map = (Map) mapList.get(i);
                    if ("Drawing".equals(map.get("type"))) {
                        isDrawingFlag = true;
                        break;
                    }
                }

                LOGGER.info("isDrawingFlag  ===> " + isDrawingFlag);

                if(isDrawingFlag){

                    // 获取数据为 : CA的ID 、 审批人的中文 、 该节点所属人 、 该节点实际完成时间 、 该节点的审批人
                    String getInfo = "print bus " + InboxTaskId + " select from[Route Task].to.to[Object Route].from.id  attribute[Title] owner from[Route Task].to.from[Route Node].attribute[Actual Completion Date] from[Route Task].to.from[Route Node].attribute[Title] dump |";
                    String inboxInfo = MqlUtil.mqlCommand(context, getInfo);
                    LOGGER.info("inboxInfo ==> " + inboxInfo);

                    String[] splitInfo = inboxInfo.split("\\|");

                    if(splitInfo.length > 3){
                        ChangeActionId = splitInfo[0];

                        if(!splitInfo[1].isEmpty() && splitInfo[1].contains("@")){
                            TitleValue =  splitInfo[1].split("@")[0];
                        }

                        if(!splitInfo[1].isEmpty() && !splitInfo[2].isEmpty()){
                            String Title = splitInfo[1];
                            PersonName = splitInfo[2];

                            // 这个逻辑稍微有点复杂，总体就是通过Title 找到对应的 实际完成时间
                            for (int i = 3 + (splitInfo.length - 3)/2; i < splitInfo.length; i++) {
                                if(Title.equals(splitInfo[i])) {
                                    DateValue = splitInfo[i-(splitInfo.length-3)/2];
                                    break;
                                }
                            }

                            //getChineseName
                            String getChineseName = "temp query bus Person " + PersonName + " * select attribute[Title] dump |";
                            String PersonNameInfo = MqlUtil.mqlCommand(context, getChineseName);


                            String[] PersonNameInfoLength = PersonNameInfo.split("\\|");
                            if(PersonNameInfoLength.length == 4) {
                                ChineseName = PersonNameInfo.split("\\|")[3];
                            }else{
                                ChineseName = PersonName;
                            }

                            //Processing date format  进行时间格式的转换
                            try {
                                Date date = ORIGINAL_DATE_FORMAT.parse(DateValue);

                                DateValue = NEW_DATE_FORMAT.format(date);

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            LOGGER.info("DateValue ==> " + DateValue);
                            LOGGER.info("ChineseName ==> " + ChineseName);
                            LOGGER.info("ChangeActionId ==> " + ChangeActionId);
                            LOGGER.info("TitleValue ==> " + TitleValue);

                            for (int i = 0; i < mapList.size(); i++) {
                                Map map = (Map) mapList.get(i);
                                String drawingId = (String) map.get("id");

                                if(! "Drawing".equals(map.get("type")))
                                {
                                    continue;
                                }

                                //主要是判断设计者是否已经有了数据，有了数据之后就不进行操作剩余的赋值操作了
                                Boolean isFlag = getAttrDesignInfo(context, drawingId);

                                if(!isFlag){
                                    String chineseName = getChineseName(context, drawingId);
                                    String cnTime = getCNTime(context,drawingId);
                                    updateAttrDesign(context,drawingId,chineseName,cnTime);
                                }

                                // 这个就是普通的数据赋值操作
                                if("\u6279\u51c6".equals(TitleValue))
                                {
                                    updateAttr(context,drawingId,"XP_Drawing_Ext.approval",ChineseName,"XP_Drawing_Ext.approval_date",DateValue);
                                } else if ("\u8bbe\u8ba1".equals(TitleValue))
                                {
                                    updateAttr(context,drawingId,"XP_Drawing_Ext.design",ChineseName,"XP_Drawing_Ext.design_date",DateValue);
                                } else if ("\u6821\u5bf9".equals(TitleValue))
                                {
                                    updateAttr(context, drawingId, "XP_Drawing_Ext.check", ChineseName, "XP_Drawing_Ext.check_date", DateValue);
                                } else if ("\u6807\u51c6\u5316".equals(TitleValue))
                                {
                                    updateAttr(context, drawingId, " XP_Drawing_Ext.standard", ChineseName, "XP_Drawing_Ext.standard_date", DateValue);
                                } else if ("\u5de5\u827a".equals(TitleValue))
                                {
                                    updateAttr(context, drawingId, "XP_Drawing_Ext.technique", ChineseName, "XP_Drawing_Ext.technique_date", DateValue);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // 赋值操作
    public void updateAttr(Context context,String drawingId, String personNameKey, String personNameValue, String attrDateKey, String arrDateValue) throws FrameworkException {
        String updateAttrName = "modify bus " + drawingId + " " + personNameKey + " " + personNameValue + " " + attrDateKey + " " + arrDateValue ;
        LOGGER.info("updateAttName === >" + updateAttrName);

        ContextUtil.pushContext(context);
        MqlUtil.mqlCommand(context,updateAttrName);
        ContextUtil.popContext(context);
    }

    // 判断设计者是否有值
    public Boolean getAttrDesignInfo(Context context, String drawingId) throws FrameworkException {
        String getDesignInfo = "print bus " +drawingId + " select Attribute[XP_Drawing_Ext.design].value dump |";
        String designInfo = MqlUtil.mqlCommand(context, getDesignInfo);
        if(designInfo.isEmpty())
        {
            return false;
        }
        return true;
    }

    // 获取中文名
    public String getChineseName(Context context, String drawingId) throws FrameworkException {
        String getUsName = "print bus " + drawingId + " select owner dump |";
        String usName = MqlUtil.mqlCommand(context, getUsName);

        String getCnName = "temp query bus Person " + usName + " * select attribute[Title] dump |";
        String getNameInfo = MqlUtil.mqlCommand(context, getCnName);
        String cnName = getNameInfo.split("\\|")[3];

        return cnName;
    }

    // 获取中国的时间
    public String getCNTime(Context context, String drawingId) throws Exception {
        String getUsTime = "print bus " + drawingId + " select originated dump |";
        String usTime =  MqlUtil.mqlCommand(context,getUsTime);

        Date date = ORIGINAL_DATE_FORMAT.parse(usTime);
        String cnTime = NEW_DATE_FORMAT.format(date);

        return cnTime;
    }

    // 向设计者赋值 (仅仅只为设计)
    public void updateAttrDesign(Context context, String drawingId, String drawingOwner, String drawingDate)  throws FrameworkException{
        String updateAttrName = "modify bus " + drawingId + " XP_Drawing_Ext.design " + drawingOwner +  " XP_Drawing_Ext.design_date " + drawingDate ;

        ContextUtil.pushContext(context);
        MqlUtil.mqlCommand(context,updateAttrName);
        ContextUtil.popContext(context);
    }
}
