package com.malk.zhongche.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.teambition.TBConf;
import com.malk.server.teambition.TBR;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.teambition.TBClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import com.malk.zhongche.service.ZhongcheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Slf4j
@Service
public class ZhongcheServiceImpl implements ZhongcheService {
    @Autowired
    private TBClient tbClient;

    @Autowired
    private YDClient ydClient;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private TBConf tbConf;

    @Autowired
    private YDConf ydConf;

    @Value("${file.path}")
    private String filePath;

    @Override
    public McR getTaskInfo(String taskId,String projectId) {
        Map taskInfo = tbClient.queryTaskDetail(taskId,null,null).get(0);

        log.info("taskInfo:{}", JSONObject.toJSONString(taskInfo));

        List<Map> customfields = UtilMap.getList(taskInfo, "customfields");

        List<String> wtls = new ArrayList<>();//问题类型

        for (Map customfield : customfields) {
            String cfId = UtilMap.getString(customfield, "cfId");

            switch (cfId){
                case "6941202e92136abe2d9de68f"://问题类型
                    List<Map> value = UtilMap.getList(customfield, "value");

                    for (Map map : value) {
                        wtls.add(UtilMap.getString(map, "title"));
                    }
                    break;
                case "6969da08b9d8a458d706212d"://完成状态
                    break;
                case "6969dc054cd1174e86aa213a"://延期次数
                    break;
            }
        }

        String executorId = UtilMap.getString(taskInfo, "executorId");//执行者id

        Map ddUser = new HashMap();
        if (Strings.isNotBlank(executorId)){
            Map ddUserInfo = tbClient.idMapQuery(executorId, true).get(0);
            Map extra = UtilMap.getMap(ddUserInfo, "extra");
            String ddUserId = UtilMap.getString(extra, "userId");//执行人钉钉userid
            Map userInfoById = ddClient_contacts.getUserInfoById(ddClient.getAccessToken(),ddUserId);
            String ddUserName = UtilMap.getString(userInfoById, "name");//执行人钉钉姓名
            ddUser.put("label",ddUserName);
            ddUser.put("value",ddUserId);
            ddUser.put("emplId",ddUserId);
        }

        Long startDate = extracted(UtilMap.getString(taskInfo, "startDate"));//任务开始时间
        Long dueDate = extracted(UtilMap.getString(taskInfo, "dueDate"));//任务截止时间

        String tfsId = UtilMap.getString(taskInfo, "tfsId");//任务状态id

        Map body = new HashMap();
        body.put("tfsIds", tfsId);
        Map tfsInfo = tbClient.queryProjectCustomFlowStatus(projectId, body).get(0);
        String tfsName = UtilMap.getString(tfsInfo, "name");//任务状态

        String parentTaskId = UtilMap.getString(taskInfo, "parentTaskId");
        String parentTaskName = "";
        String rootTaskName = "";
        if (Strings.isNotBlank(parentTaskId)){
            //获取tb任务上级任务
            Map parentTaskInfo = tbClient.queryTaskDetail(parentTaskId, null, null).get(0);
            parentTaskName = UtilMap.getString(parentTaskInfo, "content");

            //获取tb顶级任务
            Map rootTaskInfo = getRootTask(parentTaskId);
            rootTaskName = UtilMap.getString(rootTaskInfo, "content");
        }

        Map result = new HashMap();
        result.put("wtls", wtls);
        result.put("ddUser", ddUser);
        result.put("startDate", startDate);
        result.put("dueDate", dueDate);
        result.put("tfsName", tfsName);
        result.put("parentTaskName", parentTaskName);
        result.put("rootTaskName", rootTaskName);


        return McR.success(result);
    }

