package com.malk.lingmingguangzi.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.malk.lingmingguangzi.utils.SkipHttpsUtil;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.server.teambition.TBConf;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;
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.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class LingmingguangziServiceImpl implements LingmingguangziService {
    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDConf ydConf;

    @Autowired
    private TBConf tbConf;

    @Autowired
    private DDClient ddClient;

    @Autowired
    private YDService ydService;

    @Value(value = "${teambition.TemplateId}")
    private String templateId;

    @Value(value = "${erp_sz.url}")
    private String erpUrlSz;

    @Value(value = "${erp_sz.username}")
    private String userNameSz;

    @Value(value = "${erp_sz.password}")
    private String passwordSz;

    @Value(value = "${erp_sz.filePath}")
    private String filePathSz;

    @Value(value = "${erp_xg.url}")
    private String erpUrlXg;

    @Value(value = "${erp_xg.username}")
    private String userNameXg;

    @Value(value = "${erp_xg.password}")
    private String passwordXg;

    @Value(value = "${erp_xg.filePath}")
    private String filePathXg;

    @Value(value = "${erp_zj.url}")
    private String erpUrlZj;

    @Value(value = "${erp_zj.username}")
    private String userNameZj;

    @Value(value = "${erp_zj.password}")
    private String passwordZj;

    @Value(value = "${erp_zj.filePath}")
    private String filePathZj;

    @Value(value = "${erp_hz.url}")
    private String erpUrlHz;

    @Value(value = "${erp_hz.username}")
    private String userNameHz;

    @Value(value = "${erp_hz.password}")
    private String passwordHz;

    @Value(value = "${erp_hz.filePath}")
    private String filePathHz;

    private final Object $lock = new Object[0];

    private static final Long EXPIRES_IN = 7200000L;

    private static final String TASK_URL_PREFIX = "https://www.teambition.com/task/";

    private static final List<String> STAGES = new ArrayList<>();

    static {
        STAGES.add("TR/TO阶段");
        STAGES.add("EV产品开发验证");
        STAGES.add("DV过程开发验证");
        STAGES.add("PV量产爬坡验证");
        STAGES.add("MP大批量生产");
    }

    @Override
    public McR test() {
        log.info("test");
        Map map = new HashMap();
        String aaa = map.get("aaa").toString();
        return McR.success();
    }

    @Override
    public McR getCustomerQuestionnaireCount(Long start, Long end) {
        YDParam.YDParamBuilder ydParamBuilder = YDParam.builder()
                .formUuid("FORM-5CC9748D283C49FC8C8A86EE0529730A4I1D");

        if (start != null && end != null){
            String startDate = DateUtil.format(new Date(start), "yyyy-MM-dd HH:mm:ss");
            String endDate = DateUtil.format(DateUtil.offsetDay(new Date(end),1), "yyyy-MM-dd HH:mm:ss");

            ydParamBuilder.createFromTimeGMT(startDate);
            ydParamBuilder.createToTimeGMT(endDate);
        }

        //车载--------------------------------------------
        DDR_New ddrNew = ydClient.queryData(ydParamBuilder.build(), YDConf.FORM_QUERY.retrieve_list);
        List<Map> dataList = (List<Map>) ddrNew.getData();
        int importantCustomerCount = 0;
        int orderCustomerCount = 0;
        int strategicCustomerCount = 0;

        for (Map data : dataList) {
            Map formData = (Map) data.get("formData");
            String customerLevel = String.valueOf(formData.get("selectField_lx4g7em6"));
            switch (customerLevel){
                case "重要客户": importantCustomerCount++; break;
                case "普通客户": orderCustomerCount++; break;
                case "战略客户": strategicCustomerCount++; break;
            }
        }

        Map<String,Integer> result = new HashMap<>();
        result.put("importantCustomerCount", importantCustomerCount);
        result.put("orderCustomerCount", orderCustomerCount);
        result.put("strategicCustomerCount", strategicCustomerCount);

        return McR.success(result);
    }

    @Override
    public McR getCustomerQuestionnaireCount2(Long start, Long end) {
        YDParam.YDParamBuilder ydParamBuilder = YDParam.builder()
                .formUuid("FORM-D4587ABF101246F6B17635C8CB178B6BGTAW");

        if (start != null && end != null){
            String startDate = DateUtil.format(new Date(start), "yyyy-MM-dd HH:mm:ss");
            String endDate = DateUtil.format(DateUtil.offsetDay(new Date(end),1), "yyyy-MM-dd HH:mm:ss");

            ydParamBuilder.createFromTimeGMT(startDate);
            ydParamBuilder.createToTimeGMT(endDate);
        }
        //商务端
        DDR_New ddrNew = ydClient.queryData(ydParamBuilder.build(), YDConf.FORM_QUERY.retrieve_list);
        List<Map> dataList = (List<Map>) ddrNew.getData();
        int businessCustomerCount = 0;
        int technologyCustomerCount = 0;
        int qualityCustomerCount = 0;
        for (Map data : dataList) {
            Map formData = (Map) data.get("formData");
            String project = formData.get("selectField_lwragwwz").toString();//项目
            switch (project) {
                case "交付":businessCustomerCount++;break;
                case "技术":technologyCustomerCount++;break;
                case "质量":qualityCustomerCount++;break;
            }
        }

        Map<String,Integer> result = new HashMap<>();
        result.put("businessCustomerCount",businessCustomerCount);
        result.put("technologyCustomerCount",technologyCustomerCount);
        result.put("qualityCustomerCount",qualityCustomerCount);

        return McR.success(result);
    }

    @Override
    public McR addCustomer(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();

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

        Map<String,Object> body = new HashMap<>();

        //查询erp账号
        Map originator = ddrNew.getOriginator();
        String userId = originator.get("userId").toString();
        List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-65789BACB6F64B2C880875260026A6EACTOB")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m0ypgxec", userId)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();
        if (!data.isEmpty()){
            Map formData2 = (Map) data.get(0).get("formData");
            body.put("createBy", formData2.get("textField_m0ypgxeb").toString());
        }

        body.put("customerCode", formData.get("textField_lwpqbm7a").toString());
        body.put("customerName", formData.get("textField_lwpqbm7b").toString());

        body.put("recConditionCode", formData.get("textField_m3o22635").toString());

        body.put("payCurrencyCode", formData.get("textField_m0yq620t").toString());

        //客户简称
        if (Objects.nonNull(formData.get("textField_lwpqbm7c"))){
            body.put("customerShortName", formData.get("textField_lwpqbm7c").toString());
        }
        //客户英文名
        if (Objects.nonNull(formData.get("textField_lwpqbm7d"))){
            body.put("customerEnglishName", formData.get("textField_lwpqbm7d").toString());
        }
        //地址
        if (Objects.nonNull(formData.get("textField_lwpqbm7t"))){
            body.put("address", formData.get("textField_lwpqbm7t").toString());
        }
        //联系人
        if (Objects.nonNull(formData.get("textField_lwpqbm7u"))){
            body.put("linkMan", formData.get("textField_lwpqbm7u").toString());
        }
        //联系电话
        if (Objects.nonNull(formData.get("textField_lwpqbm7v"))){
            body.put("linkNumber", formData.get("textField_lwpqbm7v").toString());
        }
        //内/外销
        if (Objects.nonNull(formData.get("selectField_lwpqbm82"))){
            String makCustomerType = formData.get("selectField_lwpqbm82").toString();
            switch (makCustomerType){
                case "内销": body.put("makCustomerType", "001");break;
                case "外销":body.put("makCustomerType", "002");break;
            }
        }
        //备注
        if (Objects.nonNull(formData.get("textareaField_lwpqbm7x"))){
            body.put("comments", formData.get("textareaField_lwpqbm7x").toString());
        }
        //erp环境
        String type = formData.get("selectField_m3fgkfz9_id").toString();
        String erpUrl = getErpUrl(type);

        Map<String, Object> result = post(erpUrl + "pws/mak/makCustomer/add", null, getHeader(type), body);

        if ((boolean) result.get("success")){
            return McR.success();
        }else {
            return McR.errorUnknown(result.get("message").toString());
        }
    }

    private String getErpUrl(String type) {
        String erpUrl = "";
        if ("深圳".equals(type)){
            erpUrl = erpUrlSz;
        }else if ("香港".equals(type)){
            erpUrl = erpUrlXg;
        }else if ("浙江".equals(type)){
            erpUrl = erpUrlZj;
        }else if ("杭州".equals(type)){
            erpUrl = erpUrlHz;
        }
        return erpUrl;
    }

    @Override
    public McR updateCustomer(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();

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

        Map<String,Object> body = new HashMap<>();

        //查询erp账号
        Map originator = ddrNew.getOriginator();
        String userId = originator.get("userId").toString();
        List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-65789BACB6F64B2C880875260026A6EACTOB")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m0ypgxec", userId)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();
        if (!data.isEmpty()){
            Map formData2 = (Map) data.get(0).get("formData");
            body.put("updateBy", formData2.get("textField_m0ypgxeb").toString());
        }

        body.put("customerCode", formData.get("textField_lwpqbm7a").toString());
        body.put("customerName", formData.get("textField_lwpqbm7b").toString());
        body.put("recConditionCode", formData.get("textField_m3o22635").toString());
        body.put("payCurrencyCode", formData.get("textField_m0yq620t").toString());

        //客户简称
        if (Objects.nonNull(formData.get("textField_lwpqbm7c"))){
            body.put("customerShortName", formData.get("textField_lwpqbm7c").toString());
        }
        //客户英文名
        if (Objects.nonNull(formData.get("textField_lwpqbm7d"))){
            body.put("customerEnglishName", formData.get("textField_lwpqbm7d").toString());
        }
        //地址
        if (Objects.nonNull(formData.get("textField_lwpqbm7t"))){
            body.put("address", formData.get("textField_lwpqbm7t").toString());
        }
        //联系人
        if (Objects.nonNull(formData.get("textField_lwpqbm7u"))){
            body.put("linkMan", formData.get("textField_lwpqbm7u").toString());
        }
        //联系电话
        if (Objects.nonNull(formData.get("textField_lwpqbm7v"))){
            body.put("linkNumber", formData.get("textField_lwpqbm7v").toString());
        }
        //内/外销
        if (Objects.nonNull(formData.get("selectField_lwpqbm82"))){
            String makCustomerType = formData.get("selectField_lwpqbm82").toString();
            switch (makCustomerType){
                case "001": body.put("makCustomerType", "001");break;
                case "002":body.put("makCustomerType", "002");break;
            }
        }
        //备注
        if (Objects.nonNull(formData.get("textareaField_lwpqbm7x"))){
            body.put("comments", formData.get("textareaField_lwpqbm7x").toString());
        }

        //erp环境
        String type = formData.get("selectField_m3fgkfz9_id").toString();

        Map<String, Object> result = put(getErpUrl(type) + "pws/mak/makCustomer/customEdit", null, getHeader(type), body);
        if ((boolean) result.get("success")){
            return McR.success();
        }else {
            return McR.errorUnknown(result.get("message").toString());
        }
    }

    @Override
    public McR getProductDeliveryStatus(String keyword,int pageNo,int pageSize,String type) {
        Map<String,Object> param = new HashMap<>();

        //物料编码
        param.put("pageNo",pageNo);
        param.put("pageSize",pageSize);
        param.put("partnumber",keyword);
        Map<String,Object> res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
        Map result = (Map) res.get("result");
        List<Map> data = (List<Map>) result.get("records");

        if (data.isEmpty()){
            //物料名称
            param.remove("partnumber");
            param.put("partname",keyword);
            res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
            result = (Map) res.get("result");
            data = (List<Map>) result.get("records");
        }

        if (data.isEmpty()){
            //物料型号
            param.remove("partname");
            param.put("pmodel",keyword);
            res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
            result = (Map) res.get("result");
            data = (List<Map>) result.get("records");
        }

        if (data.isEmpty()){
            //物料规格
            param.remove("pmodel");
            param.put("pstandard",keyword);
            res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
            result = (Map) res.get("result");
            data = (List<Map>) result.get("records");
        }

        if (data.isEmpty()){
            //客户型号
            param.remove("pstandard");
            param.put("customerModel",keyword);
            res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
            result = (Map) res.get("result");
            data = (List<Map>) result.get("records");
        }

        //交付名称
        if (data.isEmpty()){
            param.remove("customerModel");
            param.put("saleCode",keyword);
            res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
            result = (Map) res.get("result");
            data = (List<Map>) result.get("records");
        }

        //交付说明
        if (data.isEmpty()){
            param.remove("saleCode");
            param.put("saleName",keyword);
            res = get(getErpUrl(type) + "pws/pdm/pdmProductForm/list", param, getHeader(type));
            result = (Map) res.get("result");
            data = (List<Map>) result.get("records");
        }



        int totalCount = (int) result.get("total");
        int currentPage = (int) result.get("current");

        Map map = new HashMap();
        map.put("data",data);
        map.put("totalCount",totalCount);
        map.put("currentPage",currentPage);

        return McR.success(map);
    }

    @Override
    public McR addSaleOrder(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();
        DDR_New ddrNew = ydClient.queryData(YDParam.builder().formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);

        Map formData = ddrNew.getFormData();

        //erp环境
        String type = formData.get("selectField_m3fgkfz9_id").toString();

        //新增销售订单
        Map body = new HashMap();

        //查询erp账号
        Map originator = ddrNew.getOriginator();
        String userId = originator.get("userId").toString();
        List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-65789BACB6F64B2C880875260026A6EACTOB")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m0ypgxec", userId)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();
        if (!data.isEmpty()){
            Map formData2 = (Map) data.get(0).get("formData");
            body.put("createBy", formData2.get("textField_m0ypgxeb").toString());
        }

        body.put("customerCode",getString(formData.get("textField_ly5m36nw")));//客户编码
        String priority = getString(formData.get("selectField_lwpsp162"));//紧急级别
        switch (priority) {
            case "普通": body.put("priority", "D1_NORMAL "); break;
            case "紧急": body.put("priority", "D2_URGENT"); break;
            case "特紧急": body.put("priority", "D3_VERY_URGENT"); break;
        }
        String soType = getString(formData.get("selectField_lx2xj36n"));//合同类型
        if ("预测订单".equals(soType)){
            body.put("soType", "D2_FORECAST_ORDER");
        }else {
            body.put("soType", "D1_SALES_ORDER");
        }
        /*switch (soType) {
            case "常规订单":
            case "特殊订单":
            case "定制协议":
            case "采购框架":
            case "质量协议":
            case "demo/测试板/硬件":
            case "战略合作协议": body.put("soType", "D1_SALES_ORDER"); break;
            case "预测订单": body.put("soType", "D2_FORECAST_ORDER"); break;
            default: body.put("soType", "D1_SALES_ORDER"); break;
        }*/
        body.put("deliveryDate",getString(formData.get("textField_m0aduyx1")));//希望交期
        body.put("salesperson",getString(formData.get("textField_m0aduyx9")));//销售员
        body.put("payCurrencyCode",getString(formData.get("textField_m0aduyxa")));//币别
        body.put("ioDate",getString(formData.get("textField_m0aduyx2")));//单据日期
        body.put("comments",getString(formData.get("textareaField_lwpsp16e")));//备注
        //销售订单明细
        List<Map> list = (List<Map>) formData.get("tableField_lwpsp16f");
        List<Map> makSoDetailList = list.stream().map(map1 -> {
            Map detail = new HashMap();
            detail.put("productFormId",getString(map1.get("textField_m03o1x0m")));//交付状态id
            detail.put("saleCode",getString(map1.get("textField_lwpsp16g")));//交付名称
            detail.put("saleName",getString(map1.get("textField_lwpsp16h")));//交付说明
            detail.put("customerModel",getString(map1.get("textField_lwpsp16i")));//客户型号
            detail.put("partnumber",getString(map1.get("textField_lwpsp16k")));//物料编码
            detail.put("partname",getString(map1.get("textField_lwpsp16m")));//物料名称
            detail.put("pmodel",getString(map1.get("textField_lwpsp16o")));//物料型号
            detail.put("pstandard",getString(map1.get("textField_lwpsp16q")));//物料规格
            detail.put("stationCode",getString(map1.get("textField_m053iuol")));//工序编码
            detail.put("waferQty",getString(map1.get("numberField_lwpsp16t")));//片数
            detail.put("qty",getString(map1.get("numberField_lwpsp16v")));//数量
            detail.put("quotation",getString(map1.get("numberField_lwpsp172")));//未税单价
            detail.put("subTotal",getString(map1.get("numberField_lwpz9exp")));//未税总价
            detail.put("taxRate",getString(map1.get("numberField_m053iuom")));//税率
            detail.put("taxQuotation",getString(map1.get("numberField_lwpsp175")));//含税单价
            detail.put("taxSubtotal",getString(map1.get("numberField_lwpsp177")));//含税总价
            detail.put("die_model","");//
            return detail;
        }).collect(Collectors.toList());
        //附件  20250413 附件过大可能上传超时 暂时不推送erp
        /*List<Map> list2 = (List<Map>) formData.get("tableField_ly8fxusx");

        String[] ERP_FILEPATHS = new String[]{filePathSz,filePathXg,filePathZj,filePathHz};
        String[] ERP_ENVS = new String[]{"深圳","香港","浙江","杭州"};

        if (Objects.nonNull(list2)){
            List<Map> makSoFilesList = list2.stream().map(map1 -> {
                Map detail = new HashMap();
                String fileType = getString(map1.get("selectField_m0ls7yb8"));
                if (fileType.equals("合同")){
                    detail.put("fileType","D1_CONTRACT");
                }else {
                    detail.put("fileType","D2_TECHNICAL_DOC");
                }
                List<Map> fileList = (List<Map>) JSONArray.parse(String.valueOf(map1.get("attachmentField_ly8fxusz")));
                String ydDownloadUrl = fileList.get(0).get("downloadUrl").toString();
                String fileName = fileList.get(0).get("name").toString();

                fileName = DigestUtils.sha256Hex(fileName.substring(fileName.lastIndexOf(".")+1)) + fileName.substring(fileName.lastIndexOf("."));
//                fileName = convertChineseToUtf8Hex(fileName);

                for (int i = 0; i < ERP_ENVS.length; i++) {
                    if (ERP_ENVS[i].equals(type)){
                        //将downloadurl下载到本地
                        try {
                            downloadFile(ydDownloadUrl, ERP_FILEPATHS[i],fileName);
                            System.out.println("文件下载成功！");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //上传附件
                        try {
                            detail.put("files",postWithFile(getErpUrl(type) + "pws/sys/common/upload", ERP_FILEPATHS[i] + fileName,type));
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }

                        break;
                    }
                }
                if ("深圳".equals(type)){
                    //将downloadurl下载到本地
                    try {
                        downloadFile(ydDownloadUrl, filePathSz,fileName);
                        System.out.println("文件下载成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //上传附件
                    try {
                        detail.put("files",postWithFile(getErpUrl(type) + "pws/sys/common/upload", filePathSz + fileName,type));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }else if ("香港".equals(type)){
                    //将downloadurl下载到本地
                    try {
                        downloadFile(ydDownloadUrl, filePathXg,fileName);
                        System.out.println("文件下载成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //上传附件
                    try {
                        detail.put("files",postWithFile(getErpUrl(type) + "pws/sys/common/upload", filePathXg + fileName,type));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }else if ("浙江".equals(type)){
                    //将downloadurl下载到本地
                    try {
                        downloadFile(ydDownloadUrl, filePathZj,fileName);
                        System.out.println("文件下载成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //上传附件
                    try {
                        detail.put("files",postWithFile(getErpUrl(type) + "pws/sys/common/upload", filePathZj + fileName,type));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }

                return detail;
            }).collect(Collectors.toList());
            body.put("makSoFilesList",makSoFilesList);
        }*/
        body.put("makSoDetailList",makSoDetailList);


        Map res = post(getErpUrl(type) + "pws/mak/makSalesOrder/add", null, getHeader(type), body);

        if (!(boolean)res.get("success")){
            return McR.errorUnknown(getString(res.get("message")));
        }

        String orderCode = getString(res.get("result"));
        //更新宜搭订单编号
        ydClient.operateData(YDParam.builder()
                .formInstId(formInstId)
                .updateFormDataJson(JSON.toJSONString(UtilMap.map("textField_m0alsjj1",orderCode)))
                .build(),YDConf.FORM_OPERATION.update);

        //如果是变更订单 则更新原订单
        String orderType = getString(formData.get("selectField_m3ii047l"));
        if ("变更订单".equals(orderType)){
            String jsonString = formData.get("associationFormField_m3ii047m_id").toString();
            String orderJsonString = StringEscapeUtils.unescapeJava(jsonString.substring(1, jsonString.length() - 1));
            List<Map> order =(List<Map>) JSONArray.parse(orderJsonString);

            String updateFormInstId = order.get(0).get("instanceId").toString();

            order.get(0).put("instanceId",formInstId);
            order.get(0).put("title",orderCode);

            Map updateMap = new HashMap();
            updateMap.put("associationFormField_m3ii047n",JSON.toJSONString(order));
            ydClient.operateData(YDParam.builder()
                    .formInstId(updateFormInstId)
                    .updateFormDataJson(JSON.toJSONString(updateMap))
                    .build(),YDConf.FORM_OPERATION.update);
        }

        return McR.success();
    }

    public void downloadFile(String fileURL, String savePath , String fileName) throws IOException {
        //若是宜搭附件url 则需获得附件临时免登地址
        Map<String,Object> param = new HashMap<>();
        param.put("systemToken",ydConf.getSystemToken());
        param.put("userId","344749020127590108");//wzy
        param.put("fileUrl",fileURL);
        param.put("timeout",3600000);

        Map mcBody = new HashMap();
        mcBody.put("params",param);
        mcBody.put("headers",ddClient.initTokenHeader());
        mcBody.put("url","https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/" + ydConf.getAppType());
        mcBody.put("fileName",fileName);
        mcBody.put("downloadPath","/home/mc/mjs/lingmingguangzi/");
//        mcBody.put("downloadPath","d:\\");

        fileURL = UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/downloadFile",null,null,mcBody);
//        fileURL = UtilHttp.doPost("http://127.0.0.1:9900/api/mc/request/downloadFile",null,null,mcBody);

//        fileURL = ((DDR_New) UtilHttp.doGet("https://api.dingtalk.com/v1.0/yida/apps/temporaryUrls/" + ydConf.getAppType(), ddClient.initTokenHeader(), param, DDR_New.class)).getResult().toString();
        log.info("fileUrl:{}",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 + fileName);

            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();
    }

    @Override
    public McR updateClueStatus(Map map) {
        String formInstId = getString(map.get("formInstId"));

       if (!Strings.isNullOrEmpty(formInstId)) {
           Map formData = ydClient.queryData(YDParam.builder()
                   .formInstId(formInstId)
                   .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

           String customerName = getString(formData.get("textField_lwpqbm7b"));
           String customerCode = getString(formData.get("serialNumberField_m4rv2j4i"));

           List<Map> clueList = (List<Map>) formData.get("tableField_m86r3mmn");
           if (Objects.nonNull(clueList) && !clueList.isEmpty()){
               for (Map clue : clueList) {
                   String clueCode = getString(clue.get("textField_m86r3mmo"));

                   //客户资源池关联表单
                   List<Map> formControlList = new ArrayList<>();
                   Map formControl = new HashMap();
                   formControl.put("formType","receipt");
                   formControl.put("formUuid","FORM-6F1E2DCFB3F5448EBDD4994551EBF690DVIT");
                   formControl.put("instanceId",formInstId);
                   formControl.put("appType","APP_MOIYIC856NRIBCMXEXVD");
                   formControl.put("title",customerName);
                   formControlList.add(formControl);

                   Map updateFormData = new HashMap();
                   updateFormData.put("associationFormField_m50t9d7y",formControlList);
                   updateFormData.put("selectField_m2lh8c49","已转换");
                   updateFormData.put("textField_m50vl2jt",customerCode);

                   //更新线索
                   ydClient.operateData(YDParam.builder()
                           .formUuid("FORM-45C086AFF2F94D9BB056A15B34CD2BCAFQET")
                           .searchCondition(JSONObject.toJSONString(UtilMap.map("serialNumberField_m2mwp0iy",clueCode)))
                           .formDataJson(JSONObject.toJSONString(updateFormData))
                           .build(), YDConf.FORM_OPERATION.upsert);
               }
           }



       }else {
           McR.errorParam("formInstId不能为空");
       }
       return McR.success();
    }

/*    @Override
    public McR updateSaleOrder(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();
        DDR_New ddrNew = ydClient.queryData(YDParam.builder().formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);

        Map formData = ddrNew.getFormData();

        //erp环境
        String type = formData.get("selectField_m3fgkfz9").toString();

        //更新销售订单
        Map body = new HashMap();

        //查询erp账号
        Map originator = ddrNew.getOriginator();
        String userId = originator.get("userId").toString();
        List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-65789BACB6F64B2C880875260026A6EACTOB")
                .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_m0ypgxec", userId)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();
        if (!data.isEmpty()){
            Map formData2 = (Map) data.get(0).get("formData");
            body.put("updateBy", formData2.get("textField_m0ypgxeb").toString());
        }

        body.put("soCode",getString(formData.get("textField_m0alsjj1")));
        body.put("customerCode",getString(formData.get("textField_ly5m36nw")));//客户编码
        String priority = getString(formData.get("selectField_lwpsp162"));//紧急级别
        switch (priority) {
            case "普通": body.put("priority", "D1_NORMAL "); break;
            case "紧急": body.put("priority", "D2_URGENT"); break;
            case "特紧急": body.put("priority", "D3_VERY_URGENT"); break;
        }
        String soType = getString(formData.get("selectField_lx2xj36n"));//合同类型
        switch (soType) {
            case "常规订单":
            case "特殊订单":
            case "定制协议":
            case "采购框架":
            case "质量协议":
            case "战略合作协议": body.put("soType", "D1_SALES_ORDER"); break;
            case "预测订单": body.put("soType", "D2_FORECAST_ORDER"); break;
            default: body.put("soType", "D1_SALES_ORDER"); break;
        }
        body.put("deliveryDate",getString(formData.get("textField_m0aduyx1")));//希望交期
        body.put("salesperson",getString(formData.get("textField_m0aduyx9")));//销售员
        body.put("payCurrencyCode",getString(formData.get("textField_m0aduyxa")));//币别
        body.put("ioDate",getString(formData.get("textField_m0aduyx2")));//单据日期
        body.put("comments",getString(formData.get("textareaField_lwpsp16e")));//备注
        //销售订单明细
        List<Map> list = (List<Map>) formData.get("tableField_lwpsp16f");
        List<Map> makSoDetailList = list.stream().map(map1 -> {
            Map detail = new HashMap();
            detail.put("productFormId",getString(map1.get("textField_m03o1x0m")));//交付状态id
            detail.put("saleCode",getString(map1.get("textField_lwpsp16g")));//交付名称
            detail.put("saleName",getString(map1.get("textField_lwpsp16h")));//交付说明
            detail.put("customerModel",getString(map1.get("textField_lwpsp16i")));//客户型号
            detail.put("partnumber",getString(map1.get("textField_lwpsp16k")));//物料编码
            detail.put("partname",getString(map1.get("textField_lwpsp16m")));//物料名称
            detail.put("pmodel",getString(map1.get("textField_lwpsp16o")));//物料型号
            detail.put("pstandard",getString(map1.get("textField_lwpsp16q")));//物料规格
            detail.put("stationCode",getString(map1.get("textField_m053iuol")));//工序编码
            detail.put("waferQty",getString(map1.get("numberField_lwpsp16t")));//片数
            detail.put("qty",getString(map1.get("numberField_lwpsp16v")));//数量
            detail.put("quotation",getString(map1.get("numberField_lwpsp172")));//未税单价
            detail.put("subTotal",getString(map1.get("numberField_lwpz9exp")));//未税总价
            detail.put("taxRate",getString(map1.get("numberField_m053iuom")));//税率
            detail.put("taxQuotation",getString(map1.get("numberField_lwpsp175")));//含税单价
            detail.put("taxSubtotal",getString(map1.get("numberField_lwpsp177")));//含税总价
            detail.put("die_model","");//
            return detail;
        }).collect(Collectors.toList());
        //附件
        List<Map> list2 = (List<Map>) formData.get("tableField_ly8fxusx");
        if (Objects.nonNull(list2)){
            List<Map> makSoFilesList = list2.stream().map(map1 -> {
                Map detail = new HashMap();
                String fileType = getString(map1.get("selectField_m0ls7yb8"));
                if (fileType.equals("合同")){
                    detail.put("fileType","D1_CONTRACT");
                }else {
                    detail.put("fileType","D2_TECHNICAL_DOC");
                }
                List<Map> fileList = (List<Map>) JSONArray.parse(String.valueOf(map1.get("attachmentField_ly8fxusz")));
                String ydDownloadUrl = fileList.get(0).get("downloadUrl").toString();
                String fileName = fileList.get(0).get("name").toString();
                if ("深圳".equals(type)){
                    //将downloadurl下载到本地
                    try {
                        downloadFile(ydDownloadUrl, filePathSz + fileName);
                        System.out.println("文件下载成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //上传附件
                    detail.put("files",postWithFile(getErpUrl(type) + "pws/sys/common/upload", filePathSz + fileName,type));
                }else {
                    //将downloadurl下载到本地
                    try {
                        downloadFile(ydDownloadUrl, filePathXg + fileName);
                        System.out.println("文件下载成功！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //上传附件
                    detail.put("files",postWithFile(getErpUrl(type) + "pws/sys/common/upload", filePathXg + fileName,type));
                }
                return detail;
            }).collect(Collectors.toList());
            body.put("makSoFilesList",makSoFilesList);
        }

        body.put("makSoDetailList",makSoDetailList);


        Map res = put(getErpUrl(type) + "pws/mak/makSalesOrder/change", null, getHeader(type), body);

        return McR.success();
    }*/

    private String getString(Object object){
        return (object == null) ? "" : object.toString();
    }

    private Map<String,String> getHeader(String type){
        Map<String, Object> map = new HashMap<>();
        if ("深圳".equals(type)){
            map = post(erpUrlSz + "pws/sys/mLogin", null, null,UtilMap.map("username, password", userNameSz, passwordSz));
        }else if ("香港".equals(type)){
            map = post(erpUrlXg + "pws/sys/mLogin", null, null,UtilMap.map("username, password", userNameXg, passwordXg));
        }else if ("浙江".equals(type)){
            map = post(erpUrlZj + "pws/sys/mLogin", null, null,UtilMap.map("username, password", userNameZj, passwordZj));
        }else if ("杭州".equals(type)){
            map = post(erpUrlHz + "pws/sys/mLogin", null, null,UtilMap.map("username, password", userNameHz, passwordHz));
        }

        if (Objects.nonNull(map.get("result"))){
            Map<String,Object> result = (Map<String,Object>) map.get("result");
            if (Objects.nonNull(result.get("token"))){
                Map<String, String> header = new HashMap<>();
                header.put("X-Access-Token", result.get("token").toString());
                return header;
            }
        }
        return null;
    }

    /**
     * 封装GET请求
     *
     * @param url    请求的URL
     * @param params 请求参数
     * @param headers 请求头
     * @return 响应内容
     */
    public static Map<String, Object> get(String url, Map<String, Object> params, Map<String, String> headers) {
        log.info("GET 请求url:{}, 请求参数:{}, 请求头:{}", url, params, headers);
        HttpRequest get = HttpUtil.createGet(url);
        if (params!= null){
            get.form(params);
        }

        if (headers!= null){
            get.addHeaders(headers);
        }
        HttpResponse response = get.execute();

        Map<String, Object> result = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(response.body(), new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        log.info("响应结果: {}", result);
        return result;
    }

    /**
     * 封装POST请求
     *
     * @param url    请求的URL
     * @param params 请求参数
     * @param headers 请求头
     * @param body   请求体
     * @return 响应内容
     */
    public static Map<String, Object> post(String url, Map<String, Object> params, Map<String, String> headers, Map<String, Object> body) {
        log.info("POST 请求url:{}, 请求参数:{}, 请求头:{}, 请求体:{}", url, params, headers, body);
        HttpRequest request = HttpUtil.createPost(url);
        if (params != null) {
            request.form(params);
        }
        if (headers != null) {
            request.addHeaders(headers);
        }
        if (body != null) {
            request.body(JSONUtil.toJsonStr(body), "application/json");
        }
        HttpResponse response = request.execute();
//        Map<String,Object> result = JSONUtil.toBean(response.body(), Map.class);
        Map<String, Object> result = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(response.body(), new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("响应结果: {}", result);
        return result;
    }

    public static Map<String, Object> put(String url, Map<String, Object> params, Map<String, String> headers, Map<String, Object> body) {
        log.info("PUT 请求url:{}, 请求参数:{}, 请求头:{}, 请求体:{}", url, params, headers, body);
        HttpRequest request = HttpRequest.put(url);
        if (params != null) {
            request.form(params);
        }
        if (headers != null) {
            request.addHeaders(headers);
        }
        if (body != null) {
            request.body(JSONUtil.toJsonStr(body), "application/json");
        }
        HttpResponse response = request.execute();
//        Map<String,Object> result = JSONUtil.toBean(response.body(), Map.class);
        Map<String, Object> result = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            result = objectMapper.readValue(response.body(), new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        log.info("响应结果: {}", result);
        return result;
    }

    public static String convertChineseToUtf8Hex(String input) {
        StringBuilder sb = new StringBuilder();
        Pattern pattern = Pattern.compile("[\\u4E00-\\u9FFF\\u3000-\\u303F\\uFF00-\\uFFEF]");
        Matcher matcher = pattern.matcher(input);

        int i = 0;
        while (i < input.length()) {
            if (matcher.region(i, i + 1).find()) {
                // 当前字符是中文字符
                char chineseChar = input.charAt(i);
                byte[] utf8Bytes = String.valueOf(chineseChar).getBytes(StandardCharsets.UTF_8);
                StringBuilder hexString = new StringBuilder();
                for (byte b : utf8Bytes) {
                    hexString.append(String.format("%02x", b));
                }
                sb.append(hexString.toString());
            } else {
                // 当前字符不是中文字符
                sb.append(input.charAt(i));
            }
            i++;
        }

        return sb.toString();
    }

    public String postWithFile(String url, String filePath,String type) throws UnsupportedEncodingException {
        // 文件路径
        File file = new File(filePath);

        // 创建HttpClient实例
        HttpClient client = SkipHttpsUtil.wrapClient();
//        HttpClient client = HttpClients.createDefault();

        // 创建HttpPost实例
        HttpPost post = new HttpPost(url);

        // 添加请求头
        post.setHeader("X-Access-Token", getHeader(type).get("X-Access-Token"));

        // 使用MultipartEntityBuilder来构建multipart请求
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        //如果fileUrl中包含中文，则需要对其进行编码
//        String encodeFileName = convertChineseToUtf8Hex(file.getName());

        builder.addBinaryBody("file", file, ContentType.DEFAULT_BINARY, file.getName());

        // 设置请求体
        HttpEntity multipart = builder.build();
        post.setEntity(multipart);

        try {
            // 发送请求并获取响应

            org.apache.http.HttpResponse response = client.execute(post);

            // 处理响应
            // 例如，打印响应状态码
            System.out.println(response.getStatusLine().getStatusCode());
            HttpEntity entity = response.getEntity();
            String fileName = "";
            // 判断响应实体是否为null
            if (entity != null) {
                // 使用EntityUtils读取响应体内容（这里假设是文本类型）
                String responseString = EntityUtils.toString(entity, "UTF-8"); // 指定字符集
                System.out.println("Response Body: " + responseString);
                Map parse = (Map) JSONObject.parse(responseString);
                if ((boolean)parse.get("success")){
                    fileName = getString(parse.get("message"));
                }
                // 释放响应实体资源（虽然EntityUtils.toString()在某些HttpClient版本中会自动处理）
                EntityUtils.consume(entity);
            }
            return fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void updateCurrency() {
        //获取erp币别列表
        String[] ERP_URLS = new String[]{erpUrlSz,erpUrlXg,erpUrlZj, erpUrlHz};
        String[] ERP_ENVS = new String[]{"深圳","香港","浙江","杭州"};
        for (int i = 0; i < ERP_URLS.length; i++) {
            List<Map<String,String>> list = new ArrayList<>();
            int pageNo = 1;
            int pageSize = 50;
            Map result = new HashMap<>();
            do {
                Map param = new HashMap();
                param.put("pageNo",pageNo);
                param.put("pageSize",pageSize);
                Map<String, Object> res = get(ERP_URLS[i] + "pws/fin/finCurrency/list", param, getHeader(ERP_ENVS[i]));
                result = (Map) res.get("result");
                List<Map> records = (List<Map>) result.get("records");
                int finalI = i;
                list.addAll(records.stream().map(map1 -> {
                    Map<String,String> map = new HashMap<>();
                    map.put("textField_m054h6gw",map1.get("currencyCode").toString());
                    map.put("textField_m054h6gx",map1.get("currencyName").toString());
                    map.put("textField_m054h6gy",map1.get("active_dictText").toString());
                    map.put("selectField_m3fgkfz9",ERP_ENVS[finalI]);
                    map.put("textField_m3fiygvb",map.get("selectField_m3fgkfz9") + map.get("textField_m054h6gw"));//唯一标识

                    return map;
                }).collect(Collectors.toList()));
                pageNo++;
            }while (pageNo * pageSize < (int) result.get("total"));

            //更新宜搭币别
            for (Map map : list) {
                ydService.upsertFormData("FORM-01CF3B9C5A364D32A011A6EA8B59B82AIUDI",UtilMap.map("textField_m3fiygvb",map.get("textField_m3fiygvb")),map,null);
            }
        }
    }

    @Override
    public void updateTaxRate() {
        //获取erp税率列表
        String[] ERP_URLS = new String[]{erpUrlSz,erpUrlXg,erpUrlZj, erpUrlHz};
        String[] ERP_ENVS = new String[]{"深圳","香港","浙江","杭州"};
        for (int i = 0; i < ERP_URLS.length; i++) {
            List<Map<String,String>> list = new ArrayList<>();
            int pageNo = 1;
            int pageSize = 50;
            Map result = new HashMap<>();
            do {
                Map param = new HashMap();
                param.put("pageNo",pageNo);
                param.put("pageSize",pageSize);
                Map<String, Object> res = get(ERP_URLS[i] + "pws/fin/finTax/list", param, getHeader(ERP_ENVS[i]));
                result = (Map) res.get("result");
                List<Map> records = (List<Map>) result.get("records");
                int finalI = i;
                list.addAll(records.stream().map(map1 -> {
                    Map<String,String> map = new HashMap<>();
                    map.put("textField_m0539uy1",map1.get("id").toString());
                    map.put("numberField_m0539uy2",map1.get("taxValue").toString());
                    map.put("textField_m0539uy4",map1.get("taxName").toString());
                    map.put("selectField_m3fgkfz9",ERP_ENVS[finalI]);
                    map.put("textField_m3fiygvb",map.get("selectField_m3fgkfz9") + map.get("textField_m0539uy1"));//唯一标识
                    return map;
                }).collect(Collectors.toList()));
                pageNo++;
            }while (pageNo * pageSize < (int) result.get("total"));

            //更新宜搭税率
            for (Map map : list) {
                ydService.upsertFormData("FORM-47A9FC4550574A0488A3F2ECB30FADB0Z67F",UtilMap.map("textField_m3fiygvb",map.get("textField_m3fiygvb")),map,null);
            }
        }
    }

    @Override
    public void updateProcess() {
        //获取erp工序列表
        String[] ERP_URLS = new String[]{erpUrlSz,erpUrlXg,erpUrlZj, erpUrlHz};
        String[] ERP_ENVS = new String[]{"深圳","香港","浙江","杭州"};
        for (int i = 0; i < ERP_URLS.length; i++) {
            List<Map<String,String>> list = new ArrayList<>();
            int pageNo = 1;
            int pageSize = 50;
            Map result = new HashMap<>();

            do {
                Map param = new HashMap();
                param.put("pageNo",pageNo);
                param.put("pageSize",pageSize);
                Map<String, Object> res = get(ERP_URLS[i] + "pws/pdm/pdmStation/list", param, getHeader(ERP_ENVS[i]));
                result = (Map) res.get("result");
                List<Map> records = (List<Map>) result.get("records");
                int finalI = i;
                list.addAll(records.stream().map(map1 -> {
                    Map<String,String> map = new HashMap<>();
                    map.put("textField_m04yhw4p",getString(map1.get("stationCode")));//工序编码
                    map.put("textField_m04yhw56",getString(map1.get("stationName")));//工序名称
                    map.put("textField_m04yhw57",getString(map1.get("stationClass")));//工序分类
                    map.put("textField_m04yhw58",getString(map1.get("productionType_dictText")));//生产类型
                    map.put("numberField_m04yhw5b",getString(map1.get("cycleTime")));//生产周期
                    map.put("textField_m04yhw5a",getString(map1.get("stockFlag")));//可入库
                    map.put("textField_m04yhw5c",getString(map1.get("unitCode_dictText")));//计价方式
                    map.put("textField_m04yhw5d",getString(map1.get("stationType_dictText")));//工序类型
                    map.put("textField_m04yhw5e",getString(map1.get("comments")));//备注
                    map.put("textField_m04yhw5f",getString(map1.get("active_dictText")));//审核状态
                    map.put("selectField_m3fgkfz9",ERP_ENVS[finalI]);
                    map.put("textField_m3fiygvb",map.get("selectField_m3fgkfz9") + map.get("textField_m04yhw4p"));//唯一标识

                    return map;
                }).collect(Collectors.toList()));
                pageNo++;
            }while (pageNo * pageSize < (int) result.get("total"));

            //更新宜搭工序
            for (Map map : list) {
                ydService.upsertFormData("FORM-2F06B5F437124B3ABA8D5275D1D277E4R9O1",UtilMap.map("textField_m3fiygvb",map.get("textField_m3fiygvb")),map,null);
            }
        }
    }

    @Override
    public McR updateCustomerProcess(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();

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

        String jsonString = formData.get("associationFormField_lzto0clw_id").toString();
        String customerJsonString = StringEscapeUtils.unescapeJava(jsonString.substring(1, jsonString.length() - 1));
        List<Map> customer =(List<Map>) JSONArray.parse(customerJsonString);
        String updateFormInstId = customer.get(0).get("instanceId").toString();

        String jsonString2 = formData.get("associationFormField_m3s7manr_id").toString();
        String customerJsonString3 = StringEscapeUtils.unescapeJava(jsonString2.substring(1, jsonString2.length() - 1));
        formData.put("associationFormField_m3s7manr",customerJsonString3);//代理终端客户

        formData.put("employeeField_m2cz3vbt",formData.get("employeeField_m2cz3vbt_id"));//关联人员

        ydClient.operateData(YDParam.builder()
                .formInstanceId(updateFormInstId)
                .updateFormDataJson(JSON.toJSONString(formData))
                .build(),YDConf.FORM_OPERATION.update);

        return McR.success();
    }

    @Override
    public McR addWeeklyReport(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();
        //查询周报计划
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);

        Map formData = ddrNew.getFormData();
        //周报发起人
        List<String> initiateUserIds = (List<String>) formData.get("employeeField_m27e9i5u_id");

        //周报填写人员
        List<String> weeklyUserIds = (List<String>) formData.get("employeeField_m27e9i5v_id");

        //下次自动发起周报日期
        long nextTime = (long) formData.get("dateField_m27e9i5w");
        Date nextDate = new Date(nextTime);

        //汇报日期区间
        Date startDate = DateUtil.beginOfWeek(nextDate);
        Date endDate = DateUtil.endOfWeek(nextDate);
        String startDateTime = startDate.getTime() + "";
        String endDateTime = endDate.getTime() + "";

        //上次自动发起周报日期
        Date lastTime = nextDate;

        nextDate = DateUtils.addDays(nextDate, 7);

        Map weeklyFormData = new HashMap();
        weeklyFormData.put("departmentSelectField_lwprtzha",formData.get("departmentSelectField_m27e9i5t_id"));//部门
        weeklyFormData.put("dateField_m2d0mach",formData.get("dateField_m27e9i5w"));//汇报开始日期
        weeklyFormData.put("cascadeDateField_m2cyyp0j",new String[]{startDateTime,endDateTime});//汇报日期区间
        weeklyFormData.put("numberField_m27dxqle",formData.get("numberField_m27dxqle"));//汇报周
        weeklyFormData.put("employeeField_m28cj0dq",weeklyUserIds);//周报填写人员

        List<Map> weeklyDetails = new ArrayList<>();
        for (String weeklyUserId : weeklyUserIds) {
            Map detail = new HashMap();
            detail.put("employeeField_m0z2tckk",new String[]{weeklyUserId});//周报人员

            weeklyDetails.add(detail);
        }

        weeklyFormData.put("tableField_m27dxqla",weeklyDetails);//周报明细

        //发起销售周报
        ydClient.operateData(YDParam.builder()
                .formUuid("FORM-A68EA411FA5E498490FAC6E4FC30A84F2KN5")
                .formDataJson(JSON.toJSONString(weeklyFormData))
                .userId(initiateUserIds.get(0))
                .build(),YDConf.FORM_OPERATION.create);

        //更新周报计划下次发起周报时间及上次发起周报时间
        Map updateFormData = new HashMap();
        updateFormData.put("dateField_m27e9i61", lastTime);
        updateFormData.put("dateField_m27e9i5w", nextDate);

        ydClient.operateData(YDParam.builder()
                .formInstId(formInstId)
                .updateFormDataJson(JSON.toJSONString(updateFormData))
                .build(), YDConf.FORM_OPERATION.update);

        return McR.success();
    }

    @Override
    public McR getTbStageOptions(String projectName,String projectId,String stageName) {
        List<Map> options = new ArrayList<>();

        if (Strings.isNullOrEmpty(projectName)){
            return McR.errorParam("项目名称不能为空！");
        }

        if (Strings.isNullOrEmpty(projectId)){
            Map mcBody = new HashMap();
            mcBody.put("url","https://open.teambition.com/api/v3/project/query");
            mcBody.put("headers",initHeaderToken());
            mcBody.put("params",UtilMap.map("name", projectName));
            Map mcResult = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody));
            List<Map> projectList = (List<Map>)mcResult.get("result");


/*            TBR projectTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/query", initHeaderToken(), UtilMap.map("name", projectName), TBR.class);
            List<Map> projectList = (List<Map>) projectTbr.getResult();*/
            if (projectList.isEmpty()){
                return McR.errorParam("未在TB中查询到此项目信息！");
            }
            Map projectMap = projectList.get(0);
            projectId = projectMap.get("id").toString();
        }

        //搜索任务列表
        Map mcBody = new HashMap();
        mcBody.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/stage/search");
        mcBody.put("headers",initHeaderToken());
        mcBody.put("params",null);
        Map mcResult = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody));
        List<Map> stageList = (List<Map>)mcResult.get("result");

        /*TBR stageTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/stage/search", initHeaderToken(), null, TBR.class);
        List<Map> stageList = (List<Map>) stageTbr.getResult();*/
        Map<String,String> stageMap = new HashMap<>();
        for (Map stage : stageList) {
            String name = stage.get("name").toString().replaceAll("\\s+","");
            if (STAGES.contains(name)){
                stageMap.put(stage.get("id").toString(),name);
            }
        }

        //查询父任务详情
        for (String stageId : stageMap.keySet()) {
            Map mcBody2 = new HashMap();
            mcBody2.put("url","https://open.teambition.com/api/v3/project/" + projectId + "/task/query");
            mcBody2.put("headers",initHeaderToken());
            mcBody2.put("params",UtilMap.map("q", "stageId = " + stageId + " AND taskLayer = onlyTopLevel"));
            Map mcResult2 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody2));
            List<Map> parentTaskList = (List<Map>)mcResult2.get("result");

            /*TBR parentTaskTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/query", initHeaderToken(), UtilMap.map("q", "stageId = " + stageId + " AND taskLayer = onlyTopLevel"), TBR.class);
            List<Map> parentTaskList = (List<Map>) parentTaskTbr.getResult();*/
            for (Map parentTask : parentTaskList) {
                String content = parentTask.get("content").toString();

                if (content.contains(stageName)) {
                    Map<String,Object> option = new HashMap<>();
                    option.put("text",content);
                    option.put("value",parentTask.get("id").toString());
                    options.add(option);
                }
            }
        }
        return McR.success(options);
    }

    @Override
    public McR claimBusinessOpportunities(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        if (Objects.isNull(map.get("userId"))){
            return McR.errorParam("userId不能为空");
        }
        String formInstId = map.get("formInstId").toString();
        String userId = map.get("userId").toString();
        userId = userId.substring(userId.indexOf("\"")+1,userId.lastIndexOf("\""));
        //更新商机状态和销售人员
        Map updateFormData = new HashMap();
        updateFormData.put("selectField_m28uros3","跟进中");
        updateFormData.put("employeeField_m2a830k8",userId);
        ydClient.operateData(YDParam.builder()
                .formInstId(formInstId)
                .updateFormDataJson(JSON.toJSONString(updateFormData))
                .build(),YDConf.FORM_OPERATION.update);

        return McR.success();
    }

    @Override
    public McR createTbProject(Map map) {
        if (Objects.isNull(map.get("name")) || Objects.isNull(map.get("uuid"))){
            return McR.errorParam("项目名称或项目唯一标识不能为空");
        }

        String name = map.get("name").toString();
        String uuid = map.get("uuid").toString();

        Map body = new HashMap();
        body.put("name",name);
        body.put("templateId",templateId);

        Map mcBody = new HashMap();
        mcBody.put("url","https://open.teambition.com/api/v3/project/create-from-template");
        mcBody.put("headers",initHeaderToken());
        mcBody.put("params",null);
        mcBody.put("body",body);
        Map mcResult = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/post",null,null,mcBody));
        Map result = (Map) mcResult.get("result");


        /*TBR tbr = (TBR) UtilHttp.doPost("https://open.teambition.com/api/v3/project/create-from-template", initHeaderToken(), null,body, TBR.class);
        Map result = (Map) tbr.getResult();*/
        String id = result.get("id").toString();

        //更新项目档案
        ydClient.operateData(YDParam.builder()
                .formUuid("FORM-B43148BB37324A729A852ED7B40E1A10USDA")
                .searchCondition(JSON.toJSONString(UtilMap.map("textField_m03860ye",uuid)))
                .formDataJson(JSON.toJSONString(UtilMap.map("textField_m2cwpzya",id)))
                .build(),YDConf.FORM_OPERATION.upsert);

        return McR.success(id);
    }

    @Override
    public McR addContacts(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();
        //查询线索信息
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);

        Map formData = ddrNew.getFormData();

        String customerName = getString(formData.get("textField_m2ipea64"));//客户名称
        String customerCode = getString(formData.get("textField_m50vl2jt"));//客户编号
        String contacts = getString(formData.get("textField_m2ipea63"));//联系人
        String phone = getString(formData.get("textField_m2ipea65"));//电话

        List<Map> data = (List<Map>) ydClient.queryData(YDParam.builder()
                .formUuid("FORM-221A9483B28448089ACBA5B4748D6288KMG5")
                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_m4u3lrdv, textField_lwpquxe4", customerCode, contacts)))
                .build(), YDConf.FORM_QUERY.retrieve_list).getData();
        if (!data.isEmpty()){
            Map updateFormData = (Map) data.get(0).get("formData");
            String updateFormInstId = data.get(0).get("formInstanceId").toString();
            List<String> types = (List<String>) updateFormData.get("multiSelectField_m278ty7s");
            if (types.contains("电话")){
                return McR.success("联系人已存在");
            }else{
                types.add("电话");
                updateFormData.put("multiSelectField_m278ty7s",types);
                updateFormData.put("textField_lwpquxe9",phone);

                ydClient.operateData(YDParam.builder()
                        .formInstId(updateFormInstId)
                        .updateFormDataJson(JSON.toJSONString(updateFormData))
                        .build(), YDConf.FORM_OPERATION.update);
            }
        }else {
            if (!contacts.isEmpty()){
                //新增联系人
                Map contactFormData = new HashMap();

                List<Map> customer = new ArrayList<>();
                Map customerMap = new HashMap();
                customerMap.put("appType",ydConf.getAppType());
                customerMap.put("formUuid","FORM-6F1E2DCFB3F5448EBDD4994551EBF690DVIT");
                customerMap.put("formType","receipt");
                customerMap.put("instanceId",formInstId);
                customerMap.put("title",customerName);
                customerMap.put("subTitle","");
                customer.add(customerMap);

                contactFormData.put("associationFormField_m4qdcril",customer);
                contactFormData.put("textField_lwpquxe4",contacts);
                contactFormData.put("multiSelectField_m278ty7s",new String[]{"电话"});
                contactFormData.put("textField_lwpquxe9",phone);
                contactFormData.put("textField_m0z0e88f",customerName);
                contactFormData.put("textField_m4u3lrdv",customerCode);

                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-221A9483B28448089ACBA5B4748D6288KMG5")
                        .formDataJson(JSON.toJSONString(contactFormData))
                        .build(), YDConf.FORM_OPERATION.create);
            }
        }

        return McR.success();
    }

    @Override
    public McR stopProcess(Map map) {
        if (Objects.isNull(map.get("formInstId"))){
            return McR.errorParam("formInstId不能为空");
        }
        String formInstId = map.get("formInstId").toString();
        //查询发起人信息
        DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);

        Map originator = ddrNew.getOriginator();
        String userId = originator.get("userId").toString();
        //中止流程
        Map params = new HashMap();
        params.put("processInstanceId", formInstId);
        params.put("userId", userId);
        params.put("appType", ydConf.getAppType());
        params.put("systemToken", ydConf.getSystemToken());


        String result = UtilHttp.doPut("https://api.dingtalk.com/v1.0/yida/processes/instances/terminate", ddClient.initTokenHeader(),params, (Map) null);

        return McR.success(result);
    }

    @Override
    public McR getTbStageDetails(String projectName,String projectId,String parentTaskId) {
        Map<String,Object> stageDetail = new HashMap<>();
        //根据项目名称获取项目id
        if (Strings.isNullOrEmpty(projectName) || Strings.isNullOrEmpty(parentTaskId)){
            return McR.errorParam("项目名称或父任务id不能为空！");
        }
        if (Strings.isNullOrEmpty(projectId)){
            /*TBR projectTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/query", initHeaderToken(), UtilMap.map("name", projectName), TBR.class);
            List<Map> projectList = (List<Map>) projectTbr.getResult();*/
            Map mcBody = new HashMap();
            mcBody.put("url","https://open.teambition.com/api/v3/project/query");
            mcBody.put("headers",initHeaderToken());
            mcBody.put("params",UtilMap.map("name", projectName));
            Map mcResult = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody));
            List<Map> projectList = (List<Map>)mcResult.get("result");

            if (projectList.isEmpty()){
                return McR.errorParam("未在TB中查询到此项目信息！");
            }
            Map projectMap = projectList.get(0);
            projectId = projectMap.get("id").toString();
        }

        //搜索项目自定义字段
        /*TBR cfTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/customfield/search", initHeaderToken(), null, TBR.class);
        List<Map> cfList = (List<Map>) cfTbr.getResult();*/
        Map mcBody = new HashMap();
        mcBody.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/customfield/search");
        mcBody.put("headers",initHeaderToken());
        mcBody.put("params",null);
        Map mcResult = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody));
        List<Map> cfList = (List<Map>)mcResult.get("result");

        Map<String,String> cfMap = new HashMap<>();
        cfList.forEach(cf -> {
            String name = cf.get("name").toString();
            switch (name){
                case "责任部门/角色":
                    cfMap.put(cf.get("id").toString(),"dept");
                    break;
                case "评审领域":
                    cfMap.put(cf.get("id").toString(),"area");
                    break;
                case "评审要素":
                    cfMap.put(cf.get("id").toString(),"part");
                    break;
                case "交付件":
                    cfMap.put(cf.get("id").toString(),"file");
                    break;
                case "交付件2":
                    cfMap.put(cf.get("id").toString(),"file2");
            }
        });

        //搜索项目标签
        /*TBR tagTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/tag/search", initHeaderToken(), null, TBR.class);
        List<Map> tagResult = (List<Map>) tagTbr.getResult();*/
        Map mcBody2 = new HashMap();
        mcBody2.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/tag/search");
        mcBody2.put("headers",initHeaderToken());
        mcBody2.put("params",null);
        Map mcResult2 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody2));
        List<Map> tagResult = (List<Map>)mcResult2.get("result");

        Map<String,String> tagMap = new HashMap<>();
        tagResult.forEach(tag -> tagMap.put(tag.get("id").toString(),tag.get("name").toString()));

        //搜索任务列表
        /*TBR stageTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/stage/search", initHeaderToken(), null, TBR.class);
        List<Map> stageList = (List<Map>) stageTbr.getResult();*/
        Map mcBody3 = new HashMap();
        mcBody3.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/stage/search");
        mcBody3.put("headers",initHeaderToken());
        mcBody3.put("params",null);
        Map mcResult3 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody3));
        List<Map> stageList = (List<Map>)mcResult3.get("result");

        Map<String,String> stageMap = new HashMap<>();
        for (Map stage : stageList) {
            String name = stage.get("name").toString().replaceAll("\\s+","");
            if (STAGES.contains(name)){
                stageMap.put(stage.get("id").toString(),name);
            }
        }
        //子任务工作流状态
        Map<String,String> subTaskState = new HashMap<>();

        //查询父任务详情
        /*TBR tbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", initHeaderToken(), UtilMap.map("parentTaskId", parentTaskId), TBR.class);
        List<Map<String, Object>> task = (List<Map<String, Object>>) tbr.getResult();*/
        Map mcBody4 = new HashMap();
        mcBody4.put("url","https://open.teambition.com/api/v3/task/query");
        mcBody4.put("headers",initHeaderToken());
        mcBody4.put("params",UtilMap.map("parentTaskId", parentTaskId));
        Map mcResult4 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody4));
        List<Map<String, Object>> task = (List<Map<String, Object>>)mcResult4.get("result");

        List<Map<String, Object>> list = new ArrayList<>();
        boolean flag = true;
        for (Map<String,Object> subTask : task) {
            //获取子任务工作流状态（一个项目同级子任务的工作流id一样 查询一次）
            if (flag){
                String sfcId = subTask.get("sfcId").toString();//任务类型id
                //查询任务类型
                /*TBR sfcTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/scenariofieldconfig/search", initHeaderToken(), UtilMap.map("sfcIds", sfcId), TBR.class);
                List<Map> sfcList = (List<Map>) sfcTbr.getResult();*/
                Map mcBody5 = new HashMap();
                mcBody5.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/scenariofieldconfig/search");
                mcBody5.put("headers",initHeaderToken());
                mcBody5.put("params",UtilMap.map("sfcIds", sfcId));
                Map mcResult5 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody5));
                List<Map> sfcList = (List<Map>)mcResult5.get("result");

                String taskFlowId = sfcList.get(0).get("taskflowId").toString();//工作流id

                //获取工作流下所有状态节点信息
                /*TBR tfTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/taskflowstatus/search", initHeaderToken(), UtilMap.map("tfIds", taskFlowId), TBR.class);
                List<Map> tfList = (List<Map>) tfTbr.getResult();*/
                Map mcBody6 = new HashMap();
                mcBody6.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/taskflowstatus/search");
                mcBody6.put("headers",initHeaderToken());
                mcBody6.put("params",UtilMap.map("tfIds", taskFlowId));
                Map mcResult6 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody6));
                List<Map> tfList  = (List<Map>)mcResult6.get("result");

                for (Map tf : tfList) {
                    String name = tf.get("name").toString();
                    String tfsId = tf.get("id").toString();
                    subTaskState.put(tfsId, name);
                }
                flag = false;
            }

            Map<String,Object> taskDetail = new HashMap<>();
            String content2 = subTask.get("content").toString();
            taskDetail.put("content", content2);
            taskDetail.put("url", TASK_URL_PREFIX + subTask.get("id"));

            String tfsId = subTask.get("tfsId").toString();//工作流状态id
            taskDetail.put("state", subTaskState.get(tfsId));//任务状态

            List<Map<String,Object>> customfields = (List<Map<String,Object>>) subTask.get("customfields");
            taskDetail.put("dept", "");
            taskDetail.put("part", "");
            taskDetail.put("area", "");
            taskDetail.put("file", "");
            taskDetail.put("file2", "");
            if (!customfields.isEmpty()){
                for (Map<String, Object> customfield : customfields) {
                    String cfId = customfield.get("cfId").toString();
                    if (cfMap.containsKey(cfId)){
                        String cfName = cfMap.get(cfId);
                        List<Map<String, Object>> value = (List<Map<String, Object>>) customfield.get("value");
                        if (!value.isEmpty()){
                            String title = value.get(0).get("title").toString();
                            taskDetail.put(cfName, title);
                        }
                    }
                }
            }

            taskDetail.put("carTag", "");
            taskDetail.put("payTag", "");
            List<String> tagIds = (List<String>) subTask.get("tagIds");
            if (!tagIds.isEmpty()){
                for (String tagId : tagIds) {
                    if (tagMap.containsKey(tagId)) {
                        if (tagMap.get(tagId).contains("车载")){
                            taskDetail.put("carTag", tagMap.get(tagId).substring(3,5));
                        }else if (tagMap.get(tagId).contains("消费")){
                            taskDetail.put("payTag", tagMap.get(tagId).substring(3,5));
                        }
                    }
                }
            }

            list.add(taskDetail);
        }

        //获取父任务工作流状态
        //获取父任务详情
        /*TBR tbr2 = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", initHeaderToken(), UtilMap.map("taskId", parentTaskId), TBR.class);
        List<Map<String, Object>> result2 = (List<Map<String, Object>>) tbr2.getResult();*/
        Map mcBody6 = new HashMap();
        mcBody6.put("url","https://open.teambition.com/api/v3/task/query");
        mcBody6.put("headers",initHeaderToken());
        mcBody6.put("params",UtilMap.map("taskId", parentTaskId));
        Map mcResult6 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody6));
        List<Map<String, Object>> result2  = (List<Map<String, Object>>)mcResult6.get("result");

        String sfcId = result2.get(0).get("sfcId").toString();
        String tfsId = result2.get(0).get("tfsId").toString();

        //获取项目任务类型
        /*TBR tbr3 = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/"+projectId+"/scenariofieldconfig/search", initHeaderToken(), UtilMap.map("sfcIds", sfcId), TBR.class);
        List<Map<String, Object>> result3 = (List<Map<String, Object>>) tbr3.getResult();*/
        Map mcBody7 = new HashMap();
        mcBody7.put("url","https://open.teambition.com/api/v3/project/"+projectId+"/scenariofieldconfig/search");
        mcBody7.put("headers",initHeaderToken());
        mcBody7.put("params",UtilMap.map("sfcIds", sfcId));
        Map mcResult7 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody7));
        List<Map<String, Object>> result3  = (List<Map<String, Object>>)mcResult7.get("result");
        String taskflowId = result3.get(0).get("taskflowId").toString();

        //搜索项目工作流状态
        /*TBR tbr4 = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/taskflowstatus/search", initHeaderToken(), UtilMap.map("tfIds", taskflowId), TBR.class);
        List<Map<String, Object>> result4 = (List<Map<String, Object>>) tbr4.getResult();*/
        Map mcBody8 = new HashMap();
        mcBody8.put("url","https://open.teambition.com/api/v3/project/" + projectId + "/taskflowstatus/search");
        mcBody8.put("headers",initHeaderToken());
        mcBody8.put("params",UtilMap.map("tfIds", taskflowId));
        Map mcResult8 = (Map) JSON.parse(UtilHttp.doPost("https://mc.cloudpure.cn/api/mc/request/get",null,null,mcBody8));
        List<Map<String, Object>> result4  = (List<Map<String, Object>>)mcResult8.get("result");

        result4.forEach(tf -> {
            if (tf.get("id").toString().equals(tfsId)){
                stageDetail.put("state", tf.get("name").toString());
            }
        });

        stageDetail.put("list",list);


        /*if (stageName.equals(content)){
            parentTaskId = parentTask.get("id").toString();
            //查询子任务信息



            break;
        }*/

/*        for (String stageId : stageMap.keySet()) {
            TBR parentTaskTbr = (TBR) UtilHttp.doGet("https://open.teambition.com/api/v3/project/" + projectId + "/task/query", initHeaderToken(), UtilMap.map("q", "stageId = " + stageId + " AND taskLayer = onlyTopLevel"), TBR.class);
            List<Map> parentTaskList = (List<Map>) parentTaskTbr.getResult();
            for (Map parentTask : parentTaskList) {
                String content = parentTask.get("content").toString();
                String parentTaskId = "";

            }
        }*/

        return McR.success(stageDetail);
    }

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

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

}
