package com.malk.tuosi.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR;
import com.malk.service.teambition.TBClient;
import com.malk.tuosi.entity.*;
import com.malk.tuosi.mapper.*;
import com.malk.tuosi.service.TBService;
import com.malk.utils.UtilHttp;
import com.mysql.cj.xdevapi.JsonArray;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.catalina.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Slf4j
@RestController
@RequestMapping("/scheduleTask")
public class ScheduleTask {
    @Autowired
    private TBService tbService;
    @Autowired
    private ConfirmDesignYearMapper confirmDesignYearMapper;
    @Autowired
    private YearPersonalConfirmMapper yearPersonalConfirmMapper;
    @Autowired
    private EmployeeWeeklyTasksMapper employeeWeeklyTasksMapper;
    @Autowired
    private AnnualSeasonalSampleMapper annualSeasonalSampleMapper;
    @Autowired
    private AnnualSeasonalCategoryMapper annualSeasonalCategoryMapper;
    @Autowired
    private NewprocessImplementationMapper newprocessImplementationMapper;
    @Autowired
    private DesigndeparttMonthConfirmMapper designdeparttMonthConfirmMapper;
    @Autowired
    private ChangeDocumentSourceMapper changeDocumentSourceMapper;
    @Autowired
    private PersonalMonthlySuccessrateMapper personalMonthlySuccessrateMapper;
    @Autowired
    private TBClient tbClient;
    @Autowired
    private CommissionTableMapper commissionTableMapper;


