package com.malk.fenggefushi.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.malk.fenggefushi.service.HeiHuOrderService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.Na;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@Slf4j
@RequestMapping("/test")
public class test {

    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private YDService ydService;
    @Autowired
    private DDConf ddConf;
    @Autowired
    private HeiHuOrderService huOrderService;

    @PostMapping("/test1")
    McR test1(){
        System.out.println("接口正常！");
        return McR.success("接口正常！");
    }

    //测试程序发起下拉单选是否生效
    @GetMapping("/test76")
    McR test76(){
        HashMap formdata = new HashMap();
        formdata.put("selectField_mg5y3rcr","贸易公司订单");

        // 图片/附件字段 - 使用完整的结构化格式
        List<Map<String, Object>> imageAttachments = new ArrayList<>();
        Map<String, Object> imageInfo = new HashMap<>();
        imageInfo.put("name", "CWC-1758612192087.png");
        imageInfo.put("downloadUrl", "https://filebase-prod-oss.blacklake.cn/CWC-1758612192087.png");
        imageInfo.put("previewUrl", "https://filebase-prod-oss.blacklake.cn/CWC-1758612192087.png");
        imageInfo.put("url", "https://filebase-prod-oss.blacklake.cn/CWC-1758612192087.png");
        imageInfo.put("ext", "png");
        imageAttachments.add(imageInfo);
        formdata.put("imageField_mfqgmwde",imageAttachments);
        
        String string = ydClient.operateData(YDParam.builder()
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .formUuid("FORM-472F0C1BD8DF41FA965A0B4525779B67S421")
                .userId("3320511511-1158713155")
                .formDataJson(JSON.toJSONString(formdata))
                .build(), YDConf.FORM_OPERATION.start).toString();
        return McR.success(string);
    }

    //根据员工名字匹配员工id
    String getDDToken(@RequestParam String Name){
        HashMap body = new HashMap();
        body.put("appKey","dingie28nalt6tcnzizl");
        body.put("appSecret","Ss7na86M_BWPEXhKffiQDA-8jXvuBhBklfD8C-ot7xGwiDKfFMIf9y00mXYutfCB");
        String s = UtilHttp.doPost("https://api.dingtalk.com/v1.0/oauth2/accessToken", null, null, body);
        String accessToken  = JSONObject.parseObject(s).getString("accessToken");

        HashMap header = new HashMap();
        header.put("x-acs-dingtalk-access-token",accessToken);
        HashMap bodyy = new HashMap();
        bodyy.put("queryWord", Name);
        bodyy.put("offset",0);
        bodyy.put("size",10);
        String s1 = UtilHttp.doPost("https://api.dingtalk.com/v1.0/contact/users/search", header, null, bodyy);
        List<String> list = JSONObject.parseObject(s1).getJSONArray("list").toJavaList(String.class);
        String userId = "";
        if(list!= null && !list.isEmpty()){
            userId = list.get(0);
        }
        return userId;
    }

    //创建宜搭普通表单
    @PostMapping("/test77")
    McR test77(){
        HashMap formdata = new HashMap();
        formdata.put("textField_mgq90lwf","1");
        formdata.put("dateField_mgq90lwg","1760457600");
        String dd = ydClient.operateData(YDParam.builder()
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .formUuid("FORM-1693380A673E498C827CD0A4C2D8214CIK90")
                .userId("3320511511-1158713155")
                .formDataJson(JSON.toJSONString(formdata))
                .build(), YDConf.FORM_OPERATION.create).toString();
        return McR.success(dd);
    }

    @PostMapping("/test78")
    McR test78(){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 获取当前日期的零点时间
        LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();
        String formattedToday = todayMidnight.format(formatter);

        System.out.println("今天零点时间: " + formattedToday);
        return McR.success();
    }

    @SneakyThrows
    @PostMapping("/test79")
    McR test79(){
        HashMap header = new HashMap();
        header.put("X-AUTH",huOrderService.HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("orderCode","PO20250235");
        /*TODO：对json进行处理*/
        String jsonString  = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//todo:查询采购订单
        List<String> orderNoList = new ArrayList<>();//存在这个orderList里面
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonString);
        JsonNode dataNode = rootNode.get("data");
        String orderNumber = "";
        if (dataNode != null && dataNode.isArray()) {
            for (JsonNode item : dataNode) {
                JsonNode orderNoNode = item.get("orderCode");
                JsonNode saleOrders = item.get("relationSaleOrders");
                System.out.println("关联销售订单号："+ saleOrders);
                System.out.println("采购订单编号：" + orderNoNode);
                if (saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0) {
                    orderNumber = saleOrders.get(0).asText();
                    System.out.println("关联销售订单号(字符串)：" + orderNumber);
                }

                //采购订单编号
                if (orderNoNode != null) {
                    String purchaseOrderNo = orderNoNode.asText();
                    System.out.println("采购订单编号(字符串)：" + purchaseOrderNo);
                }
            }
        }
        System.out.println(orderNoList);
        return McR.success();
    }

