package com.malk.tuosi.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.server.common.McR;
import com.malk.tuosi.entity.Task;
import com.malk.tuosi.mapper.TaskMapper;
import com.malk.tuosi.service.TBService;
import com.malk.tuosi.service.TaskService;
import com.malk.utils.UtilHttp;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.StreamSupport;

@Slf4j
@RestController
@RequestMapping("/datasync")
public class TaskController {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TBService tbService;

    @SneakyThrows
    @PostMapping("/addTask")
    McR addTask(){
        /*todo:查询任务详情*/
        //1、计数项目任务
        HashMap header = new HashMap();
        header.put("x-operator-id","622ee3450cf3bb5e1a486f1f");
        McR Token = tbService.AppAccessToken();
        Object token = Token.getData();
        header.put("Authorization","Bearer " + token);
        header.put("X-Tenant-Id","61a8c26719c3b5ffe9c4cffb");
        header.put("X-Tenant-Type","organization");
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) null);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//1450
        //2、查询项目任务
        HashMap param = new HashMap();
        param.put("pageSize",100);
        ArrayList list = new ArrayList();//分页标全部存在list

        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++){
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param.put("pageToken",pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/query", header, param);
            List<String> batchIds = extractIdsFromJson(doGet1);//提取当前批次的id
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                // 不为空，使用nextPageToken
                list.add(nextPageToken);
                pageToken = nextPageToken;
            }else {
                // 为空，不进行处理
            }

            /*todo：100条数据处理*/
            //3、查询任务详情
            int k =0;
            ArrayList errorList = new ArrayList();
            for (int j = 0; j < allIds.size(); j++) {
                k++;
                HashMap params = new HashMap();
                params.put("taskId", allIds.get(j));
                String doGet2 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params);
                String crmId = "";            //CRM编码--->343513
                String renWuName = "";        //品名--->530GX16迎凤富贵--河南盈乐
                String company = "";          // 客户名称--->华美食品（河北）有限公司
                String draftStatus = "";      // 设计类别--->确认稿
                String customerType = "";     // 文件来源（公司）--->客户
                String levelOneDesign = "";   // 设计等级--->一级设计
                String tfsId = new ObjectMapper().readTree(doGet2).get("result").get(0).get("tfsId").asText();//任务状态ID
                renWuName = new ObjectMapper().readTree(doGet2).get("result").get(0).get("content").asText();//任务名称--->品名
                String title = StreamSupport.stream(new ObjectMapper().readTree(doGet2)
                                .get("result").get(0).get("customfields").spliterator(), false)
                        .filter(field -> "689d4ebf343c05fe73700c93".equals(field.get("cfId").asText()))
                        .findFirst()
                        .map(field -> field.get("value").get(0).get("title").asText())
                        .orElse(null);//CRM单据ID--->CRM编码
                JSONArray customfields = JSON.parseObject(doGet2).getJSONArray("result").getJSONObject(0).getJSONArray("customfields");
                for (int p = 0; p < customfields.size(); p++) {
                    JSONObject field = customfields.getJSONObject(p);
                    String cfId = field.getString("cfId");
                    JSONArray valueArray = field.getJSONArray("value");
                    if (valueArray != null && !valueArray.isEmpty()) {
                        String value = valueArray.getJSONObject(0).getString("title");
                        //根据cfId匹配
                        switch (cfId){
                            case "687df3b60ae1530fa2704499":
                                company = value;
                                break;
                            case "687e0308e3f7ce8174a19cfc":
                                draftStatus = value;
                                break;
                            case "687df8813d5081f8c81cf375":
                                customerType = value;
                                break;
                            case "691c29c1f8cbae320a1c8e75":
                                levelOneDesign = value;
                                break;
                            case "68f980e6a24e799a9c7a226a":
                                crmId = value;
                                break;
                        }
                    }
                }
                /*todo:给实体赋值*/
                /*打印进度*/
                log.info("进度：{}/{}",k,result);
                Task task = new Task();
                task.setTaskId(crmId);//CRM编码
                task.setTaskName(renWuName);//任务名称
                task.setCustomerName(company);//客户名称
                task.setDesignCategory(draftStatus);//设计类别
                task.setFileSource(customerType);//文件来源(公司)
                task.setDesignLevel(levelOneDesign);//设计等级
                /*todo:插入数据库*/
                int insert = taskMapper.insert(task);
                Map<String, Object> response = new HashMap<>();
                if(insert > 0){
                    response.put("success", true);
                    response.put("message", "用户创建成功");
                    response.put("data", "");
                    log.info("任务创建成功，任务ID：{},任务名称：{}", task.getTaskId(),task.getTaskName());
                }else {
                    log.info("任务创建失败，任务ID:{}，任务名称:{}",task.getTaskId(),task.getTaskName());
                    errorList.add(task.getTaskId() + "---" + task.getTaskName());//插入数据失败的统计
                }
            }

            if(errorList.size() >0){
                System.out.println("插入任务列表失败集合：" + errorList);
            }
        }

        return McR.success();
    }

    /*额外方法：从项目任务查询的100条任务提取result中所有的id*/
    private static List<String> extractIdsFromJson(String jsonString) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(jsonString);
        JsonNode resultArray = rootNode.get("result");

        // 预分配100容量（每批大约100条数据）
        List<String> ids = new ArrayList<>(100);

        if (resultArray != null && resultArray.isArray()) {
            for (JsonNode item : resultArray) {
                if (item.has("id")) {
                    String id = item.get("id").asText();
                    ids.add(id);
                }
            }
        }
        return ids;
    }


}
