package com.malk.tuosi.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Extension;
import com.malk.tuosi.service.impl.TbServiceImpl;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/test")
public class test {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDConf ddConf;


    @PostMapping("/test01")
    McR test01(){
        return McR.success("接口畅通");
    }

    @PostMapping("/test02")
    McR test02(){
        String basedir = "C:/downloads";
        String downloadUrl = "https://teambition-file.oss-cn-zhangjiakou.aliyuncs.com/attachment/2025/11/22/622ee3450cf3bb5e1a486f1f/980131a2-d227-4029-9973-66507caa9c1a/1763781410334.png?OSSAccessKeyId=LTAI5tDBLZMyFnXCXQiYZMcj&Expires=1763783213&Signature=%2BaySoA9YMyI4OdzTixSKD6ZGUXA%3D&response-content-disposition=attachment%3BfileName*%3DUTF-8%27%27e824b899a9014c08ed1ab1039e4959077bf4f431.png&tb-file-token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJvYmplY3ROYW1lIjoiYXR0YWNobWVudC8yMDI1LzExLzIyLzYyMmVlMzQ1MGNmM2JiNWUxYTQ4NmYxZi85ODAxMzFhMi1kMjI3LTQwMjktOTk3My02NjUwN2NhYTljMWEvMTc2Mzc4MTQxMDMzNC5wbmciLCJzY29wZSI6IioiLCJmaWxlTmFtZSI6ImU4MjRiODk5YTkwMTRjMDhlZDFhYjEwMzllNDk1OTA3N2JmNGY0MzEucG5nIiwiZmlsZVNpemUiOjAsImZpbGVUeXBlIjoiIiwidGltZXN0YW1wIjoxNzYzNzgxNDEzMTQxLCJpYXQiOjE3NjM3ODE0MTMsImV4cCI6MTc2Mzg2NzgxM30.-XxANowki1RyJilGK4tcZ_300hQIuwxsQCFbhJ9jQLE";
        String fileName = "11.22图片";
        String savePath = downloadFile(downloadUrl, basedir, fileName);
        return McR.success(savePath);
    }

    @PostMapping("/test03")
    McR test03() throws JsonProcessingException {
        List<String> involveMembers = new ArrayList<>();
        involveMembers.add("61a8c27b5b791c30cc540ce5");
        return McR.success(tbService.TBtoDinguserId(involveMembers));
    }