    /*每天凌晨定时同步任务状态*/
    @SneakyThrows
    @GetMapping("/renwulist")
    @Scheduled(cron = "0 0 0 * * ?")
    public McR RenWuList(){
        //计数项目任务
        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
        //查询项目任务
        HashMap param = new HashMap();
        param.put("pageSize",100);
        ArrayList list = new ArrayList();//分页标全部存在list
        ArrayList<String> allIds = new ArrayList<>();//全部任务id存在allIds
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++){
            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 {
                // 为空，不进行处理
            }
        }
        //查询任务详情
        int k =0;
        for (int i = 0; i < allIds.size(); i++) {
            k++;
            HashMap params = new HashMap();
            params.put("taskId",allIds.get(i));
            String doGet2 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params);
            String tfsId = new ObjectMapper().readTree(doGet2).get("result").get(0).get("tfsId").asText();//任务状态ID
            String 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
            //搜索项目工作流状态
            HashMap params_A = new HashMap();
            params_A.put("tfsIds",tfsId);
            String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/taskflowstatus/search", header, params_A);
            String name = new ObjectMapper().readTree(doGet3).get("result").get(0).get("name").asText();//当前任务状态
            //调用回传TB的接口更新状态
            HashMap head = new HashMap();
            head.put("crmuserid","620131c2fe8d7eb6b8dfbf76");//TODO：这里不清楚权限，用张昆
            head.put("TargetSystem","CRM");
            HashMap body_B = new HashMap();
            HashMap params_B = new HashMap();
            params_B.put("crmid",title);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentTime = LocalDateTime.now().format(formatter);
            params_B.put("jssj",currentTime);
            params_B.put("ddzt",name);
            body_B.put("params",params_B);
            String s = UtilHttp.doPost("http://ounuo.ip.raresoft.net:8888/api/dd/selfchange", head, null, body_B);
            System.out.println(k+"-"+ allIds.size());
            log.info("任务名称：{}，任务状态：{}，CRM单据ID：{}，------同步完成",renWuName,name,title);
        }
        log.info("任务同步完毕！");
        return McR.success(result);
    }

    /*额外方法：从项目任务查询的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;
    }

    /*todo:设计类别年确认情况*/
    @Scheduled(cron = "0 30 3 * * ?")
    @PostMapping("/confirmDesignYear")
    @SneakyThrows
    McR confirmDesignYear() throws JsonProcessingException {
        //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");
        HashMap param = new HashMap();
        String q = "cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND cf:691c29c1f8cbae320a1c8e75 !=null AND scenarioId = 6878b3d8f40485da4c5f99a2 AND tfsId = 6878b38d6e46cb7d4fec9592 AND cf:687df8813d5081f8c81cf375 = 公司 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND created >= 2026-01-01";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);//todo:[计数项目任务]
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//23
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++){
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q",q);
            param1.put("pageToken",pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);//todo:[查询项目任务]
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            }else {
                // 为空，不进行处理
            }
        //3、查询任务详情
            ArrayList errorList = new ArrayList();
            for (int j = 0; j < allIds.size(); j++) {
                HashMap params3 = new HashMap();
                params3.put("taskId", allIds.get(j));
                String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                String taskId = "";//任务id
                String taskName = "";//任务名称
                String designlevel = "";//设计等级
                String tasktype = "确认稿单";//任务类型
                taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                designlevel = value;
                                break;
                        }
                    }
                }
                /*todo:给实体赋值*/
                ConfirmDesignYear confirmDesignYear = new ConfirmDesignYear();
                confirmDesignYear.setTaskId(taskId);
                confirmDesignYear.setTaskName(taskName);
                confirmDesignYear.setDesignLevel(designlevel);
                confirmDesignYear.setTaskType(tasktype);
        //4、插入数据库
                QueryWrapper<ConfirmDesignYear> queryWrapper = new QueryWrapper<>();
                List<ConfirmDesignYear> confirmDesignYearList = null;
                try {
                    queryWrapper.eq("task_id", taskId);

                    confirmDesignYearList = confirmDesignYearMapper.selectList(queryWrapper);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                UpdateWrapper<ConfirmDesignYear> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("task_id", taskId);
                if (confirmDesignYearList != null && confirmDesignYearList.size() > 0) {
                    updateWrapper.set("task_name", taskName);
                    updateWrapper.set("design_level", designlevel);
                    updateWrapper.set("task_type", tasktype);
                    confirmDesignYearMapper.update(null, updateWrapper);
                }else {
                    int insert = confirmDesignYearMapper.insert(confirmDesignYear);
                    Map<String, Object> response = new HashMap<>();
                    if(insert > 0){
                        response.put("success", true);
                        response.put("message", "用户创建成功");
                        response.put("data", "");
                        log.info("任务创建成功，任务名称：{}，任务id：{}", confirmDesignYear.getTaskName(),confirmDesignYear.getTaskId());
                    }
                }

            }

        }
        log.info("设计类别年确认情况已同步数据库");
        return McR.success();
    }

    /*todo：本年度个人确认稿数据(人员)*//*todo:确认稿件数量（总数量）*//*todo:同期确认稿数量（时间）*/
    @Scheduled(cron = "0 0 3 * * ?")
    @PostMapping("/yearPersonalconfirm")
    @SneakyThrows
    McR yearPersonalconfirm(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND cf:691c29c1f8cbae320a1c8e75 !=null AND scenarioId = 6878b3d8f40485da4c5f99a2 AND tfsId = 6878b38d6e46cb7d4fec9592 AND cf:687df8813d5081f8c81cf375 = 公司 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND created >= 2026-01-01";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//26
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++){
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q",q);
            param1.put("pageToken",pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            }else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            String deadline = "";//完成时间
            String deadlineTime = "";
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                //补充：查询任务前先看下这个是否是新版本的工作流
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetId_deadline = "6875c736476bc6384b458cfc";//【完成时间节点】
                String targetName = "确认工";//确认工艺等级完成

                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        for(int k1 = 0; k1 < resultArray.size(); k1++){
                            JSONObject node1 = resultArray.getJSONObject(k1);
                            if(targetId_deadline.equals(node1.getString("id"))){
                                deadline = node1.getString("accomplished");
                                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                                    SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    //【时间转换】TB中获取的时间为UTC：世界标准时间，在标准时间上加上8小时，即东八区时间，也就是北京时间。
                                    String timeStr = deadline.replace("Z", " UTC");
                                    try {
                                        Date zhuangtaiDate = format.parse(timeStr);
                                        deadlineTime = defaultFormat.format(zhuangtaiDate);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                            }
                        }
                        params3.put("taskId", taskId1);
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String designPerson = "";//设计人员
                        String department = "";//所属部门
                        Integer coefficient = null;//系数
                        String customerName = "";//客户名称
                        String designlevel = "";//设计等级
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customerName = value;
                                        break;
                                    case "695deb1a3fbe995aeeb1b590":
                                        designPerson = value;
                                        break;
                                }
                            }
                        }

                        /*todo:给实体赋值*/
                        YearPersonalConfirm yearPersonalConfirm = new YearPersonalConfirm();
                        yearPersonalConfirm.setTaskId(taskId);
                        yearPersonalConfirm.setTaskName(taskName);
                        yearPersonalConfirm.setDesignPerson(designPerson);
                        if("一级设计".equals(designlevel)){
                            coefficient = 5;
                        }else if("二级设计".equals(designlevel)){
                            coefficient = 3;
                        }else if("三级设计".equals(designlevel)){
                            coefficient = 1;
                        }else if("四级设计".equals(designlevel)){
                            coefficient = 0;
                        }
                        yearPersonalConfirm.setCoefficient(coefficient);
                        yearPersonalConfirm.setCustomerName(customerName);
                        yearPersonalConfirm.setDesignLevel(designlevel);
                        yearPersonalConfirm.setDeadline(deadlineTime);
                        if(!designPerson.equals("")){
                            department = UserGetDeprt(designPerson);
                        }
                        yearPersonalConfirm.setDepartment(department);
                        //4、插入数据库
                        QueryWrapper<YearPersonalConfirm> queryWrapper = new QueryWrapper<>();
                        List<YearPersonalConfirm> YearPersonalConfirmList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            YearPersonalConfirmList = yearPersonalConfirmMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        UpdateWrapper<YearPersonalConfirm> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (YearPersonalConfirmList != null && YearPersonalConfirmList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("design_person", designPerson);
                            updateWrapper.set("coefficient", coefficient);
                            updateWrapper.set("customer_name", customerName);
                            updateWrapper.set("design_level", designlevel);
                            updateWrapper.set("deadline",deadlineTime);
                            updateWrapper.set("department",department);
                            yearPersonalConfirmMapper.update(null, updateWrapper);
                        }else {
                            int insert = yearPersonalConfirmMapper.insert(yearPersonalConfirm);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", yearPersonalConfirm.getTaskName(),yearPersonalConfirm.getTaskId());
                            }
                        }

                    }
                }

            }

        }
        log.info("本年度个人确认稿数据、确认稿件数量、同期确认稿数量");
        return McR.success();
    }


    /*todo:员工每周任务（每10分钟同步）*/
    @Scheduled(cron = "0 */10 * * * ?")
    @PostMapping("/employeeWeeklyTasks")
    @SneakyThrows
    McR employeeWeeklyTasks(){
        //清空数据表
        employeeWeeklyTasksMapper.delete(null);
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "(tfsId = 6895659041ab7094b84f7235 OR tfsId = 6878b384d3c6329fa3728bc5 OR tfsId = 6878b384d3c6329fa3728c0d OR tfsId = 6878b384d3c6329fa3728c4d OR  tfsId = 68946c59de80b116cef042a2 OR tfsId = 68955f8d3fc1a7d437bc2b74 OR tfsId = 6878b38c6e46cb7d4fec943e OR tfsId = 6895659041ab7094b84f7237 OR tfsId = 68946c59de80b116cef042a4 OR tfsId = 68955f8d3fc1a7d437bc2b77 OR tfsId = 68bfbe3701710304d9992693 OR tfsId = 6878b384d3c6329fa3728c0e OR tfsId =6878b384d3c6329fa3728c4e OR tfsId = 6878b384d3c6329fa3728bc6 OR tfsId = 6878b38c6e46cb7d4fec943f OR tfsId =6878b384d3c6329fa3728bc7 OR tfsId =689ededd07e4bad72e58f33b) AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//16
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            String deadlineTime_START = "";
            String deadlineTime_END = "";
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                String status = "";//状态
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "设计接";
                //这里只是遍历每一条任务是否完成status状态
                for(int n = 0;n < resultArray.size();n++){
                    JSONObject node = resultArray.getJSONObject(n);
                    String nodeName = node.getString("name");
                    if("已完成".equals(nodeName)){
                       status = node.getString("status");
                       break;
                    }
                }
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    //抓取设计接单节点数据
                    if (targetName.contains(indexOf)) {
                            params3.put("taskId", taskId1);//allIds.get(j)
                            String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                            String taskId = "";//任务id
                            String taskName = "";//任务名称
                            String manager = "";//负责人
                            String time_start = "";//开始时间
                            String time_end = "";//结束时间
                            String task_type = "";//任务类型
                            String department = "";//所属部门
                            time_start = node.getString("startDate");
                            time_end = node.getString("dueDate");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                            SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            //【时间转换】TB中获取的时间为UTC：世界标准时间，在标准时间上加上8小时，即东八区时间，也就是北京时间。
                            String timeStr = "";
                            if(time_start != null){
                                timeStr = time_start.replace("Z", " UTC");
                            }
                            String timeStr_A = "";
                            if(time_end != null){
                                timeStr_A = time_end.replace("Z", " UTC");
                            }

                            try {
                                if(timeStr != null){
                                    Date zhuangtaiDate = format.parse(timeStr);
                                    deadlineTime_START = defaultFormat.format(zhuangtaiDate);
                                }
                                if(timeStr_A != ""){
                                    Date zhuangtaiDate_A = format.parse(timeStr_A);
                                    deadlineTime_END = defaultFormat.format(zhuangtaiDate_A);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                            taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                            String type = new ObjectMapper().readTree(doGet3).get("result").get(0).get("sfcId").asText();
                            switch (type) {
                                case "6878b3b60d49d89e7955726f"://PPT效果图
                                    task_type = "PPT效果图单";
                                    break;
                                case "6878b3c0669d175c3c6bc679"://打样机打样
                                    task_type = "打样机打样";
                                    break;
                                case "6878b3ceb5ffcf500365d17a"://印刷机打样
                                    task_type = "印刷机打样";
                                    break;
                                case "6878b3d8f40485da4c5f99a2"://确认稿单
                                    task_type = "确认稿单";
                                    break;
                                case "6878b39a27ae5f3cac355fb9"://设计单
                                    task_type = "设计单";
                                    break;
                                case "6878b3a4090e6872fd6b78c6"://设计修改单
                                    task_type = "设计修改单";
                                    break;
                                case "6878b3ad9e17ac8a027c6d37"://设计扩版单
                                    task_type = "设计扩版单";
                                    break;
                            }
                            JSONArray customfields = JSON.parseObject(doGet3).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()) {
                                    //根据cfId匹配
                                    switch (cfId) {
                                        case "66bb1a56f7e230ed6843796e"://设计接单的负责人
                                            for (int a = 0; a < valueArray.size(); a++) {
                                                String value = valueArray.getJSONObject(a).getString("title");
                                                manager = value;
                                                department = UserGetDeprt(manager);
                                                /*todo:给实体赋值*/
                                                EmployeeWeeklyTasks employeeWeeklyTasks = new EmployeeWeeklyTasks();
                                                employeeWeeklyTasks.setTaskId(taskId);
                                                employeeWeeklyTasks.setTaskName(taskName);
                                                employeeWeeklyTasks.setManager(manager);
                                                employeeWeeklyTasks.setTaskType(task_type);
                                                employeeWeeklyTasks.setTimeEnd(deadlineTime_END);
                                                employeeWeeklyTasks.setTimeStart(deadlineTime_START);
                                                employeeWeeklyTasks.setStatus(status);
                                                employeeWeeklyTasks.setDepartment(department);
                                                //4、插入数据库
                                                QueryWrapper<EmployeeWeeklyTasks> queryWrapper = new QueryWrapper<>();
                                                List<EmployeeWeeklyTasks> EmployeeWeeklyTasksList = null;
                                                try {
                                                    String finalManager = manager;
                                                    queryWrapper.eq("task_id", taskId).and(q1 -> q1.eq("manager", finalManager));

                                                    EmployeeWeeklyTasksList = employeeWeeklyTasksMapper.selectList(queryWrapper);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                UpdateWrapper<EmployeeWeeklyTasks> updateWrapper = new UpdateWrapper<>();
                                                updateWrapper.eq("task_id", taskId).eq("manager",manager);
                                                if (EmployeeWeeklyTasksList != null && EmployeeWeeklyTasksList.size() > 0) {
                                                    updateWrapper.set("task_name", taskName);
                                                    updateWrapper.set("manager", manager);
                                                    updateWrapper.set("time_start", deadlineTime_START);
                                                    updateWrapper.set("time_end", deadlineTime_END);
                                                    updateWrapper.set("task_type", task_type);
                                                    updateWrapper.set("status", status);
                                                    updateWrapper.set("department",department);
                                                    employeeWeeklyTasksMapper.update(null, updateWrapper);
                                                } else {
                                                    int insert = employeeWeeklyTasksMapper.insert(employeeWeeklyTasks);
                                                    Map<String, Object> response1 = new HashMap<>();
                                                    if (insert > 0) {
                                                        response1.put("success", true);
                                                        response1.put("message", "用户创建成功");
                                                        response1.put("data", "");
                                                        log.info("任务创建成功，任务名称：{}，任务id：{}", employeeWeeklyTasks.getTaskName(), employeeWeeklyTasks.getTaskId());
                                                    }
                                                }
                                            }
//                                        manager = value;
                                            break;
                                    }
                                }
                            }


                        }
                }

            }
        }
        log.info("员工每周工作内容已同步");
        return McR.success();
    }

    /*todo:年度季节品类打样数量*/
    @Scheduled(cron = "0 0 2 * * ?")
    @PostMapping("/annualSeasonalSample")
    @SneakyThrows
    McR annualSeasonalSample(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = " (tfsId = 6878b38c6e46cb7d4fec9479  OR tfsId = 6878b38d6e46cb7d4fec9516) AND (scenarioId = 6878b3c0669d175c3c6bc679 OR scenarioId = 6878b3ceb5ffcf500365d17a) AND (cf:691c29c1f8cbae320a1c8e75 = 二级设计 OR cf:691c29c1f8cbae320a1c8e75 = 二级系列设计) AND cf:687df8813d5081f8c81cf375 = 公司 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND created >= 2026-01-01";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//57
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                //补充：查询任务前先看下这个是否是新版本的工作流
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "确认工";//确认工艺等级完成
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", allIds.get(j));
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String customer = "";//客户
                        String designType = "";//设计类别
                        String designlevel = "";//设计等级
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        designType = value;
                                        break;
                                }
                            }
                        }
                        /*todo:给实体赋值*/
                        AnnualSeasonalSample annualSeasonalSample = new AnnualSeasonalSample();
                        annualSeasonalSample.setTaskId(taskId);
                        annualSeasonalSample.setTaskName(taskName);
                        annualSeasonalSample.setCustomer(customer);
                        annualSeasonalSample.setDesignType(designType);
                        annualSeasonalSample.setDesignLevel(designlevel);
                        //4、插入数据库
                        QueryWrapper<AnnualSeasonalSample> queryWrapper = new QueryWrapper<>();
                        List<AnnualSeasonalSample> AnnualSeasonalSampleList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            AnnualSeasonalSampleList = annualSeasonalSampleMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        UpdateWrapper<AnnualSeasonalSample> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (AnnualSeasonalSampleList != null && AnnualSeasonalSampleList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("design_type", designType);
                            updateWrapper.set("design_level", designlevel);
                            annualSeasonalSampleMapper.update(null, updateWrapper);
                        }else {
                            int insert = annualSeasonalSampleMapper.insert(annualSeasonalSample);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", annualSeasonalSample.getTaskName(),annualSeasonalSample.getTaskId());
                            }
                        }
                    }
                }
            }

        }
        log.info("年度季节品类打样数量同步完成");
        return McR.success();
    }

    /*todo:年度季节品类确认数量*/
    @Scheduled(cron = "0 0 4 * * ?")
    @PostMapping("/annualSeasonalCategory")
    @SneakyThrows
    McR annualSeasonalCategory(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "tfsId = 6878b38d6e46cb7d4fec9592 AND scenarioId = 6878b3d8f40485da4c5f99a2 AND (cf:691c29c1f8cbae320a1c8e75 = 二级设计 OR cf:691c29c1f8cbae320a1c8e75 = 二级系列设计) AND cf:687df8813d5081f8c81cf375 = 公司 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND created >= 2026-01-01";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//6
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                //补充：查询任务前先看下这个是否是新版本的工作流
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "确认工";//确认工艺等级完成
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", allIds.get(j));
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String customer = "";//客户
                        String designType = "";//设计类别
                        String designlevel = "";//设计等级
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        designType = value;
                                        break;
                                }
                            }
                        }
                        /*todo:给实体赋值*/
                        AnnualSeasonalCategory annualSeasonalCategory = new AnnualSeasonalCategory();
                        annualSeasonalCategory.setTaskId(taskId);
                        annualSeasonalCategory.setTaskName(taskName);
                        annualSeasonalCategory.setCustomer(customer);
                        annualSeasonalCategory.setDesignType(designType);
                        annualSeasonalCategory.setDesignLevel(designlevel);
                        //4、插入数据库
                        QueryWrapper<AnnualSeasonalCategory> queryWrapper = new QueryWrapper<>();
                        List<AnnualSeasonalCategory> AnnualSeasonalCategoryList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            AnnualSeasonalCategoryList = annualSeasonalCategoryMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        UpdateWrapper<AnnualSeasonalCategory> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (AnnualSeasonalCategoryList != null && AnnualSeasonalCategoryList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("design_type", designType);
                            updateWrapper.set("design_level", designlevel);
                            annualSeasonalCategoryMapper.update(null, updateWrapper);
                        }else {
                            int insert = annualSeasonalCategoryMapper.insert(annualSeasonalCategory);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", annualSeasonalCategory.getTaskName(),annualSeasonalCategory.getTaskId());
                            }
                        }
                    }
                }
            }

        }
        log.info("年度季节品类确认数量同步完成");
        return McR.success();
    }

    /*todo:新工艺落地情况*/
    @Scheduled(cron = "0 30 1 * * ?")
    @SneakyThrows
    @PostMapping("/newprocessImplementation")
    McR newprocessImplementation(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "(scenarioId = 6878b3d8f40485da4c5f99a2 OR scenarioId = 6878b3ceb5ffcf500365d17a OR scenarioId = 6878b3c0669d175c3c6bc679) AND (tfsId = 6878b38d6e46cb7d4fec9592 OR tfsId = 6878b38c6e46cb7d4fec9479 OR tfsId = 6878b38d6e46cb7d4fec9516) AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND cf:687df8813d5081f8c81cf375 = 公司 AND created >= 2026-01-01";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//个数 113
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                //补充：查询任务前先看下这个是否是新版本的工作流
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "确认工";//确认工艺等级完成
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", allIds.get(j));
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String customer = "";//客户
                        String designType = "";//设计类别
                        String designlevel = "";//设计等级
                        String repetitionCount = "";//遍数
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        designType = value;
                                        break;
                                    case "691c1e19bac224231d7b0994":
                                        repetitionCount = value;
                                }
                            }
                        }
                        /*todo:给实体赋值*/
                        NewprocessImplementation newprocessImplementation = new NewprocessImplementation();
                        newprocessImplementation.setTaskId(taskId);
                        newprocessImplementation.setTaskName(taskName);
                        newprocessImplementation.setCustomer(customer);
                        newprocessImplementation.setDesignType(designType);
                        newprocessImplementation.setDesignLevel(designlevel);
                        newprocessImplementation.setRepetitionCount(repetitionCount);
                        //4、插入数据库
                        QueryWrapper<NewprocessImplementation> queryWrapper = new QueryWrapper<>();
                        List<NewprocessImplementation> NewprocessImplementationList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            NewprocessImplementationList = newprocessImplementationMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        UpdateWrapper<NewprocessImplementation> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (NewprocessImplementationList != null && NewprocessImplementationList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("design_type", designType);
                            updateWrapper.set("design_level", designlevel);
                            updateWrapper.set("repetition_count",repetitionCount);
                            newprocessImplementationMapper.update(null, updateWrapper);
                        }else {
                            int insert = newprocessImplementationMapper.insert(newprocessImplementation);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", newprocessImplementation.getTaskName(),newprocessImplementation.getTaskId());
                            }
                        }
                    }
                }
            }
        }
        log.info("新工艺落地情况数据已同步");
        return McR.success();
    }

    /*todo:设计部月确认稿数量*/
    @Scheduled(cron = "0 0 1 * * ?")
    @SneakyThrows
    @PostMapping("/designdeparttMonthConfirm")
    McR DesigndeparttMonthConfirm(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "scenarioId = 6878b3d8f40485da4c5f99a2 AND tfsId = 6878b38d6e46cb7d4fec9592 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND cf:687df8813d5081f8c81cf375 = 公司 AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND created >= 2026-01-01";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//个数 26
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            String deadlineTime_END = "";
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                //补充：查询任务前先看下这个是否是新版本的工作流
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "确认工";//确认工艺等级完成
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", allIds.get(j));
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String customer = "";//客户
                        String designType = "";//设计类别
                        String designlevel = "";//设计等级
                        String time_end = "";//结束时间
                        time_end = node.getString("accomplished");
                        if(time_end != null){
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                            SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            //【时间转换】TB中获取的时间为UTC：世界标准时间，在标准时间上加上8小时，即东八区时间，也就是北京时间
                            String timeStr_A = time_end.replace("Z", " UTC");
                            try {
                                Date zhuangtaiDate_A = format.parse(timeStr_A);
                                deadlineTime_END = defaultFormat.format(zhuangtaiDate_A);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        designType = value;
                                        break;
                                }
                            }
                        }
                        /*todo:给实体赋值*/
                        DesigndeparttMonthConfirm designdeparttMonthConfirm = new DesigndeparttMonthConfirm();
                        designdeparttMonthConfirm.setTaskId(taskId);
                        designdeparttMonthConfirm.setTaskName(taskName);
                        designdeparttMonthConfirm.setCustomer(customer);
                        designdeparttMonthConfirm.setDesignType(designType);
                        designdeparttMonthConfirm.setDesignLevel(designlevel);
                        designdeparttMonthConfirm.setDateLineEnd(deadlineTime_END);
                        //4、插入数据库
                        QueryWrapper<DesigndeparttMonthConfirm> queryWrapper = new QueryWrapper<>();
                        List<DesigndeparttMonthConfirm> DesigndeparttMonthConfirmList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            DesigndeparttMonthConfirmList = designdeparttMonthConfirmMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        UpdateWrapper<DesigndeparttMonthConfirm> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (DesigndeparttMonthConfirmList != null && DesigndeparttMonthConfirmList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("design_type", designType);
                            updateWrapper.set("design_level", designlevel);
                            updateWrapper.set("date_line_end",deadlineTime_END);
                            designdeparttMonthConfirmMapper.update(null, updateWrapper);
                        }else {
                            int insert = designdeparttMonthConfirmMapper.insert(designdeparttMonthConfirm);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", designdeparttMonthConfirm.getTaskName(),designdeparttMonthConfirm.getTaskId());
                            }
                        }
                    }
                }
            }
        }
        log.info("设计部月确认稿数量数据已同步");
        return McR.success();
    }

    /*todo:文件来源变更统计*/
    @Scheduled(cron = "0 0 4 * * ?")
    @SneakyThrows
    @PostMapping("/changedocumentsource")
    McR changedocumentsource(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "cf:687df8813d5081f8c81cf375 != null";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//个数4300
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            Map header2 = new HashMap<>();
            header2.put("x-operator-id","622ee3450cf3bb5e1a486f1f");
            McR Token2 = tbService.AppAccessToken();
            Object token2 = Token2.getData();
            header2.put("Authorization","Bearer " + token2);
            header2.put("X-Tenant-Id","61a8c26719c3b5ffe9c4cffb");
            header2.put("X-Tenant-Type","organization");
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header2, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
        //3、列出任务动态(taskid && actions = “customfield.update.v2”)
            for (int j = 0; j < allIds.size(); j++) {
                String renwutime = "";
                HashMap params3 = new HashMap();
                params3.put("actions", "customfield.update.v2");
                params3.put("pageSize",100);
                Map header3 = new HashMap<>();
                header3.put("x-operator-id","622ee3450cf3bb5e1a486f1f");
                McR Token3 = tbService.AppAccessToken();
                Object token3 = Token3.getData();
                header3.put("Authorization","Bearer " + token3);
                header3.put("X-Tenant-Id","61a8c26719c3b5ffe9c4cffb");
                header3.put("X-Tenant-Type","organization");
                String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/"+ allIds.get(j) +"/activity/list", header3, params3);
                System.out.println("doGet3" + doGet3);
                JsonNode resultNode = new ObjectMapper().readTree(doGet3).get("result");
                if(resultNode == null || resultNode.isEmpty() ){
                   //为空不做处理
                }else {
                    for (JsonNode item : resultNode) {
                        String contentStr = item.get("content").asText();
                        ObjectMapper objectMapper = new ObjectMapper();
                        JsonNode content = objectMapper.readTree(contentStr);
                        JsonNode customfieldName = content.get("customfieldName");
                        if (customfieldName != null && "文件来源".equals(customfieldName.asText())) {
                            //写入数据库
                            /*todo:给实体赋值*/
                            String taskId = allIds.get(j);//任务id
                            String taskName  = "";//任务名称
                            String renwuTime = "";//创建时间
                            String customer = "";//客户名称
                            String ywPerson = "";//业务人员
                            String zdrPerson = "";//制单人
                            String zyjl = "";//业务经理
                            String designcatogry = "";//设计类别

                            HashMap param_A = new HashMap();
                            param_A.put("taskId",taskId);
                            String doGet4 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header3, param_A);//查询任务详情

                            JSONArray customfields = JSON.parseObject(doGet4).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":
                                            customer = value;//客户名称
                                            break;
                                        case "688191972ab6c4f412ea2bb9":
                                            ywPerson = value;//业务人员
                                            break;
                                        case "687df458b9c2f9f90865c13b":
                                            zyjl = value;//业务经理
                                            break;
                                        case "687e0308e3f7ce8174a19cfc":
                                            designcatogry = value;//设计类别
                                            break;
                                        case "688191a2d18cef625eccade6":
                                            zdrPerson = value;//制单人
                                            break;
                                    }
                                }
                            }
                            ObjectMapper objectMapper4 = new ObjectMapper();
                            JsonNode rootNode = objectMapper4.readTree(doGet4);
                            for(JsonNode resultNode4 : rootNode.path("result")) {
                                taskName = resultNode4.path("content").asText();//任务名称

                                renwuTime = resultNode4.path("created").asText();//创建时间
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
                                SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                //【时间转换】TB中获取的时间为UTC：世界标准时间，在标准时间上加上8小时，即东八区时间，也就是北京时间。
                                String timeStr = renwuTime.replace("Z", " UTC");
                                try {
                                    Date zhuangtaiDate = format.parse(timeStr);
                                    renwutime = defaultFormat.format(zhuangtaiDate);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

//                                String creatorId = resultNode4.path("creatorId").asText();//创建人id
//                                List<String> involveMembers = new ArrayList<>();
//                                involveMembers.add(creatorId);
//                                zdrPerson = tbService.TBtoDinguserId(involveMembers);//创建人

                            }

                            ChangeDocumentSource changeDocumentSource = new ChangeDocumentSource();
                            changeDocumentSource.setTaskId(taskId);
                            changeDocumentSource.setTaskName(taskName);
                            changeDocumentSource.setRenwuTime(renwutime);
                            changeDocumentSource.setCustomer(customer);
                            changeDocumentSource.setYwPerson(ywPerson);
                            changeDocumentSource.setZdrPerson(zdrPerson);
                            changeDocumentSource.setZyjl(zyjl);
                            changeDocumentSource.setDesigncatogry(designcatogry);
                            //4、插入数据库
                            QueryWrapper<ChangeDocumentSource> queryWrapper = new QueryWrapper<>();
                            List<ChangeDocumentSource> changeDocumentSourceList = null;
                            try {
                                queryWrapper.eq("task_id", taskId);

                                changeDocumentSourceList = changeDocumentSourceMapper.selectList(queryWrapper);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            UpdateWrapper<ChangeDocumentSource> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("task_id", taskId);
                            if (changeDocumentSourceList != null && changeDocumentSourceList.size() > 0) {
                                updateWrapper.set("renwu_time", renwutime);
                                updateWrapper.set("customer",customer);
                                updateWrapper.set("yw_person",ywPerson);
                                updateWrapper.set("zdr_person",zdrPerson);
                                updateWrapper.set("zyjl",zyjl);
                                updateWrapper.set("designcatogry",designcatogry);
                                changeDocumentSourceMapper.update(null, updateWrapper);
                            }else {
                                int insert = changeDocumentSourceMapper.insert(changeDocumentSource);
                                Map<String, Object> response = new HashMap<>();
                                if(insert > 0){
                                    response.put("success", true);
                                    response.put("message", "用户创建成功");
                                    response.put("data", "");
                                    log.info("任务创建成功，任务名称：{}，任务id：{}", changeDocumentSource.getTaskName(),changeDocumentSource.getTaskId());
                                }
                            }
                            break;//跳出循环，开始下一个任务
                        }
                    }
                }

            }

        }
        System.out.println("[任务动态同步完毕！]");
        return McR.success();
    }

    /*todo:个人月度成功率*/
    @Scheduled(cron = "0 30 4 * * ?")
    @SneakyThrows
    @PostMapping("/personalmonthlySuccessrate")
    McR personalmonthlySuccessrate(){
        dayang();
        querengao();
        sheji();
        return McR.success();
    }

    /*todo:提成表*/
    @SneakyThrows
    @PostMapping("/commissionTable")
    McR commissionTable(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "cf:687df8813d5081f8c81cf375 = 公司 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND created >= 2026-01-01 AND (scenarioId = 6878b3a4090e6872fd6b78c6 OR scenarioId = 6878b3ad9e17ac8a027c6d37 OR scenarioId = 6878b3b60d49d89e7955726f OR scenarioId = 6878b3c0669d175c3c6bc679 OR scenarioId = 6878b3ceb5ffcf500365d17a OR scenarioId = 6878b3d8f40485da4c5f99a2) AND (tfsId = 6878b384d3c6329fa3728c10 OR tfsId = 6878b384d3c6329fa3728c50 OR tfsId = 6878b38c6e46cb7d4fec9440 OR tfsId = 6878b38c6e46cb7d4fec9479 OR tfsId =  6878b38d6e46cb7d4fec9516 OR tfsId = 6878b38d6e46cb7d4fec9592)";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//241
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值

        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情

            for (int j = 0; j < allIds.size(); j++) {
                String taskId = "";//任务id
                String taskName = "";//任务名称(品名)
                String designPerson = "";//负责人(设计接单负责人 | 设计人员)
                String customer = "";//客户
                String time = "";
                String task_type = "";//任务类型
                String department = "";//所属部门
                String design_level = "";//设计等级
                String expand_or = "";//是否扩版
                String added_plates = "";//设计扩版数量
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                //打样机打样、印刷机打样、确认稿件取的都是确认工艺等级完成节点的设计人员   存到targetList中的
                List<String> targetList = Arrays.asList("691a7ca681e221b157a87268","691a7d4ba0c38bac0aed504e","689ededd07e4bad72e58f33b");
                //设计修改单、设计扩版单、PPT效果图取的是设计接单节点的tfsId          存到targetList2中的
                List<String> targetList2 = Arrays.asList("6878b384d3c6329fa3728c0d","6878b384d3c6329fa3728c4d","6878b38c6e46cb7d4fec943e");
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String tfsId = node.getString("tfsId");
                    // 判断属于哪个列表
                    boolean isTarget2 = targetList2.contains(tfsId);
                    boolean isTarget = targetList.contains(tfsId);

                    if (isTarget2 || isTarget) {

                        if(isTarget){//打样机打样、印刷机打样、确认稿件
                            Map task = tbClient.queryTaskDetail(taskId1, null, null).get(0);
                            System.out.println("task:" + task);
                            String targetValue = Optional.ofNullable(task)
                                    .map(t -> (List<Map<String, Object>>) t.get("customfields"))
                                    .orElse(Collections.emptyList())
                                    .stream()
                                    .filter(f -> "695deb1a3fbe995aeeb1b590".equals(f.get("cfId")))
                                    .findFirst()
                                    .map(f -> (List<Map<String, Object>>) f.get("value"))
                                    .filter(v -> !v.isEmpty())
                                    .map(v -> v.get(0).get("title"))
                                    .map(String::valueOf)
                                    .orElse(null);
                            System.out.println("设计人员：" + targetValue);
                            department = UserGetDeprt(targetValue);

                        } else if (isTarget2) {//设计修改单、设计扩版单、PPT效果图
                            JSONArray assigneeIds = node.getJSONArray("assigneeIds");
                            // assigneeIds 可能为 null 或空数组
                            if (assigneeIds != null && assigneeIds.size() > 0) {
                                // 处理 assigneeIds，例如转换为 List<String>
                                List<String> ids = assigneeIds.toJavaList(String.class);
                                System.out.println("设计接单完成的 (负责人Tbid)assigneeIds: " + ids);
                                designPerson = tbService.TBtoDinguserId(ids);
                                System.out.println("负责人：" + designPerson);
                                department = UserGetDeprt(designPerson);
                            }
                        }

                        params3.put("taskId", taskId1);//allIds.get(j)
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        String type = new ObjectMapper().readTree(doGet3).get("result").get(0).get("sfcId").asText();
                        switch (type) {
                            case "6878b3b60d49d89e7955726f"://PPT效果图
                                task_type = "PPT效果图单";
                                break;
                            case "6878b3c0669d175c3c6bc679"://打样机打样
                                task_type = "打样机打样";
                                break;
                            case "6878b3ceb5ffcf500365d17a"://印刷机打样
                                task_type = "印刷机打样";
                                break;
                            case "6878b3d8f40485da4c5f99a2"://确认稿单
                                task_type = "确认稿单";
                                break;
                            case "6878b39a27ae5f3cac355fb9"://设计单
                                task_type = "设计单";
                                break;
                            case "6878b3a4090e6872fd6b78c6"://设计修改单
                                task_type = "设计修改单";
                                break;
                            case "6878b3ad9e17ac8a027c6d37"://设计扩版单
                                task_type = "设计扩版单";
                                break;
                        }
                        JSONArray customfields = JSON.parseObject(doGet3).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()) {
                                //根据cfId匹配
                                switch (cfId) {
                                    case "687df3b60ae1530fa2704499"://客户
                                        for (int a = 0; a < valueArray.size(); a++) {
                                            String value = valueArray.getJSONObject(a).getString("title");
                                            customer = value;
                                        }
                                        break;
                                    case "691c29c1f8cbae320a1c8e75"://设计等级
                                        for (int a = 0; a < valueArray.size(); a++) {
                                            String value = valueArray.getJSONObject(a).getString("title");
                                            design_level = value;
                                        }
                                        break;
                                    case "691c29e9b9b559205fded8f2"://设计扩版数量
                                        for (int a = 0; a < valueArray.size(); a++) {
                                            String value = valueArray.getJSONObject(a).getString("title");
                                            added_plates = value;
                                        }
                                        break;
                                    case "6878ab7d30e46af5c88d2324"://是否扩版
                                        for (int a = 0; a < valueArray.size(); a++) {
                                            String value = valueArray.getJSONObject(a).getString("title");
                                            expand_or = value;
                                        }
                                        break;
                                }
                            }
                        }

                        /*todo:给实体赋值*/
                        CommissionTable commissionTable = new CommissionTable();
                        commissionTable.setTaskId(taskId);
                        commissionTable.setTaskName(taskName);
                        commissionTable.setDesignPerson(designPerson);
                        commissionTable.setTaskType(task_type);
                        commissionTable.setDepartment(department);
                        commissionTable.setCustomer(customer);
                        commissionTable.setAddedPlates(added_plates);
                        commissionTable.setDesignLevel(design_level);
                        commissionTable.setExpandOr(expand_or);

                        //4、插入数据库
                        QueryWrapper<CommissionTable> queryWrapper = new QueryWrapper<>();
                        List<CommissionTable> commissionTableList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);
                            commissionTableList = commissionTableMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        UpdateWrapper<CommissionTable> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (commissionTableList != null && commissionTableList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("design_person", designPerson);
                            updateWrapper.set("task_type", task_type);
                            updateWrapper.set("department", department);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("added_plates",added_plates);
                            updateWrapper.set("price",null);
                            updateWrapper.set("design_level",design_level);
                            updateWrapper.set("expand_or",expand_or);
                            commissionTableMapper.update(null, updateWrapper);
                        } else {
                            int insert = commissionTableMapper.insert(commissionTable);
                            Map<String, Object> response1 = new HashMap<>();
                            if (insert > 0) {
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", commissionTable.getTaskName(), commissionTable.getTaskId());
                            }
                        }

                    }
                }

            }
        }
        log.info("提成表已同步");
        return McR.success();
    }

    /*todo:提成表AI*/
    @Scheduled(cron = "0 0 5 * * ?")
    @SneakyThrows
    @PostMapping("/commissionTableAI")
    public McR commissionTableAI() {
        // 1、统计符合条件的任务个数
        Map 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");

        HashMap param = new HashMap();
        String q = "cf:687df8813d5081f8c81cf375 = 公司 AND tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND created >= 2026-01-01 AND (scenarioId = 6878b3a4090e6872fd6b78c6 OR scenarioId = 6878b3ad9e17ac8a027c6d37 OR scenarioId = 6878b3b60d49d89e7955726f OR scenarioId = 6878b3c0669d175c3c6bc679 OR scenarioId = 6878b3ceb5ffcf500365d17a OR scenarioId = 6878b3d8f40485da4c5f99a2) AND (tfsId = 6878b384d3c6329fa3728c10 OR tfsId = 6878b384d3c6329fa3728c50 OR tfsId = 6878b38c6e46cb7d4fec9440 OR tfsId = 6878b38c6e46cb7d4fec9479 OR tfsId =  6878b38d6e46cb7d4fec9516 OR tfsId = 6878b38d6e46cb7d4fec9592)";
        param.put("q", q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", header, param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0; // 总数

        // 2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize", 100);
        String pageToken = ""; // 初始值

        // 临时列表，存放所有任务（价格先不填）
        List<CommissionTable> tempTaskList = new ArrayList<>();

        for (int i = 0; i < result / 100 + 1; i++) {
            ArrayList<String> allIds = new ArrayList<>();
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            }

            // 3、查询每个任务的详情，收集信息
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");

                // 打样机打样、印刷机打样、确认稿件取确认工艺等级完成节点的设计人员（targetList）
                List<String> targetList = Arrays.asList("691a7ca681e221b157a87268", "691a7d4ba0c38bac0aed504e", "689ededd07e4bad72e58f33b");
                // 设计修改单、设计扩版单、PPT效果图取设计接单节点的tfsId（targetList2）
                List<String> targetList2 = Arrays.asList("6878b384d3c6329fa3728c0d", "6878b384d3c6329fa3728c4d", "6878b38c6e46cb7d4fec943e");

                // 默认值
                String designPerson = "";
                String department = "";
                String taskId = "";
                String taskName = "";
                String task_type = "";
                String customer = "";
                String design_level = "";
                String expand_or = "";
                String added_plates = "";
                String completedTime = "";

                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String tfsId = node.getString("tfsId");
                    boolean isTarget2 = targetList2.contains(tfsId);
                    boolean isTarget = targetList.contains(tfsId);

                    if (isTarget2 || isTarget) {
                        // 负责人获取
                        if (isTarget) { // 打样机打样、印刷机打样、确认稿件：从 customfields 中取设计人员（cfId:695deb1a3fbe995aeeb1b590）
                            Map task = tbClient.queryTaskDetail(taskId1, null, null).get(0);
                            String targetValue = Optional.ofNullable(task)
                                    .map(t -> (List<Map<String, Object>>) t.get("customfields"))
                                    .orElse(Collections.emptyList())
                                    .stream()
                                    .filter(f -> "695deb1a3fbe995aeeb1b590".equals(f.get("cfId")))
                                    .findFirst()
                                    .map(f -> (List<Map<String, Object>>) f.get("value"))
                                    .filter(v -> !v.isEmpty())
                                    .map(v -> v.get(0).get("title"))
                                    .map(String::valueOf)
                                    .orElse(null);
                            designPerson = targetValue;
                            department = UserGetDeprt(designPerson);
                        } else if (isTarget2) { // 设计修改单、设计扩版单、PPT效果图：从 assigneeIds 取负责人
                            JSONArray assigneeIds = node.getJSONArray("assigneeIds");
                            if (assigneeIds != null && assigneeIds.size() > 0) {
                                List<String> ids = assigneeIds.toJavaList(String.class);
                                designPerson = tbService.TBtoDinguserId(ids);
                                department = UserGetDeprt(designPerson);
                            }
                        }

                        // 获取任务详情（taskId, taskName, 类型, customfields）
                        params3.put("taskId", taskId1);
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        JsonNode taskNode = new ObjectMapper().readTree(doGet3).get("result").get(0);
                        taskId = taskNode.get("id").asText();
                        taskName = taskNode.get("content").asText();
                        completedTime = convertUtcToBeijingTime(new ObjectMapper().readTree(doGet3).get("result").get(0).get("accomplishTime").asText());
                        String type = taskNode.get("sfcId").asText();
                        switch (type) {
                            case "6878b3b60d49d89e7955726f":
                                task_type = "PPT效果图单";
                                break;
                            case "6878b3c0669d175c3c6bc679":
                                task_type = "打样机打样";
                                break;
                            case "6878b3ceb5ffcf500365d17a":
                                task_type = "印刷机打样";
                                break;
                            case "6878b3d8f40485da4c5f99a2":
                                task_type = "确认稿单";
                                break;
                            case "6878b39a27ae5f3cac355fb9":
                                task_type = "设计单";
                                break;
                            case "6878b3a4090e6872fd6b78c6":
                                task_type = "设计修改单";
                                break;
                            case "6878b3ad9e17ac8a027c6d37":
                                task_type = "设计扩版单";
                                break;
                        }

                        // 解析 customfields（客户、设计等级、扩版数量、是否扩版）
                        JSONArray customfields = JSON.parseObject(doGet3).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()) {
                                switch (cfId) {
                                    case "687df3b60ae1530fa2704499": // 客户
                                        customer = valueArray.getJSONObject(0).getString("title");
                                        break;
                                    case "691c29c1f8cbae320a1c8e75": // 设计等级
                                        design_level = valueArray.getJSONObject(0).getString("title");
                                        break;
                                    case "691c29e9b9b559205fded8f2": // 设计扩版数量
                                        added_plates = valueArray.getJSONObject(0).getString("title");
                                        break;
                                    case "6878ab7d30e46af5c88d2324": // 是否扩版
                                        expand_or = valueArray.getJSONObject(0).getString("title");
                                        break;
                                }
                            }
                        }

                        // 构建临时对象，加入列表（price 暂不设置）
                        CommissionTable commissionTable = new CommissionTable();
                        commissionTable.setTaskId(taskId);
                        commissionTable.setTaskName(taskName);
                        commissionTable.setDesignPerson(designPerson);
                        commissionTable.setTaskType(task_type);
                        commissionTable.setDepartment(department);
                        commissionTable.setCustomer(customer);
                        commissionTable.setAddedPlates(added_plates);
                        commissionTable.setDesignLevel(design_level);
                        commissionTable.setExpandOr(expand_or);
                        commissionTable.setDate(completedTime);
                        // price 后面统一计算
                        tempTaskList.add(commissionTable);
                    }
                }
            }
        }

        // 4、统一计算价格
        for (CommissionTable ct : tempTaskList) {
            // 规则1：确认稿单且二级设计时，根据是否有同客户同品名的打样任务判断价格
            if ("确认稿单".equals(ct.getTaskType()) && "二级设计".equals(ct.getDesignLevel())) {
                boolean hasSample = tempTaskList.stream().anyMatch(t ->
                        ("打样机打样".equals(t.getTaskType()) || "印刷机打样".equals(t.getTaskType()))
                                && ct.getCustomer().equals(t.getCustomer())
                                && ct.getTaskName().equals(t.getTaskName())
                );
                ct.setPrice(String.valueOf(hasSample ? 600 : 800));
            } else {
                // 规则2：按设计等级和任务类型计算基础价格
                double basePrice = 0;
                String taskType = ct.getTaskType();
                String originalLevel = ct.getDesignLevel();

                // 将系列设计映射到对应等级，用于计算基础价格
                String levelForBase = originalLevel;
                if ("二级系列设计".equals(originalLevel)) {
                    levelForBase = "二级设计";
                } else if ("三级系列设计".equals(originalLevel)) {
                    levelForBase = "三级设计";
                }

                // 打样类任务（印刷机打样、打样机打样）
                if ("印刷机打样".equals(taskType) || "打样机打样".equals(taskType)) {
                    switch (levelForBase) {
                        case "一级设计": basePrice = 0; break;
                        case "二级设计": basePrice = 200; break;
                        case "三级设计": basePrice = 0; break;
                        case "四级设计": basePrice = 0; break;
                        case "五级设计": basePrice = 100; break;
                        default: basePrice = 0;
                    }
                }
                // 确认稿单
                else if ("确认稿单".equals(taskType)) {
                    switch (levelForBase) {
                        case "一级设计": basePrice = 1000; break;
                        case "二级设计": basePrice = 600; break;
                        case "三级设计": basePrice = 400; break;
                        case "四级设计": basePrice = 200; break;
                        case "五级设计": basePrice = 100; break;
                        default: basePrice = 0;
                    }
                }
                // PPT效果图
                else if ("PPT效果图单".equals(taskType)) {
                    basePrice = 100;
                }
                // 其他类型不包含设计价格
                else {
                    basePrice = 0;
                }

                // 规则3：扩版价格
                double expandPrice = 0;
                if ("扩版".equals(ct.getExpandOr())) {
                    try {
                        int plates = Integer.parseInt(ct.getAddedPlates().trim());
                        expandPrice = 20 * plates;
                    } catch (NumberFormatException e) {
                        expandPrice = 0;
                    }
                }

                double totalPrice = basePrice + expandPrice;

                // 规则4：二级系列设计或三级系列设计，总价乘以0.25
                if ("二级系列设计".equals(originalLevel) || "三级系列设计".equals(originalLevel)) {
                    totalPrice = totalPrice * 0.25;
                }

                // 特殊：跨年连选/客户文件 价格为0
                if ("跨年连选/客户文件".equals(originalLevel)) {
                    totalPrice = 0;
                }

                // 保留两位小数
                ct.setPrice(String.valueOf(Math.round(totalPrice * 100) / 100.0));
            }
        }

        // 5、统一插入/更新数据库
        for (CommissionTable ct : tempTaskList) {
            QueryWrapper<CommissionTable> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("task_id", ct.getTaskId());
            List<CommissionTable> existingList = commissionTableMapper.selectList(queryWrapper);
            if (existingList != null && !existingList.isEmpty()) {
                UpdateWrapper<CommissionTable> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("task_id", ct.getTaskId());
                updateWrapper.set("task_name", ct.getTaskName());
                updateWrapper.set("design_person", ct.getDesignPerson());
                updateWrapper.set("task_type", ct.getTaskType());
                updateWrapper.set("department", ct.getDepartment());
                updateWrapper.set("customer", ct.getCustomer());
                updateWrapper.set("added_plates", ct.getAddedPlates());
                updateWrapper.set("price", ct.getPrice());
                updateWrapper.set("design_level", ct.getDesignLevel());
                updateWrapper.set("expand_or", ct.getExpandOr());
                updateWrapper.set("date",ct.getDate());
                commissionTableMapper.update(null, updateWrapper);
            } else {
                int insert = commissionTableMapper.insert(ct);
                if (insert > 0) {
                    log.info("任务创建成功，任务名称：{}，任务id：{}", ct.getTaskName(), ct.getTaskId());
                }
            }
        }

        log.info("提成表AI已同步");
        return McR.success();
    }

    /*todo:人员获取部门*/
    @SneakyThrows
    @PostMapping("/UserGetDeprt")
    String UserGetDeprt(@RequestParam String User){
        Map 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");
        HashMap param = new HashMap();
        param.put("query",User);
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/org/member/search", (Map) header, (Map) param);
        JSONObject jsonObject = JSON.parseObject(doGet);
        JSONArray resultArray = jsonObject.getJSONArray("result");
        String userId = "";
        String value = "";
        if (resultArray != null && !resultArray.isEmpty()) {
            JSONObject firstUser = resultArray.getJSONObject(0);
            userId = firstUser.getString("userId");
            System.out.println("提取到的userId: " + userId);
            List<String> involveMembers = new ArrayList<>();
            involveMembers.add(userId);
            HashMap param2 = new HashMap();
            param2.put("tbUserIds",involveMembers);
            String s = UtilHttp.doGet("https://open.teambition.com/api/idmap/dingtalk/getDingUserId", header, param2);
            ObjectMapper objectMapper = new ObjectMapper();
            var rootNode = objectMapper.readTree(s);
            List<String> userIdList  = objectMapper.convertValue(
                            rootNode.get("result"),
                            new TypeReference<List<Map<String, String>>>() {
                            }
                    )
                    .stream()
                    .map(map -> map.get("dingtalkUserId"))
                    .collect(Collectors.toList());
            System.out.println(userIdList);
            HashMap head = new HashMap();
            McR Token2 = tbService.OuNuoXinAccessToken();
            Object Data = Token2.getData();
            head.put("x-acs-dingtalk-access-token",Data);
            HashMap boddy = new HashMap();
            boddy.put("userIdList",userIdList);
            boddy.put("fieldFilterList", Arrays.asList("sys00-mainDept"));
            boddy.put("appAgentId","4115325431");
            boddy.put("text2SelectConvert",true);
            String ddt = UtilHttp.doPost("https://api.dingtalk.com/v1.0/hrm/rosters/lists/query",head,null,boddy);
            // 使用Fastjson解析
            JSONObject jsonObj = JSON.parseObject(ddt);
            JSONArray resultArray2 = jsonObj.getJSONArray("result");

            if (resultArray2 != null && !resultArray2.isEmpty()) {
                JSONObject firstResult = resultArray2.getJSONObject(0);
                JSONArray fieldDataList = firstResult.getJSONArray("fieldDataList");

                if (fieldDataList != null && !fieldDataList.isEmpty()) {
                    // 遍历fieldDataList找到主部门字段（如果有多个字段的话）
                    for (int i = 0; i < fieldDataList.size(); i++) {
                        JSONObject fieldData = fieldDataList.getJSONObject(i);
                        String fieldCode = fieldData.getString("fieldCode");

                        // 如果是主部门字段
                        if ("sys00-mainDept".equals(fieldCode)) {
                            JSONArray fieldValueList = fieldData.getJSONArray("fieldValueList");
                            if (fieldValueList != null && !fieldValueList.isEmpty()) {
                                JSONObject firstValue = fieldValueList.getJSONObject(0);
                                value = firstValue.getString("value");
                                System.out.println("提取到的部门: " + value);
                            }
                            break;
                        }
                    }
                }
            }
        }
        return value;
    }

    /*todo：个人月度成功率
    *  1、打样机打样/印刷机打样*/
    @SneakyThrows
    public void dayang(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "tagId != \"68f5840f90efa8d7498bd5e9\" AND tagId != \"68f58407a89ee3bbe639f85c\" " +
                "AND created >= \"2026-01-01\" AND cf:691c29c1f8cbae320a1c8e75 != \"无\" " +
                "AND cf:691c29c1f8cbae320a1c8e75 != \"扩版\" AND cf:691c29c1f8cbae320a1c8e75 != \"二级系列设计\" " +
                "AND cf:691c29c1f8cbae320a1c8e75 != \"三级系列设计\" AND cf:691c29c1f8cbae320a1c8e75 != \"跨年连选/客户文件\" " +
                "AND (scenarioId = \"6878b3c0669d175c3c6bc679\" OR scenarioId = \"6878b3ceb5ffcf500365d17a\") " +
                "AND (tfsId = \"6878b38c6e46cb7d4fec9479\" OR tfsId = \"6878b38d6e46cb7d4fec9516\") " +
                "AND cf:695deb1a3fbe995aeeb1b590 != null " +
                String.format("AND accomplished >= \"%s\" AND accomplished < \"%s\"", LocalDate.now().minusDays(1), LocalDate.now());

//        String q = "tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c  AND created >= 2026-01-01 AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND cf:691c29c1f8cbae320a1c8e75 != 二级系列设计 AND cf:691c29c1f8cbae320a1c8e75 != 三级系列设计 AND cf:691c29c1f8cbae320a1c8e75 != 跨年连选/客户文件 AND (scenarioId = 6878b3c0669d175c3c6bc679 OR scenarioId = 6878b3ceb5ffcf500365d17a) AND (tfsId = 6878b38c6e46cb7d4fec9479 OR tfsId = 6878b38d6e46cb7d4fec9516) AND accomplished >= 2026-04-01 AND accomplished < 2026-05-01 AND cf:695deb1a3fbe995aeeb1b590 != null";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//241
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "确认工";//确认工艺等级完成
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", allIds.get(j));
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String taskType = "";//任务类型
                        String deisgnPerson = "";//设计人员
                        String department = "";//所属部门
                        String customer = "";//客户
                        String designlevel = "";//设计等级
                        String completedTime = "";//完成时间(+8T)
                        String deadlineTime = "";//节点完成时间(+8T)
                        deadlineTime = convertUtcToBeijingTime(node.getString("accomplished"));
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        completedTime = convertUtcToBeijingTime(new ObjectMapper().readTree(doGet3).get("result").get(0).get("accomplishTime").asText());
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        taskType = value;
                                        break;
                                    case "695deb1a3fbe995aeeb1b590":
                                        deisgnPerson = value;
                                        if(deisgnPerson.equals("刘佳辉") || deisgnPerson.equals("刘家辉")){
                                            department = UserGetDeprt("刘佳辉");
                                        }else {
                                            department = UserGetDeprt(deisgnPerson);
                                        }
                                }
                            }
                        }
                        /*todo:给实体赋值*/
                        PersonalMonthlySuccessrate personalMonthlySuccessrate = new PersonalMonthlySuccessrate();
                        personalMonthlySuccessrate.setTaskId(taskId);
                        personalMonthlySuccessrate.setTaskName(taskName);
                        personalMonthlySuccessrate.setTaskType(taskType);
                        personalMonthlySuccessrate.setDesignPerson(deisgnPerson);
                        personalMonthlySuccessrate.setDepartment(department);
                        personalMonthlySuccessrate.setCustomer(customer);
                        personalMonthlySuccessrate.setDesignlevel(designlevel);
                        personalMonthlySuccessrate.setTime(completedTime);
                        personalMonthlySuccessrate.setDeadlineTime(deadlineTime);
                        //4、插入数据库
                        QueryWrapper<PersonalMonthlySuccessrate> queryWrapper = new QueryWrapper<>();
                        List<PersonalMonthlySuccessrate> personalMonthlySuccessrateList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            personalMonthlySuccessrateList = personalMonthlySuccessrateMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        UpdateWrapper<PersonalMonthlySuccessrate> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (personalMonthlySuccessrateList != null && personalMonthlySuccessrateList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("task_type",taskType);
                            updateWrapper.set("design_person",deisgnPerson);
                            updateWrapper.set("department",department);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("designlevel", designlevel);
                            updateWrapper.set("time",completedTime);
                            updateWrapper.set("deadline_time",deadlineTime);

                            personalMonthlySuccessrateMapper.update(null, updateWrapper);
                        }else {
                            int insert = personalMonthlySuccessrateMapper.insert(personalMonthlySuccessrate);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", personalMonthlySuccessrate.getTaskName(),personalMonthlySuccessrate.getTaskId());
                            }
                        }
                    }
                }
            }
        }
        log.info("个人月度成功率已同步------打样机/印刷机打样");
    }

    /*todo：个人月度成功率
     *  2、确认稿件*/
    @SneakyThrows
    public void querengao(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c " +
                "AND created >= 2026-01-01 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 无 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 扩版 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 二级系列设计 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 三级系列设计 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 跨年连选/客户文件 " +
                "AND scenarioId = 6878b3d8f40485da4c5f99a2 " +
                "AND tfsId = 6878b38d6e46cb7d4fec9592 " +
                "AND cf:695deb1a3fbe995aeeb1b590 != null " +
                String.format("AND accomplished >= %s AND accomplished < %s",
                        LocalDate.now().minusDays(1), LocalDate.now());
//        String q = "tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND created >= 2026-01-01 AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND cf:691c29c1f8cbae320a1c8e75 != 二级系列设计 AND cf:691c29c1f8cbae320a1c8e75 != 三级系列设计 AND cf:691c29c1f8cbae320a1c8e75 != 跨年连选/客户文件 AND scenarioId = 6878b3d8f40485da4c5f99a2 AND tfsId = 6878b38d6e46cb7d4fec9592 AND accomplished >= 2026-04-01 AND accomplished < 2026-05-01 AND cf:695deb1a3fbe995aeeb1b590 != null";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//241
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);
                HashMap params3 = new HashMap();
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "确认工";//确认工艺等级完成
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", allIds.get(j));
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String taskType = "";//任务类型
                        String deisgnPerson = "";//设计人员
                        String department = "";//所属部门
                        String customer = "";//客户
                        String designlevel = "";//设计等级
                        String completedTime = "";//完成时间(+8T)
                        String deadlineTime = "";//节点完成时间(+8T)
                        deadlineTime = convertUtcToBeijingTime(node.getString("accomplished"));
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        completedTime = convertUtcToBeijingTime(new ObjectMapper().readTree(doGet3).get("result").get(0).get("accomplishTime").asText());
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        taskType = value;
                                        break;
                                    case "695deb1a3fbe995aeeb1b590":
                                        deisgnPerson = value;
                                        if(deisgnPerson.equals("刘佳辉") || deisgnPerson.equals("刘家辉")){
                                            department = UserGetDeprt("刘佳辉");
                                        }else {
                                            department = UserGetDeprt(deisgnPerson);
                                        }
                                }
                            }
                        }
                        /*todo:给实体赋值*/
                        PersonalMonthlySuccessrate personalMonthlySuccessrate = new PersonalMonthlySuccessrate();
                        personalMonthlySuccessrate.setTaskId(taskId);
                        personalMonthlySuccessrate.setTaskName(taskName);
                        personalMonthlySuccessrate.setTaskType(taskType);
                        personalMonthlySuccessrate.setDesignPerson(deisgnPerson);
                        personalMonthlySuccessrate.setDepartment(department);
                        personalMonthlySuccessrate.setCustomer(customer);
                        personalMonthlySuccessrate.setDesignlevel(designlevel);
                        personalMonthlySuccessrate.setTime(completedTime);
                        personalMonthlySuccessrate.setDeadlineTime(deadlineTime);
                        //4、插入数据库
                        QueryWrapper<PersonalMonthlySuccessrate> queryWrapper = new QueryWrapper<>();
                        List<PersonalMonthlySuccessrate> personalMonthlySuccessrateList = null;
                        try {
                            queryWrapper.eq("task_id", taskId);

                            personalMonthlySuccessrateList = personalMonthlySuccessrateMapper.selectList(queryWrapper);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        UpdateWrapper<PersonalMonthlySuccessrate> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("task_id", taskId);
                        if (personalMonthlySuccessrateList != null && personalMonthlySuccessrateList.size() > 0) {
                            updateWrapper.set("task_name", taskName);
                            updateWrapper.set("task_type",taskType);
                            updateWrapper.set("design_person",deisgnPerson);
                            updateWrapper.set("department",department);
                            updateWrapper.set("customer", customer);
                            updateWrapper.set("designlevel", designlevel);
                            updateWrapper.set("time",completedTime);
                            updateWrapper.set("deadline_time",deadlineTime);

                            personalMonthlySuccessrateMapper.update(null, updateWrapper);
                        }else {
                            int insert = personalMonthlySuccessrateMapper.insert(personalMonthlySuccessrate);
                            Map<String, Object> response1 = new HashMap<>();
                            if(insert > 0){
                                response1.put("success", true);
                                response1.put("message", "用户创建成功");
                                response1.put("data", "");
                                log.info("任务创建成功，任务名称：{}，任务id：{}", personalMonthlySuccessrate.getTaskName(),personalMonthlySuccessrate.getTaskId());
                            }
                        }
                    }
                }
            }
        }
        log.info("个人月度成功率已同步------确认稿件");
    }

    /*todo：个人月度成功率
    *  3、设计单*/
    @SneakyThrows
    public void sheji(){
        //1、统计符合条件的任务个数
        Map 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");
        HashMap param = new HashMap();
        String q = "tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c " +
                "AND created >= 2026-01-01 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 无 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 扩版 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 二级系列设计 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 三级系列设计 " +
                "AND cf:691c29c1f8cbae320a1c8e75 != 跨年连选/客户文件 " +
                "AND scenarioId = 6878b39a27ae5f3cac355fb9 " +
                "AND tfsId = 6878b384d3c6329fa3728bc9 " +
                String.format("AND accomplished >= %s AND accomplished < %s",
                        LocalDate.now().minusDays(1), LocalDate.now());
//        String q = "tagId != 68f5840f90efa8d7498bd5e9 AND tagId != 68f58407a89ee3bbe639f85c AND created >= 2026-01-01 AND cf:691c29c1f8cbae320a1c8e75 != 无 AND cf:691c29c1f8cbae320a1c8e75 != 扩版 AND cf:691c29c1f8cbae320a1c8e75 != 二级系列设计 AND cf:691c29c1f8cbae320a1c8e75 != 三级系列设计 AND cf:691c29c1f8cbae320a1c8e75 != 跨年连选/客户文件 AND scenarioId = 6878b39a27ae5f3cac355fb9 AND tfsId = 6878b384d3c6329fa3728bc9 AND accomplished >= 2026-04-10 AND accomplished < 2026-04-11";
        param.put("q",q);
        String projectId = "6878b323386fac7ab9dbe5e9";
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/count", (Map) header, (Map) param);
        Matcher m = Pattern.compile("\"result\":(\\d+)").matcher(doGet);
        int result = m.find() ? Integer.parseInt(m.group(1)) : 0;//85
        //2、分页查询
        HashMap param1 = new HashMap();
        param1.put("pageSize",100);
        String pageToken = "";//初始值
        for (int i=0;i<result/100 + 1;i++) {
            ArrayList<String> allIds = new ArrayList<>();//todo:->>>>>>>>>全部任务id存在allIds
            param1.put("q", q);
            param1.put("pageToken", pageToken);
            String doGet1 = UtilHttp.doGet("https://open.teambition.com/api/v3/project/6878b323386fac7ab9dbe5e9/task/query", header, param1);
            List<String> batchIds = extractIdsFromJson(doGet1);
            allIds.addAll(batchIds);//添加到总列表
            ObjectMapper mapper = new ObjectMapper();
            String nextPageToken = mapper.readTree(doGet1).get("nextPageToken").asText();
            if (nextPageToken != null && !nextPageToken.trim().isEmpty()) {
                pageToken = nextPageToken;
            } else {
                // 为空，不进行处理
            }
            //3、查询任务详情
            for (int j = 0; j < allIds.size(); j++) {
                String taskId1 = allIds.get(j);

                HashMap params3 = new HashMap();
                String doneGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId1 + "/node/list", header, new HashMap());
                JSONObject response = JSON.parseObject(doneGet);
                JSONArray resultArray = response.getJSONArray("result");
                String targetName = "设计接";
                for (int k = 0; k < resultArray.size(); k++) {
                    JSONObject node = resultArray.getJSONObject(k);
                    String currentNodeId = node.getString("name");
                    String indexOf = currentNodeId.substring(0,3);
                    //抓取设计接单节点数据
                    if (targetName.contains(indexOf)) {
                        params3.put("taskId", taskId1);//allIds.get(j)
                        String doGet3 = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", header, params3);
                        String taskId = "";//任务id
                        String taskName = "";//任务名称
                        String taskType = "";//任务类型
                        String manager = "";//负责人
                        String department = "";//所属部门
                        String customer = "";//客户
                        String designlevel = "";//设计等级
                        String completedTime = "";//完成时间
                        String deadlineTime = "";//节点完成时间
                        deadlineTime = convertUtcToBeijingTime(node.getString("accomplished"));
                        taskId = new ObjectMapper().readTree(doGet3).get("result").get(0).get("id").asText();
                        taskName = new ObjectMapper().readTree(doGet3).get("result").get(0).get("content").asText();
                        completedTime = convertUtcToBeijingTime(new ObjectMapper().readTree(doGet3).get("result").get(0).get("accomplishTime").asText());
                        JSONArray customfields = JSON.parseObject(doGet3).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 "691c29c1f8cbae320a1c8e75":
                                        designlevel = value;
                                        break;
                                    case "687df3b60ae1530fa2704499":
                                        customer = value;
                                        break;
                                    case "687e0308e3f7ce8174a19cfc":
                                        taskType = value;
                                        break;
                                }
                            }
                        }

                        String assigneeIds = node.getString("assigneeIds");
                        ObjectMapper mappers = new ObjectMapper();
                        List<String> list = mappers.readValue(assigneeIds, new TypeReference<List<String>>() {});
                        String dingusers = tbService.TBtoDinguserId(list);

                        List<String> nameList = new ArrayList<>();
                        // 判空：null、空字符串、纯空格都视为空
                        if (dingusers != null && !dingusers.trim().isEmpty()) {
                            nameList = Arrays.stream(dingusers.split(","))
                                    .map(String::trim)
                                    .collect(Collectors.toList());
                        } else {
                            System.out.println("dingusers 为空，无法转换");
                        }

                        for (String name : nameList) {
                            manager = name;
                            if("刘佳辉".equals(manager) || "刘家辉".equals(manager)){
                                department = UserGetDeprt("刘佳辉");
                            }else {
                                department = UserGetDeprt(manager);
                            }
                            /*todo:给实体赋值*/
                            PersonalMonthlySuccessrate personalMonthlySuccessrate = new PersonalMonthlySuccessrate();
                            personalMonthlySuccessrate.setTaskId(taskId);
                            personalMonthlySuccessrate.setTaskName(taskName);
                            personalMonthlySuccessrate.setTaskType(taskType);
                            personalMonthlySuccessrate.setDesignPerson(manager);
                            personalMonthlySuccessrate.setDepartment(department);
                            personalMonthlySuccessrate.setCustomer(customer);
                            personalMonthlySuccessrate.setDesignlevel(designlevel);
                            personalMonthlySuccessrate.setTime(completedTime);
                            personalMonthlySuccessrate.setDeadlineTime(deadlineTime);
                            //4、插入数据库
                            QueryWrapper<PersonalMonthlySuccessrate> queryWrapper = new QueryWrapper<>();
                            List<PersonalMonthlySuccessrate> personalMonthlySuccessrateList = null;
                            try {
                                String finalManager = manager;
                                queryWrapper.eq("task_id", taskId).and(q1 ->q1.eq("design_person",finalManager));

                                personalMonthlySuccessrateList = personalMonthlySuccessrateMapper.selectList(queryWrapper);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            UpdateWrapper<PersonalMonthlySuccessrate> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("task_id", taskId).eq("design_person",manager);
                            if (personalMonthlySuccessrateList != null && personalMonthlySuccessrateList.size() > 0) {
                                updateWrapper.set("task_name", taskName);
                                updateWrapper.set("task_type",taskType);
                                updateWrapper.set("design_person",manager);
                                updateWrapper.set("department",department);
                                updateWrapper.set("customer", customer);
                                updateWrapper.set("designlevel", designlevel);
                                updateWrapper.set("time",completedTime);
                                updateWrapper.set("deadline_time",deadlineTime);

                                personalMonthlySuccessrateMapper.update(null, updateWrapper);
                            }else {
                                int insert = personalMonthlySuccessrateMapper.insert(personalMonthlySuccessrate);
                                Map<String, Object> response1 = new HashMap<>();
                                if(insert > 0){
                                    response1.put("success", true);
                                    response1.put("message", "用户创建成功");
                                    response1.put("data", "");
                                    log.info("任务创建成功，任务名称：{}，任务id：{}", personalMonthlySuccessrate.getTaskName(),personalMonthlySuccessrate.getTaskId());
                                }
                            }
                        }

                    }
                }

            }
        }
        log.info("个人月度成功率已同步------设计单");
    }



    /**
     * 将 UTC 时间字符串转换为北京时间字符串（格式：yyyy-MM-dd HH:mm:ss）
     * 输入示例：2026-02-27T00:35:23.201Z  → 输出：2026-02-27 08:35:23
     *
     * @param utcTimeStr UTC 时间字符串，符合 ISO-8601 标准（末尾带 Z）
     * @return 格式化后的北京时间字符串，如果输入无效则返回空字符串
     */
    public static String convertUtcToBeijingTime(String utcTimeStr) {
        if (utcTimeStr == null || utcTimeStr.isEmpty()) {
            return "";
        }
        try {
            // 解析 UTC 时间（自动处理毫秒）
            Instant instant = Instant.parse(utcTimeStr);
            // 转换为东八区（北京时间）
            ZonedDateTime beijingTime = instant.atZone(ZoneId.of("Asia/Shanghai"));
            // 格式化输出，只保留到秒
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            return beijingTime.format(formatter);
        } catch (DateTimeParseException e) {
            // 可根据实际需要记录日志或抛出运行时异常
            System.err.println("时间格式解析失败: " + utcTimeStr);
            return "";
        }
    }

}