    @Override
    public McR updateTaskDelayInfo(Map map) {
        MDC.put("MDC_KEY_PID","1001");

        String formInstId = UtilMap.getString(map, "formInstId");

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstanceId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        String projectId = UtilMap.getString(formData, "textField_mkkrgg8u");//项目id
        String taskId = UtilMap.getString(formData, "textField_mkkrgg8y");//任务id
        long dueDate = UtilMap.getLong(formData, "dateField_mn757w7y");//预计完成时间
        List<String> questionTypes = UtilMap.getList(formData, "checkboxField_mp28uz2w");//任务类型

        Map taskInfo = tbClient.queryTaskDetail(taskId, null, null).get(0);

        List<Map> customfields = UtilMap.getList(taskInfo, "customfields");

        int delayNum = 0;//延期次数

        for (Map customfield : customfields) {
            String cfId = UtilMap.getString(customfield, "cfId");

            switch (cfId){
                case "6941202e92136abe2d9de68f"://问题类型
                    break;
                case "6969da08b9d8a458d706212d"://完成状态
                    break;
                case "6969dc054cd1174e86aa213a"://延期次数
                    List<Map> values = UtilMap.getList(customfield, "value");
                    if (Objects.nonNull(values) && !values.isEmpty()){
                        Map value = values.get(0);
                        delayNum = Integer.parseInt(UtilMap.getString(value, "title"));
                        break;
                    }
            }
        }

        //获取管理员审批人
        String tbOperatorId = tbConf.getOperatorId();

        Map param = new HashMap();
        param.put("appType",ydConf.getAppType());
        param.put("systemToken",ydConf.getSystemToken());
        param.put("userId","yida_pub_account");
        param.put("processInstanceId",formInstId);
        Map jsonMap = (Map) JSONObject.parse(UtilHttp.doGet("https://api.dingtalk.com/v1.0/yida/processes/operationRecords", ddClient.initTokenHeader(), param));
        List<Map> result = UtilMap.getList(jsonMap, "result");
        for (Map map1 : result) {
            String activityId = UtilMap.getString(map1, "activityId");

            //管理员审批节点
            if ("node_ocmouwh06v1".equals(activityId)){
                String operatorUserId = UtilMap.getString(map1, "operatorUserId");

                Map jsonMap2 = (Map) JSONObject.parse(UtilHttp.doGet("https://open.teambition.com/api/idmap/dingtalk/getTbUserId", initHeaderToken(), UtilMap.map("dingUserIds", operatorUserId)));
                List<Map> result2 = UtilMap.getList(jsonMap2, "result");
                if (Objects.nonNull(result2) && !result2.isEmpty()){
                    Map map2 = result2.get(0);
                    tbOperatorId = UtilMap.getString(map2, "tbUserId");
                }
                break;
            }
        }

        //更新任务截止时间

        // 1. 转换为 Instant（UTC 时间点）
        Instant instant = Instant.ofEpochMilli(dueDate);

        // 2.1 转换为 UTC 时间（比上海时间早 8 小时）
        ZonedDateTime utcTime = instant.atZone(ZoneId.of("UTC"));
        DateTimeFormatter utcFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String utcDateTime = utcTime.format(utcFormatter);
        System.out.println("UTC date-time (比上海早8小时): " + utcDateTime); // 输出: 2026-03-20T01:30:00Z

        tbClient.updateTaskDueDate(taskId, utcDateTime, tbOperatorId);

        //更新任务延期次数
        Map body = new HashMap();
        body.put("customfieldId", "6969dc054cd1174e86aa213a");

        Map value = new HashMap();
        value.put("title",delayNum + 1 + "");
        body.put("value",Arrays.asList(value));

        Map map1 = tbClient.updateTaskCustomField(taskId, tbOperatorId, body);

        log.info("map1:{}",JSONObject.toJSONString(map1));

        //更新任务问题类型
        Map body2 = new HashMap();
        body2.put("customfieldId", "6941202e92136abe2d9de68f");
        List<Map> value2 = new ArrayList<>();
        for (String questionType : questionTypes) {
            Map map3 = new HashMap();
            map3.put("title", questionType);
            value2.add(map3);
        }
        body2.put("value",value2);

        Map map2 = tbClient.updateTaskCustomField(taskId, tbOperatorId, body2);

        log.info("map2:{}",JSONObject.toJSONString(map2));

        return McR.success();
    }

    @Override
    public McR updateParentTaskType(Map map) {
        log.info("更新父任务任务类型:{}",JSONObject.toJSONString(map));
        String taskId = UtilMap.getString(map, "taskId");

        Map taskInfo = tbClient.queryTaskDetail(taskId, null, null).get(0);

        String parentTaskId = UtilMap.getString(taskInfo, "parentTaskId");

        if (Strings.isNotBlank(parentTaskId)){
            Map parentTaskInfo = tbClient.queryTaskDetail(parentTaskId, null, null).get(0);

            String projectId = UtilMap.getString(parentTaskInfo, "projectId");
            String sfcId = UtilMap.getString(parentTaskInfo, "sfcId");

            //获取项目任务类型
            List<Map> result = searchProjectSfc(projectId);

            String sfcId2 = "";//任务（企业）
            String sfcId3 = "";//末级任务(企业)

            for (Map resultMap : result) {
                String name = UtilMap.getString(resultMap, "name");
                String id = UtilMap.getString(resultMap, "id");

                switch (name){
                    case "任务企业":sfcId2 = id;break;
                    case "末级任务企业":sfcId3 = id;break;
                    default:break;
                }
            }

            //若父任务任务类型为末级任务（企业），更新为任务（企业）
            if (sfcId.equals(sfcId3)){
                updateTaskSfc(parentTaskId, sfcId2);
            }
        }

        return McR.success();
    }