    @SneakyThrows
    @PostMapping("/test80")
    McR test80(){
        HashMap header = new HashMap();
        header.put("X-AUTH",huOrderService.HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("orderNo","882698-1107444");
        /*TODO：对json进行处理*/
        String jsonString  = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body);//todo:查询采购订单
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(jsonString);
        JsonNode dataNode = rootNode.get("data");
        if (dataNode != null && dataNode.isArray()) {
            for (JsonNode item : dataNode) {
                JsonNode customFieldValues = item.get("customFieldValues");
                System.out.println("自定义字段列表："+ customFieldValues);
                if (customFieldValues != null && customFieldValues.isArray()) {
                    for (JsonNode field : customFieldValues) {
                        JsonNode fieldIdNode = field.get("fieldId");
                        // 查找fieldId为47771的字段
                        if (fieldIdNode != null && fieldIdNode.asInt() == 47771) {
                            JsonNode valueNode = field.get("value");
                            if (valueNode != null) {
                                String value = valueNode.asText();
                                System.out.println("fieldId为47771的value值：" + value);
                                // 找到后可以跳出内层循环
                                break;
                            }
                        }
                    }
                }
            }
        }
        return McR.success();
    }

    @SneakyThrows
    @PostMapping("/test81")
    McR test81(){
        HashMap head = new HashMap();
        head.put("X-AUTH",huOrderService.HeiHuAccessToken().getData().toString());
        head.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("orderNo","3300--");//订单编号
        String s = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", head, null, body);
        JSONObject jsonObject = JSONObject.parseObject(s);
        JSONArray products = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");
        for (int i = 0; i < products.size(); i++) {
            JSONObject detail = products.getJSONObject(i);
            String customFieldValues = detail.getString("customFieldValues");
            System.out.println("自定义字段：" + customFieldValues);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode jsonArray = mapper.readTree(customFieldValues);
            for (JsonNode node : jsonArray) {
                if (node.get("fieldId").asInt() == 47919) {
                    String value = node.get("value").asText();
                    System.out.println("找到的 value: " + value); // 输出: CNY
                    break;
                }
            }
        }

        return McR.success();
    }

    @SneakyThrows
    @PostMapping("/getPurchaseList")
    McR getPurchaseList(){
        log.info("开始查询宜搭采购订单汇总表");
        String formUuid = "FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91";
        YDParam ydParam = YDParam.builder().formUuid(formUuid).build();
        ydParam.setPageSize(1);
        long totalCount = ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getTotalCount();
        List<Map> datalist = new ArrayList<>();
        ydParam.setCurrentPage(1);
        ydParam.setPageSize(100);
        int totalPages = (int)Math.ceil((double) totalCount / ydParam.getPageSize());

        for (int page = 1;page <= totalPages;page++){
            ydParam.setCurrentPage(page);
            datalist.addAll((List<Map>) ydClient.queryData(ydParam, YDConf.FORM_QUERY.retrieve_search_form).getData());
        }
        int i =0;
        String jsonStr = "";
        Map<String, String> orderMap = new HashMap<>();//格式：采购订单/关联销售订单
        for(Map li : datalist){
            i++;
//            log.info("{}/{}",i,datalist.size());
            jsonStr = li.get("formData").toString();
            String orderNum = new ObjectMapper().readTree(jsonStr).get("textField_mgq932hi").asText();
            String relatedOrderNum = new ObjectMapper().readTree(jsonStr).get("textField_mhyh7ues").asText();
            orderMap.put(orderNum, relatedOrderNum);
        }
        return McR.success(orderMap);
    }

    @PostMapping("/updateTable")
    McR updateTable(){
        HashMap map = new HashMap();
        ArrayList<Map> list = new ArrayList<>();
        HashMap map1 = new HashMap();
        map1.put("textField_mi2tln2x","测试1");
        map1.put("numberField_mi2tln2y",1);
        list.add(map1);
        map.put("tableField_mi2tln2w",list);
        ydService.operateData(YDParam.builder()
                .appType(ydConf.getAppType())
                .systemToken(ydConf.getSystemToken())
                .formInstanceId("FINST-B7D66XA1ODP09SY6N5AB47TE5JAZ2YB5XT2IMNU")
                .updateFormDataJson(JSONObject.toJSONString(map))
                .build(),YDConf.FORM_OPERATION.update);
        return McR.success();
    }

