package com.malk.tuosi.event;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.malk.delegate.TBEvent;
import com.malk.server.common.McException;
import com.malk.service.teambition.TBClient;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

@Primary
@Service
@Slf4j
public class McTbEventImpl implements TBEvent {

    @Autowired
    private TBClient tbClient;

    @Async
    @Override
    public void callBackTask(JSONObject eventJson) {
        String event = eventJson.getString("event");
        if(event.equals("v3.task.node.status.update")){
            JSONObject data = eventJson.getJSONObject("data");
            String taskId = data.getString("taskId");
            String status = data.getString("status");
            String nodeId = data.getString("nodeId");
//            String creatorId = data.getString("creatorId");
            String creatorId = "61a8c27a143030d9110a66d4";
//            Map task = tbClient.queryTaskDetail(taskId,null,null).get(0);
//            if(!"6970a3ff4f887b90bfdbe7e3".equals(String.valueOf(task.get("projectId")))){
//                return;
//            }
//            if(!Arrays.asList("622ee3450cf3bb5e1a486f1f","61a9e8a36355609fb6383d40").contains(creatorId)){
//                return;
//            }
            log.info("XXXXXX 进入节点更新流程，节点ID：{}，状态：{}，任务ID：{}",nodeId,status,taskId);
            if(status.equals("finish")){
                List<Map> list=tbClient.queryNodeList(taskId);
                Map node = _getNodeDetail(list,nodeId);
                if(String.valueOf(node.get("name")).contains("接单")){
                    try {
                        Thread.sleep(3000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    List<String> assigneeIds =  UtilMap.getList(node,"assigneeIds");
                    String startDate = UtilMap.getString(node,"startDate");
                    String dueDate = UtilMap.getString(node,"dueDate");
                    Map nextMap=_getNextNode(list,nodeId);
                    log.info("XXXXXX 接单完成，更新下一节点数据：{}，{}-{}",assigneeIds,startDate,dueDate);
                    if(nextMap!=null){
                        String nextId = UtilMap.getString(nextMap,"id");
                        Map result=tbClient.updateNodeById(taskId,nextId,assigneeIds,startDate,dueDate,creatorId);
                        log.info("XXXXXX 更新结果{}：{}",nextId,result);
                    }
                }
            }else if(status.equals("begin")){
                if(!"finish".equals(data.getJSONObject("old").getString("status"))){
                    return;
                }
                log.info("XXXXXX 接单开始，清空后续节点数据");
                try {
                    Thread.sleep(3000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                List<Map> list=tbClient.queryNodeList(taskId);
//                Map node = _getNodeDetail(list,nodeId);
//                if(String.valueOf(node.get("name")).contains("接单")){
                    nextNode(taskId,list,nodeId,creatorId);
//                }
            }
        }else if(event.equals("v3.task.node.dueDate.update") || event.equals("v3.task.node.startDate.update")){
            JSONObject data = eventJson.getJSONObject("data");
            String taskId = data.getString("taskId");
            String nodeId = data.getString("nodeId");
            String creatorId = "61a8c27a143030d9110a66d4";
            List<Map> list=tbClient.queryNodeList(taskId);
            Map node = _getNodeDetail(list,nodeId);
            String nodeName =getContainsName(String.valueOf(node.get("name")));
            if(!PublicUtil.isNull(nodeName)){
                try {
                    Thread.sleep(3000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                boolean isDue = event.equals("v3.task.node.dueDate.update");
                String date = data.getString(isDue?"dueDate":"startDate");
                String key = NODE_FIELDNAME.get(nodeName)[isDue?0:1];
                log.info("XXXXXX {}时间变更，更新任务{}：{}-{}",nodeName,key,taskId,date);
                tbClient.updateTaskCustomField(taskId,creatorId, UtilMap.map("customfieldName, value",key,Arrays.asList(new JSONObject().fluentPut("title",date))));
            }
        }
    }

    private String getContainsName(String name){
        for (String key : NODE_FIELDNAME.keySet()) {
            if(name.contains(key)){
                return key;
            }
        }
        return null;
    }

    private static Map<String,String[]> NODE_FIELDNAME=new HashMap<>();
    static{
        NODE_FIELDNAME.put("设计接单",new String[]{"设计截止时间","设计开始时间"});
        NODE_FIELDNAME.put("版线组接单",new String[]{"版线组接单截止时间","版线组接单开始时间"});
        NODE_FIELDNAME.put("制作接单",new String[]{"制作截止时间","制作开始时间"});
        NODE_FIELDNAME.put("打样组接单",new String[]{"打样组接单截止时间","打样组接单开始时间"});
        NODE_FIELDNAME.put("CTP接单",new String[]{"CTP接单截止时间","CTP接单开始时间"});
        NODE_FIELDNAME.put("设计完成",new String[]{"设计截止时间","设计开始时间"});
        NODE_FIELDNAME.put("版线组完成",new String[]{"版线组接单截止时间","版线组接单开始时间"});
        NODE_FIELDNAME.put("制作完成",new String[]{"制作截止时间","制作开始时间"});
        NODE_FIELDNAME.put("打样组完成",new String[]{"打样组接单截止时间","打样组接单开始时间"});
        NODE_FIELDNAME.put("CTP完成",new String[]{"CTP接单截止时间","CTP接单开始时间"});
    }

    private void nextNode(String taskId,List<Map> list,String nodeId,String creatorId){
        Map nextMap=_getNextNode(list,nodeId);
        if(nextMap!=null){
            String nextId = UtilMap.getString(nextMap,"id");
            Map result=tbClient.updateNodeById(taskId,nextId,new ArrayList<>(),null,null,creatorId);
            log.info("XXXXXX 清空结果{}：{}",nextId,result);
            nextNode(taskId,list,nextId,creatorId);
        }
    }

    @Override
    public void callBackProject(JSONObject eventJson) {

    }

    @Async
    @Override
    public void callBackWorktime(JSONObject eventJson) {
    }

    private Map _getNodeDetail(List<Map> list, String nodeId) {
        Optional optional = list.stream().filter(item -> nodeId.equals(item.get("id"))).findAny();
        McException.assertAccessException(!optional.isPresent(), nodeId + ": 节点不存在");
        return (Map) optional.get();
    }

    private Map _getNextNode(List<Map> list, String nodeId) {
        for(Map map : list) {
            List<String> prevIds = UtilMap.getList(map,"prevIds");
            if(prevIds.contains(nodeId)){
                return map;
            }
        }
        return null;
    }
}