    @Override
    public void updateLastTaskSfc() {
//        List<String> projectIds = searchProject();
        List<String> projectIds = new ArrayList<String>(){{add("681b19b2ac9fa0e9bfaa186e");}};

        for (String projectId : projectIds) {
//            if (!"68d20eee0e4637c8b70445fc".equals(projectId)) continue;

            String sfcId = "";//末级任务(企业)
            String sfcId2 = "";//任务(企业)

            //获取项目任务类型
            List<Map> result = searchProjectSfc(projectId);
            for (Map resultMap : result) {
                String name = UtilMap.getString(resultMap, "name");
                String id = UtilMap.getString(resultMap, "id");

                switch (name){
                    case "任务（企业）":sfcId2 = id;break;
                    case "末级任务(企业)":sfcId = id;break;
                    default:break;
                }
            }

            //查询项目下所有任务类型为任务（企业）
//            List<Map> taskList = tbClient.queryProjectTaskList(projectId, UtilMap.map("q, pageSize", "taskLayer = exceptTopLevel AND scenarioId = " + sfcId2, 1000), null);
            List<Map> taskList = tbClient.queryProjectTaskList(projectId, UtilMap.map("q, pageSize", "scenarioId = " + sfcId2, 1000), null);

            //遍历所有任务，查询末级任务
            for (Map task : taskList) {
                String taskId = UtilMap.getString(task, "id");

                //查询该任务是否有子任务
                List<Map> sonTaskList = tbClient.queryTaskDetail(null, null, taskId);

                if (sonTaskList.isEmpty()){
                    //更新任务类型为末级任务（企业）
                    updateTaskSfc(taskId, sfcId);
                }
            }




        }
    }