    @PostMapping("/test82")
    McR test82(){

        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .appType("APP_Q6XXLRDPRA0DDRMF3VL4")
                .systemToken("BVG665B18O0Z0EXND3DCR44WX4MC22YQOFQFMCT6")
                .formUuid("FORM-472F0C1BD8DF41FA965A0B4525779B67S421")
                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mfqgmwcw", "S20250070")))
                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
        ArrayList<Map<String, Object>> productlist = new ArrayList<>();
        Map<String, Object> firstData = dataList.get(0);
        Map<String, Object> formData = (Map<String, Object>) firstData.get("formData");
        List<Map<String, Object>> tableData = (List<Map<String, Object>>) formData.get("tableField_mfqgmwe0");
        for (Map<String, Object> row : tableData) {
            Map<String, Object> productMap = new HashMap<>();
            // 提取需要的字段
            productMap.put("qty", row.get("numberField_mfqgmwe6"));           // 数量：12
            productMap.put("unitPrice", row.get("numberField_mfqgmwe9"));     // 单价：1.2
            productMap.put("productCode", row.get("textField_mfqgmwe1"));     // 产品编号：CP202503171676
            productMap.put("productName", row.get("textField_mfqgmwe2"));     // 产品名称：10856磨毛纱卡（轻水洗）(SF)
            productlist.add(productMap);
        }
        System.out.println("结果是：" + productlist);
        return McR.success();
    }

    @PostMapping("/test83")
    McR test83(){
        ArrayList<Map<String, Object>> originalList = new ArrayList<>();
        Map<String, Object> productMap = new HashMap<>();
        productMap.put("qty", 12);           // 数量：12
        productMap.put("unitPrice", 1.2);     // 单价：1.2
        productMap.put("productCode", "CP202503171676");     // 产品编号：CP202503171676
        productMap.put("productName", "10856磨毛纱卡（轻水洗）(SF)");     // 产品名称：10856磨毛纱卡（轻水洗）(SF)
        originalList.add(productMap);
        Map<String, Object> productMap1 = new HashMap<>();
        productMap1.put("qty", 1);           // 数量：12
        productMap1.put("unitPrice", 6.3);     // 单价：6.3
        productMap1.put("productCode", "CP202503171676");     // 产品编号：CP202503171676
        productMap1.put("productName", "纱卡（轻水洗）");     // 产品名称：纱卡（轻水洗）
        originalList.add(productMap1);
        System.out.println("更新前数据：" + originalList);


        ArrayList<Map<String, Object>> updatedList  = new ArrayList<>();
        Map<String, Object> productMap_B = new HashMap<>();
        productMap_B.put("qty", 10);           // 数量：12
        productMap_B.put("unitPrice", 1.2);     // 单价：1.2
        productMap_B.put("productCode", "CP202503171676");     // 产品编号：CP202503171676
        productMap_B.put("productName", "10856磨毛纱卡（轻水洗）(SF)");     // 产品名称：10856磨毛纱卡（轻水洗）(SF)
        updatedList.add(productMap_B);
        Map<String, Object> productMap_B1 = new HashMap<>();
        productMap_B1.put("qty", 2);           // 数量：12
        productMap_B1.put("unitPrice", 6.3);     // 单价：1.2
        productMap_B1.put("productCode", "CP202503171676");     // 产品编号：CP202503171676
        productMap_B1.put("productName", "纱卡（轻水洗）");     // 产品名称：10856磨毛纱卡（轻水洗）(SF)
        updatedList.add(productMap_B1);
        System.out.println("更新后数据：" + updatedList);

        List<Map<String, Object>> changedProducts = new ArrayList<>();
        // 遍历数据，找出发生改变的产品
        for (int i = 0; i < updatedList.size(); i++) {
            Map<String, Object> updatedProduct = updatedList.get(i);
            Map<String, Object> originalProduct = originalList.get(i);

            // 检查数量或单价是否发生变化
            if (!updatedProduct.get("qty").equals(originalProduct.get("qty")) ||
                    !updatedProduct.get("unitPrice").equals(originalProduct.get("unitPrice"))) {

                Map<String, Object> changedProduct = new HashMap<>();
                changedProduct.put("productCode", updatedProduct.get("productCode"));
                changedProduct.put("productName", updatedProduct.get("productName"));
                changedProduct.put("qty_old", originalProduct.get("qty"));
                changedProduct.put("unitPrice_old", originalProduct.get("unitPrice"));

                changedProducts.add(changedProduct);
            }
        }
        System.out.println("变化的值：" + changedProducts);
        return McR.success();
    }

    @PostMapping("/test84")
    McR test84(){
        String formInstanceId_bqb= "";
        List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder()
                .appType("APP_Q6XXLRDPRA0DDRMF3VL4")
                .systemToken("BVG665B18O0Z0EXND3DCR44WX4MC22YQOFQFMCT6")
                .formUuid("FORM-A98E291B02DA400B84C05BAEF735F8AFUBQP")
                .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mi2twkgd", "F3D66D91MEL0EV3TO3YUB6FYUS5S3IC9453IMJ9S")))
                .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();
        if(dataList != null && dataList.size() > 0){
            for(Map M : dataList){
                formInstanceId_bqb = M.get("formInstanceId").toString();
            }
        }
        System.out.println(formInstanceId_bqb);
        return McR.success();
    }