    @SneakyThrows
    public static String downloadFile(String fileUrl, String baseDir, String customFileName){
        // 创建基础目录
        File baseDirectory = new File(baseDir);
        if (!baseDirectory.exists()) {
            baseDirectory.mkdirs();
        }

        // 完整的保存路径
        String savePath = new File(baseDir, customFileName).getAbsolutePath();

        // 下载文件
        URL url = new URL(fileUrl);
        URLConnection connection = url.openConnection();

        // 添加必要的请求头
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setConnectTimeout(30000);
        connection.setReadTimeout(30000);

        try (InputStream in = connection.getInputStream();
             FileOutputStream out = new FileOutputStream(savePath)) {

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return savePath;
    }

    /*群消息卡片投放*/
    @PostMapping("/card/createAndDeliver")
    public McR createAndDeliverCard(@RequestBody JSONObject param){
        log.info("推送消息:{}",param);
        McException.assertParamException_Null(param,"cardData","outTrackId","openSpaceId","robotCode","cardTemplateId");
        Map<String,Object> data = new HashMap();
        data.put("imGroupOpenDeliverModel", UtilMap.map("robotCode",param.getString("robotCode")));
        data.put("imGroupOpenSpaceModel",UtilMap.map("supportForward",true));
        if(param.containsKey("extInfo")){
            data.putAll(param.getJSONObject("extInfo"));
        }
        Map map = ddClientExtension.createAndDeliverCards(ddClient.getAccessToken(),param.getString("cardTemplateId"),param.getString("outTrackId"),
                UtilMap.map("cardParamMap",param.getJSONObject("cardData")),param.getString("openSpaceId"),data);
        return McR.success(map);
    }
    @Autowired
    private DDClient_Extension ddClientExtension;

    /*获取群会话id*/
    @PostMapping("/card/test")
    McR cardtest(@RequestBody String body){
        System.out.println("回调参数：" + body);
        return McR.success();
    }


    @Autowired
    private TbServiceImpl tbService;
    /*查询任务详情*/
    @SneakyThrows
    @PostMapping("/searchtask")
    McR searchtask(){
        List<String> allResourceIds = new ArrayList<>();//存储文件的ids
        List<String>  downloadUrls= new ArrayList<>();//存储文件下载地址
        /*所有的字段信息定义*/
        String content = "";//任务名称
        List<String> involveMembers = new ArrayList<>();//负责人
        String businessManager = "";//业务经理
        String businessPerson = "";//业务人员
        String customerName = "";//客户名称
        String downloadUrl = "";
        String valueAsString = "";//文件下载地址（jsonString）

        String taskId = "69367cd39ae5405b05dc40bf";
        HashMap head = new HashMap();
        McR accessToken = tbService.AppAccessToken();
        Object tokenData = accessToken.getData();
        head.put("Authorization","Bearer " + tokenData);
        head.put("X-Tenant-Id","61a8c26719c3b5ffe9c4cffb");
        head.put("X-Tenant-Type","organization");
        HashMap param = new HashMap();
        param.put("taskId",taskId);
        String doGet = UtilHttp.doGet("https://open.teambition.com/api/v3/task/query", head, param);//查询任务详情
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(doGet);
        JsonNode result = rootNode.path("result");
        for(JsonNode resultNode : rootNode.path("result")){
            content = resultNode.path("content").asText();//todo:任务名称

            /*JsonNode membersNode = resultNode.path("involveMembers");
            if (membersNode.isArray()) {
                for (JsonNode member : membersNode) {
                    involveMembers.add(member.asText());
                }
            }*/
            JsonNode customFields = resultNode.path("customfields");
            if (customFields.isArray()) {
                for (JsonNode field : customFields) {
                    String cfId = field.path("cfId").asText();
                    // 检查是否有 value 数组
                    JsonNode valueArray = field.path("value");
                    if (!valueArray.isArray() || valueArray.size() == 0) {
                        continue;
                    }
                    // 获取第一个 value 对象
                    JsonNode firstValue = valueArray.get(0);
                    switch (cfId) {
                        case "687df458b9c2f9f90865c13b": // todo：业务经理
                            businessManager = firstValue.path("title").asText();
                            System.out.println("业务经理: " + businessManager);
                            break;

                        case "688191972ab6c4f412ea2bb9": // todo：业务人员
                            businessPerson = firstValue.path("title").asText();
                            System.out.println("业务人员: " + businessPerson);
                            break;

                        case "687df3b60ae1530fa2704499": // todo：客户名称
                            customerName = firstValue.path("title").asText();
                            System.out.println("客户名称: " + customerName);
                            break;

                        case "689d9834591915184b095e5f": // todo：附件 metaString
                            JsonNode valueArray1 = field.path("value");
                            if (valueArray1.isArray()) {
                                for (JsonNode attachment : valueArray) {
                                    String metaString = attachment.path("metaString").asText();
                                    /*新增*/
                                    String title = attachment.path("title").asText();
                                    String director = title.substring(title.lastIndexOf("-") + 1, title.lastIndexOf("."));
                                    involveMembers.add(director);
                                    /*新增*/
                                    if (!metaString.isEmpty()) {
                                        ObjectMapper mapper = new ObjectMapper();
                                        JsonNode metaJson = mapper.readTree(metaString);
                                        String resourceId = metaJson.path("resourceId").asText();
                                        allResourceIds.add(resourceId);
                                    }
                                }
                            }
                            HashMap haader = new HashMap();
                            haader.put("Content-Type", "application/json");
                            haader.put("Authorization", "Bearer " + tokenData);
                            haader.put("x-operator-id", "622ee3450cf3bb5e1a486f1f");
                            haader.put("X-Tenant-Id", "61a8c26719c3b5ffe9c4cffb");
                            haader.put("X-Tenant-Type", "organization");

                            HashMap boody = new HashMap();
                            boody.put("resourceIds",allResourceIds);
                            boody.put("needSign",true);

                            String fileDownloadResponse = UtilHttp.doPost("https://open.teambition.com/api/v3/file/query/by-resource-ids", haader, null, boody);
                            JSONObject response = JSON.parseObject(fileDownloadResponse);
                            JSONArray resultArray = response.getJSONArray("result");
                            for (int i=0;i< resultArray.size();i++) {
                                JSONObject fileObject = resultArray.getJSONObject(i);
                                downloadUrl = fileObject.getString("downloadUrl");
                                downloadUrls.add(downloadUrl);
                            }
                            System.out.println("下载地址" + downloadUrls);

                            ObjectMapper mapper = new ObjectMapper();
                            // 使用Stream API创建List<Map<String, String>>
                            List<Map<String, String>> res = downloadUrls.stream()
                                    .map(url -> {
                                        Map<String, String> map = new LinkedHashMap<>(); // 保持顺序
                                        map.put("arr", url);
                                        return map;
                                    })
                                    .collect(Collectors.toList());
                            valueAsString = mapper.writeValueAsString(res);
                            System.out.println("格式化后的下载地址：" + valueAsString);
                            break;
                    }
                }
            }
            System.out.println(); // 空行分隔
            System.out.println("负责人：" + involveMembers);
            String aaa = String.join("，", involveMembers);
            System.out.println("负责人：" + aaa);
        }
        return McR.success();
    }




}