    @Override
    public McR finishTask(Map map) {
        MDC.put("MDC_KEY_PID","1002");

        String formInstId = UtilMap.getString(map, "formInstId");

        Map formData = ydClient.queryData(YDParam.builder()
                .formInstanceId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        String taskId = UtilMap.getString(formData, "textField_mkkrgg8y");
        String projectId = UtilMap.getString(formData, "textField_mkkrgg8u");

        //获取质检员审批人
        String tbOperatorId = tbConf.getOperatorId();

        Map param = new HashMap();
        param.put("appType",ydConf.getAppType());
        param.put("systemToken",ydConf.getSystemToken());
        param.put("userId","yida_pub_account");
        param.put("processInstanceId",formInstId);
        Map jsonMap = (Map) JSONObject.parse(UtilHttp.doGet("https://api.dingtalk.com/v1.0/yida/processes/operationRecords", ddClient.initTokenHeader(), param));
        List<Map> processResult = UtilMap.getList(jsonMap, "result");

        //Q1~Q6上传tb附件
        List<String> activityIds = Arrays.asList("node_ocmq4wx0ihc", "node_ocmq4wz6qf1","node_ocmq4wz6qf2","node_ocmq4wz6qf3","node_ocmq4wz6qf4","node_ocmq4wz6qf5");

        for (Map map1 : processResult) {
            String activityId = UtilMap.getString(map1, "activityId");

            if (activityIds.contains(activityId)){
                String operatorUserId = UtilMap.getString(map1, "operatorUserId");

                Map jsonMap2 = (Map) JSONObject.parse(UtilHttp.doGet("https://open.teambition.com/api/idmap/dingtalk/getTbUserId", initHeaderToken(), UtilMap.map("dingUserIds", operatorUserId)));
                List<Map> result2 = UtilMap.getList(jsonMap2, "result");
                if (Objects.nonNull(result2) && !result2.isEmpty()){
                    Map map2 = result2.get(0);
                    tbOperatorId = UtilMap.getString(map2, "tbUserId");
                }
                break;
            }
        }

        if (Objects.nonNull(formData.get("attachmentField_mpzbe3w8"))){
            List<Map> addValues = new ArrayList<>();

            List<Map> fileList = (List<Map>) JSONArray.parse(String.valueOf(formData.get("attachmentField_mpzbe3w8")));
            for (Map fileMap : fileList) {
                String ydDownloadUrl = fileMap.get("downloadUrl").toString();
                String fileName = fileMap.get("name").toString();

                try {
                    //下载宜搭附件
                    downloadYdFile(ydDownloadUrl, filePath + fileName);
                    System.out.println("文件下载成功！");

                    //TB文件创建文件上传凭证
                    Path path = Paths.get(filePath + fileName);
                    String mimeType = Files.probeContentType(path);
                    System.out.println(mimeType); // application/pdf

                    File file = new File(fileName);
                    long fileSize = file.length();

                    Map body = new HashMap();
                    body.put("scope", "task:"+taskId+"/attachment");
                    body.put("fileSize", fileSize);
                    body.put("fileType", mimeType);
                    body.put("fileName", fileName);
                    body.put("category", "attachment");

                    TBR tbr = (TBR) UtilHttp.doPost("https://open.teambition.com/api/v3/awos/upload-token", initHeaderToken(), null, body, TBR.class);
                    Map result = (Map) tbr.getResult();
                    String uploadUrl = UtilMap.getString(result, "uploadUrl");
                    String token = UtilMap.getString(result, "token");

                    //上传文件
                    uploadFile(filePath + fileName, uploadUrl, mimeType);

                    Map value = new HashMap();
                    value.put("title",fileName);
                    value.put("metaString",JSONObject.toJSONString(UtilMap.map("fileToken",token)));

                    addValues.add(value);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //更新tb任务附件
            Map body = new HashMap();
            body.put("customfieldId", "67e372b0142aea12588c2d22");
            body.put("addValues",addValues);

            Map map2 = tbClient.updateTaskCustomField(taskId, tbOperatorId, body);
            log.info("map2:{}",JSONObject.toJSONString(map2));

            //查询任务所在工作流的任务状态列表
            TBR tbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/task/" + taskId + "/tfs", initHeaderToken(), null, TBR.class);

            List<Map> tfsList = (List<Map>) tbr.getResult();

            for (Map tfsMap : tfsList) {
                String tfsName = UtilMap.getString(tfsMap, "name");

                if ("已完成".equals(tfsName)){
                    String tfsId = UtilMap.getString(tfsMap, "id");
                    //完成tb任务
                    tbClient.updateTaskFlowStatus(taskId, tbOperatorId, tfsId,null);
                }
            }
        }

        return McR.success();
    }

    @Override
    public McR getProjectInfo(String projectId) {
        List<Map> results = tbClient.projectDetail(projectId, null, null);

        Map result = (Map) results.get(0);

        Map map = new HashMap();

        List<Map> customfields = UtilMap.getList(result, "customfields");

        for (Map customfield : customfields) {
            String customfieldId = UtilMap.getString(customfield, "customfieldId");

            //项目号
            if ("6805ecf00763b2e708d760bc".equals(customfieldId)){
                List<Map> values = UtilMap.getList(customfield, "value");

                Map value = values.get(0);

                String title = UtilMap.getString(value, "title");

                map.put("projectNo",title);
            }
        }

        return McR.success(map);
    }

    /**
     * 上传文件（核心方法）
     * @param filePath 本地文件路径（如"2.png"）
     * @param uploadUrl 接口地址（如Postman中的PUT URL）
     * @param contentType 文件类型（如"image/png"，可留空由服务端自动识别）
     * @return 服务端响应内容
     */
    public static String uploadFile(String filePath, String uploadUrl, String contentType) throws IOException {
        File file = new File(filePath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在：" + filePath);
        }

        // 1. 创建URL并打开连接
        URL url = new URL(uploadUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        try {
            // 2. 配置请求属性（必须为PUT，允许写入请求体）
            conn.setRequestMethod("PUT");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setConnectTimeout(30000); // 连接超时30秒
            conn.setReadTimeout(30000);    // 读取超时30秒

            // 3. 设置请求头（关键：Content-Type需与文件类型匹配）
//            if (contentType != null && !contentType.isEmpty()) {
//                conn.setRequestProperty("Content-Type", contentType);
//            }
            // 可选：添加其他头信息（如鉴权Token）
            // conn.setRequestProperty("Authorization", "Bearer your_token");

            // 4. 读取文件并写入请求体（分块读取，避免大文件内存溢出）
            try (FileInputStream fis = new FileInputStream(file);
                 OutputStream os = conn.getOutputStream()) {

                byte[] buffer = new byte[4096]; // 4KB缓冲区
                int bytesRead;
                long totalBytes = 0;

                while ((bytesRead = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                    totalBytes += bytesRead;
                    // 可选：打印上传进度（每1MB打印一次）
                    if (totalBytes % (1024 * 1024) == 0) {
                        System.out.println("已上传：" + (totalBytes / (1024 * 1024)) + " MB");
                    }
                }
            }

            // 5. 获取响应码并读取响应内容
            int responseCode = conn.getResponseCode();
            System.out.println("响应码：" + responseCode);

            // 读取响应内容（服务端返回的数据）
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            }

        } finally {
            // 6. 断开连接（确保资源释放）
            conn.disconnect();
        }
    }

    //下载宜搭附件
    private void downloadYdFile(String fileURL, String savePath) throws IOException {
        //若是宜搭附件url 则需获得附件临时免登地址
        fileURL = ydClient.convertTemporaryUrl(fileURL);

        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // 检查HTTP响应代码是否为200
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = httpConn.getInputStream();
            FileOutputStream outputStream = new FileOutputStream(savePath);

            byte[] buffer = new byte[4096];
            int bytesRead = -1;

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();
        } else {
            System.out.println("无法下载文件。HTTP响应代码: " + responseCode);
        }
        httpConn.disconnect();
    }

    private Map getRootTask(String taskId) {
        Map taskInfo = tbClient.queryTaskDetail(taskId, null, null).get(0);

        String parentTaskId = UtilMap.getString(taskInfo, "parentTaskId");

        if (Strings.isNotBlank(parentTaskId)){
            return getRootTask(parentTaskId);
        }else {
            return taskInfo;
        }
    }

    //转换时区并返回时间戳
    private static Long extracted(String dateStr) {
        if (Strings.isNotBlank(dateStr)){
            // 1. 解析为 Instant（UTC 时间）
            Instant instant = Instant.parse(dateStr);

            // 2. 转换为目标时区（Asia/Shanghai, UTC+8）
            ZoneId shanghaiZone = ZoneId.of("Asia/Shanghai");
            ZonedDateTime shanghaiTime = instant.atZone(shanghaiZone);

            // 3. 转换为时间戳（毫秒）
            long timestamp = shanghaiTime.toInstant().toEpochMilli();

            // 输出结果
            System.out.println("UTC 时间: " + instant);
            System.out.println("上海时间: " + shanghaiTime);
            System.out.println("时间戳（毫秒）: " + timestamp);

            return timestamp;
        }else {
            return null;
        }

    }

    private static final Long EXPIRES_IN = 7200000L;

    private String getAccessToken() {
            String accessToken = UtilToken.get("invalid-token-teambition");
            if (StringUtils.isNotBlank(accessToken)) {
                return accessToken;
            } else {
                Algorithm algorithm = Algorithm.HMAC256(tbConf.getAppSecret());
                long timestamp = System.currentTimeMillis();
                Date issuedAt = new Date(timestamp);
                Date expiresAt = new Date(timestamp + EXPIRES_IN);
                accessToken = JWT.create().withClaim("_appId", tbConf.getAppID()).withIssuedAt(issuedAt).withExpiresAt(expiresAt).sign(algorithm);
                log.info("响应token, {}", accessToken);
                UtilToken.put("invalid-token-teambition", accessToken, EXPIRES_IN);
                return accessToken;
            }

    }

    private Map<String, String> initHeaderToken() {
        Map header = new HashMap();
        header.put("Authorization", getAccessToken());
        header.put("X-Tenant-Id", tbConf.getTenantId());
        header.put("X-Tenant-Type", "organization");
        header.put("X-Operator-Id", tbConf.getOperatorId());

        return header;
    }

    // 操作者ID: 若是查询, 以操作人视角作为权限
    private Map<String, String> initHeaderToken(String operatorId) {
        Map header = initHeaderToken();
        header.put("x-operator-id", operatorId);
        return header;
    }

    //搜索项目任务类型
    private List<Map> searchProjectSfc(String projectId) {
        String s = UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/scenariofieldconfig/search", initHeaderToken(), UtilMap.map("objectTypes", "task"));
        Map result = (Map) JSONObject.parse(s);

        log.info("result：{}",result);

        List<Map> list = UtilMap.getList(result, "result");

        return list;
    }

    //更新任务的任务类型
    private Map updateTaskSfc(String taskId, String sfcId) {
        String s = UtilHttp.doPut("https://open.teambition.com/api/v3/task/" + taskId + "/sfc/update", initHeaderToken(tbConf.getOperatorId()), null, UtilMap.map("sfcId", sfcId));

        Map result = (Map) JSONObject.parse(s);

        log.info("result：{}",result);

        return result;
    }

    //通过TQL搜索项目
    private List<String> searchProject() {
        String s = UtilHttp.doGet("https://open.teambition.com/api/project/search", initHeaderToken(tbConf.getOperatorId()), UtilMap.map("pageSize", 100));

        Map result = (Map) JSONObject.parse(s);

        log.info("result:{}",result);

        List<String> list = UtilMap.getList(result, "result");

        return list;
    }
}