    /*采购订单修改流程发起*/
    @PostMapping("/test85")
    McR test85(){
        HashMap formdata = new HashMap();
        formdata.put("textField_mfqia327",System.currentTimeMillis());
        formdata.put("textField_mfqia328","东莞市元伊纺织有限公司");//供应商变更后的值
        String gys = "如东知品服饰有限公司";//供应商变更前的值
        formdata.put("textareaField_mjghnmvv","{\"textField_mfqia328\":\"<article class=\\\"4ever-xarticle\\\"><p style=\\\"text-align:left;text-indent:0;margin-left:0;margin-top:0;margin-bottom:0\\\"><span style=\\\"color:#FE0300\\\">" + gys + "</span></p></article>\"}");
        ArrayList<Map> list = new ArrayList<>();
        HashMap map1 = new HashMap();
        map1.put("textField_mjsamf3j","童装");
        map1.put("textField_mjsamf3k",null);
        map1.put("textField_mjsamf3l","A款");
        map1.put("textField_mjsamf3m",null);
        map1.put("textField_mjsamf3n","1");
        map1.put("numberField_mjsamf3o",1);
        map1.put("numberField_mjsamf3p",1);
        map1.put("numberField_mjsamf3q",1);
        map1.put("textField_mjsamf3r",null);
        map1.put("textField_mjsamf3s",null);
        map1.put("numberField_mjsamf3t",1);
        map1.put("numberField_mjsamf3u",1);
        map1.put("numberField_mjsamf3v",1);
        list.add(map1);
        formdata.put("tableField_mjsamf3w",list);
        ArrayList<Map> list_AAA = new ArrayList<>();
        HashMap map2 = new HashMap();
        map2.put("textField_mhsj6gtn","1");
        map2.put("textField_mhsj6gto","1");
        map2.put("textField_mhsj6gtp","1");
        map2.put("textField_mhsj6gtq","1");
        map2.put("textField_mhsj6gtr","1");
        map2.put("numberField_mhsj6gts",1);
        map2.put("numberField_mhsj6gtt",1);
        map2.put("numberField_mhsj6gtu",1);
        map2.put("textField_mhtxft3p","1");
        map2.put("textField_mhsj6gtv","1");
        map2.put("numberField_mhsj6gtw",1);
        map2.put("numberField_mhtxft3q",1);
        map2.put("numberField_mhsj6gtx",1);
        list_AAA.add(map2);
        formdata.put("tableField_mhsj6gtm",list_AAA);
        ydClient.operateData(YDParam.builder()
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .formUuid("FORM-7EB4796C4B054EEAA1B0FD52FC54C8387ZUN")
                .userId("3320511511-1158713155")
                .formDataJson(JSON.toJSONString(formdata))
                .build(), YDConf.FORM_OPERATION.start).toString();
        return McR.success();
    }

    /*条件查询宜搭数据*/
    @PostMapping("/test86")
    McR test86(){
        List<Map> list  = (List<Map>) ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-472F0C1BD8DF41FA965A0B4525779B67S421")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch(
                                "textField_mfqgmwcw", "S20260003", "订单编号", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ))))
                        .build()
                ,YDConf.FORM_QUERY.retrieve_list).getData();
        log.info("[销售订单流程档案数据],{}",list);
        String formInstanceId = (String) list.get(0).get("formInstanceId");
        log.info("[销售订单流程的实例ID],{}",formInstanceId);
        Map data = (Map) ydClient.queryData(YDParam.builder().formInstId(formInstanceId)
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

        List<Map<String, Object>> table = (List<Map<String, Object>>) data.get("tableField_mfqgmwe0");
        for (Map<String, Object> row : table) {
            System.out.println("客户: " + data.get("textField_mfqgmwcx"));
            System.out.println("订单号: " + data.get("textField_mfqgmwcw"));
            System.out.println("款号: " + row.get("textField_mfqgmwe1"));
            System.out.println("产品描述: " + row.get("textField_mfqgmwe2"));
            System.out.println("颜色: " + row.get("textField_mk0jz9i1"));
            System.out.println("数量: " + row.get("numberField_mfqgmwe6"));
            System.out.println("销售单价: " + row.get("numberField_mfqgmwe8"));
            System.out.println("销售金额: " + row.get("numberField_mfqgmweb") );
            System.out.println("币别: " + row.get("textField_mk0xio3b")  );
            System.out.println("-----------------------------");
        }
        return McR.success();
    }



}
