package com.malk.fenggefushi.service.Impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonProcessingException;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Slf4j
@Service
public class HeiHuOrderServiceImpl implements HeiHuOrderService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private YDService ydService;
    @Autowired
    private DDConf ddConf;

    private ConcurrentHashMap<String, LocalDateTime> tokenStore = new ConcurrentHashMap<>();


    /*登录获取黑湖登录token*/
    @Override
    public McR HeiHuAccessToken() throws JacksonException {
        final String[] token = {""};
        final boolean[] isHave = {false};
        tokenStore.forEach((k, v) -> {
            if (validateToken(k)) {
                token[0] = k;
                isHave[0] = true;
            }
        });
        if (!isHave[0]) {
            HashMap body = new HashMap();
            body.put("type",1);//type=1，登录方式为工厂代号+账号+密码
            body.put("code","648910");//工厂代号
            body.put("username","FGJK");//账号
            body.put("password","b715db070346a8a59e0eba5da27f8e4938536bb7867e09592326fde2");//密码加密
            HashMap header = new HashMap();
            header.put("X-CLIENT","lite-web");//固定
            header.put("Content-Type","application/json");
            String s = UtilHttp.doPost("https://liteweb.blacklake.cn/api/user/v1/users/_login", header, null, body);
//            String data = new ObjectMapper().readTree(s).get("data").asText();
            token[0] = new ObjectMapper().readTree(s).get("data").asText();
            addToken(token[0],70);
        }

        return McR.success(token[0]);
    }
    /**
     * token存储
     * @param token
     * @param expireHours
     */
    public void addToken(String token, int expireHours) {
        LocalDateTime expirationTime = LocalDateTime.now().plusHours(expireHours);
        tokenStore.put(token, expirationTime);
    }

    /**
     * 清理过期token
     * @param token
     * @return
     */
    public boolean validateToken(String token) {
        LocalDateTime expirationTime = tokenStore.get(token);
        if (expirationTime == null || expirationTime.isBefore(LocalDateTime.now())) {
            tokenStore.remove(token); // 清理过期 Token
            return false;
        }
        return true;
    }
    /*抓取黑湖工单发起宜搭审批流程*/
    @Override
    public McR StartYidaAproval(String OrderNo,String fromUuid) throws JacksonException {
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("orderNo",OrderNo);//订单编码
        /*TODO：对json进行处理*/
        String jsonString  = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        //基础信息字段
        String orderNo = ""; String customerName = "";Long orderTime = null;Long arrivalPlanTime = null;String contractNo = "";
        String operatorName = "";double orderDiscount = 0;String customerCode = "";
        // 提取自定义字段
        String productPhoto = "";//产品照片：182852
        String sampleType = "";//样品类型：69230
        String processType = "";//工艺类型：47768
        String productType = "";//产品类型：47770
        String orderType = "";//订单类型：47771
        String department = "";//部门：47777
        String season = "";//季节：47778
        String expectedOrderQty = "";//预计下单量:59314
        double estimatedUnitPrice = 0;//辅料预估单价：161769
        String purchaseOrderNumber = "";//对应预采购单号：113495
        String qualityConfirmation = "";//品质确认：113119
        String materialCycle = "";//物料周期：113086
        //产品详情字段
        String productCode = "";String productName = "";String productSpec = "";int productStockQty;int qty;
        String productUnitName = "";double unitPrice;double amount;double discount;double taxInclusiveAmount;
        double taxRate;String productArrivalPlanTime = "";String productOriginType = "";
        //其他信息
        String contactName = "";String contactNumbers = "";String contactAddress = "";

        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            // 提取订单基本信息
            orderNo = data.getString("orderNo");//订单编号：orderNo
            customerName = data.getString("customerName");//客户：customerName
            orderTime = data.getLong("orderTime");//下单日期：orderTime
            arrivalPlanTime = data.getLong("arrivalPlanTime");//计划交货日期：arrivalPlanTime
            contractNo = data.getString("contractNo");//合同号：contractNo
            operatorName = data.getString("operatorName");//业务员：operatorName
            orderDiscount = data.getDoubleValue("orderDiscount")*100;//整单折扣：orderDiscount
            customerCode = data.getString("customerCode");//客户名称：customerCode
            //提取其他信息
            contactName = data.getString("contactName");//联系人
            contactNumbers = data.getString("contactNumbers");//联系电话
            contactAddress = data.getString("contactAddress");//联系地址

            JSONArray customFields = data.getJSONArray("customFieldValues");
            if (customFields != null) {
                for (int j = 0; j < customFields.size(); j++) {
                    JSONObject field = customFields.getJSONObject(j);
                    long fieldId = field.getLongValue("fieldId");
                    String value = field.getString("value");
                    switch ((int)fieldId) {
                        case 70931: productPhoto = value; break;
                        case 69230: sampleType = value; break;
                        case 47768: processType = value; break;
                        case 47770: productType = value; break;
                        case 47771: orderType = value; break;
                        case 47777: department = value; break;
                        case 47778: season = value; break;
                        case 59314: expectedOrderQty = value;break;
                        case 161769: estimatedUnitPrice = Double.parseDouble(value);break;
                        case 113495:purchaseOrderNumber = value;break;
                        case 113119:qualityConfirmation = value;break;
                        case 113086:materialCycle = value;break;
                    }
                }
            }

        }
        /*判断订单类型来封装数据*/
        HashMap formdata = new HashMap();
        /*主表*/
        formdata.put("textField_mfqgmwcw",orderNo);
        formdata.put("textField_mfqgmwcx",customerName);
        formdata.put("dateField_mfqgmwcy",orderTime);
        formdata.put("dateField_mfqgmwcz",arrivalPlanTime);
        formdata.put("textField_mfqgmwd5",contractNo);
        formdata.put("textField_mgc0kc5u",operatorName);
        formdata.put("numberField_mfqgmwd7",orderDiscount);
        formdata.put("selectField_mg5y3rcr",orderType);
        formdata.put("textField_mfqgmwdn",processType);
        formdata.put("textField_mfqgmwdo",productType);
        formdata.put("textField_mg5y3rda",department);
        formdata.put("textField_mfqgmwdx",season);
        formdata.put("textField_mfqi6ui8",contactName);
        formdata.put("textField_mfqi6ui9",contactNumbers);
        formdata.put("textField_mfqi6uia",contactAddress);
        List<Map<String, Object>> imageAttachments = new ArrayList<>();
        //处理多照片
        if(productPhoto != null && productPhoto.contains(",")){
            String[] photoUrls = productPhoto.split(",");
            for (String url : photoUrls){
                String trimmedUrl = url.trim();
                if(!trimmedUrl.isEmpty()){
                    Map<String, Object> imageInfo = new HashMap<>();
                    imageInfo.put("name",productType);
                    imageInfo.put("downloadUrl",trimmedUrl);
                    imageInfo.put("previewUrl",trimmedUrl);
                    imageInfo.put("url",trimmedUrl);
                    imageInfo.put("ext","png");
                    imageAttachments.add(imageInfo);
                }
            }
        }else {
            HashMap<String,Object> imageInfo = new HashMap();
            imageInfo.put("name",productType);
            imageInfo.put("downloadUrl",productPhoto);
            imageInfo.put("previewUrl",productPhoto);
            imageInfo.put("url",productPhoto);
            imageInfo.put("ext","png");
            imageAttachments.add(imageInfo);
        }
        formdata.put("imageField_mfqgmwde",imageAttachments);
        if(orderType.equals("样品订单")){
            formdata.put("textField_mfqgmwdh",customerCode);
            formdata.put("textField_mg5y3rdd",sampleType);
            formdata.put("textField_mgc1xl62",expectedOrderQty);
        }else if(orderType.equals("贸易公司订单")){
            formdata.put("numberField_mg5y3rcx",estimatedUnitPrice);
            formdata.put("textField_mg5y3rcy",purchaseOrderNumber);
            formdata.put("textField_mg5y3rcz",qualityConfirmation);
            formdata.put("textField_mg5y3rd0",materialCycle);
            formdata.put("textField_mfqgmwdh",customerCode);
        }else{
            formdata.put("textField_mfqgmwdh",customerCode);
        }
        /*子表*/
        JSONArray products = jsonObject.getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");
        List<Map<String,Object>> tableData = new ArrayList();
        if (products != null) {
            for (int i = 0; i < products.size(); i++) {
                JSONObject detail = products.getJSONObject(i);
                HashMap row = new HashMap();
                //
                String color = "";
                JSONArray array1 = detail.getJSONArray("customFieldValues");
                color = array1.stream()
                        .map(obj -> (JSONObject) obj)
                        .filter(item -> item.getIntValue("fieldId") == 82259)
                        .map(item -> item.getString("value"))
                        .findFirst()
                        .orElse(null);
                ArrayList colorList = new ArrayList();
                colorList.add(color);
                String color_AAA = getProductColor(colorList);
                row.put("textField_mk0jz9i1",color_AAA);//中文颜色
                row.put("textField_mfqgmwe1",detail.getString("productCode"));//产品编号
                row.put("textField_mfqgmwe2",detail.getString("productName"));//产品名称
                row.put("textField_mfqgmwe3",detail.getString("productSpec"));//产品规格
                row.put("textField_mfqgmwe4","0".equals(detail.getString("productOriginType")) ? "自制" : "其它");//产品属性
                row.put("numberField_mfqgmwe5",detail.getIntValue("productStockQty"));//库存数量
                row.put("numberField_mfqgmwe6",detail.getIntValue("qty"));//数量
                row.put("textField_mfqgmwe7",detail.getString("productUnitName"));//单位
                row.put("numberField_mfqgmwe8",detail.getDoubleValue("unitPrice"));//单价
                row.put("numberField_mfqgmwe9",detail.getDoubleValue("amount"));//报价金额
                row.put("numberField_mfqgmwea",detail.getDoubleValue("discount")*100);//折扣
                row.put("numberField_mfqgmweb",detail.getDoubleValue("taxInclusiveAmount"));//折扣
                row.put("numberField_mfqgmwec",detail.getDoubleValue("taxRate"));//税率
                row.put("dateField_mfqgmwed",detail.getLong("arrivalPlanTime"));//产品交货日期
                tableData.add(row);
            }
        }
        formdata.put("tableField_mfqgmwe0",tableData);
        System.out.println(formdata);
        /*发起流程*/
        String userid = getDDToken(operatorName);
        String dd = ydClient.operateData(YDParam.builder()
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .formUuid(fromUuid)
                .userId(userid)
                .formDataJson(JSON.toJSONString(formdata))
                .build(), YDConf.FORM_OPERATION.start).toString();
        log.info("----------【销售订单】已发起----------");
        return McR.success(dd);
    }

    @Override
    public String getDDToken(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;
    }

    @SneakyThrows
    @Override
    public McR startYidaProcurementAproval(String OrderNo,String FormUuType) throws JsonProcessingException {
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("orderCode",OrderNo);//订单编号
        String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//todo:查询采购订单
        JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data");
        //基础信息字段
        String orderCode = "";String shortName = "";Long purchaseTime = null;Long planArrivalTime = null;String purchaserName = "";
        String gysnumber = "";
        double orderDiscount = 0;
        //自定义信息
        String department = "";//部门：186341
        String add = "";//地址：32869
        String SalesOrderNumber = "";//销售订单号：59332
        String PaymentStatus = "";//付款情况：55674
        String PortOfShipment = "";//出运地：42003
        String ShippingStatus = "";//出运状态：42002
        //产品详情字段
        String productCode = "";String productName = "";String productSpec = "";int purchaseNum;
        String unitName  = "";double purchasePrice;double purchaseAmount;double discount;double taxInclusiveAmount;
        double taxRate;Long productArrivalPlanTime = null;
        //其他信息
        String contactName = "";String contactNumber = "";String contactAddress = "";
        for (int i=0;i<dataArray.size();i++){
            JSONObject data = dataArray.getJSONObject(i);
            //提取订单基本信息
            orderCode = data.getString("orderCode");//订单编号：orderCode
            shortName = data.getString("shortName");//供应商：shortName
            gysnumber = data.getString("vendorCode");//供应商编码：gysnumber
            purchaseTime = data.getLong("purchaseTime");//采购日期：purchaseTime
            planArrivalTime = data.getLong("planArrivalTime");//计划到货日期：planArrivalTime
            purchaserName = data.getString("purchaserName");//采购员：purchaserName
            orderDiscount = data.getDouble("orderDiscount");//整单折扣：orderDiscount
            //其他信息
            contactName = data.getString("contactName");//联系人
            contactNumber = data.getString("contactNumber");//联系电话
            contactAddress = data.getString("contactAddress");//联系地址
            //自定义信息
            JSONArray customFields = data.getJSONArray("customFieldValues");
            if(customFields != null){
                for (int j = 0; j < customFields.size(); j++) {
                    JSONObject field = customFields.getJSONObject(j);
                    long fieldId = field.getLongValue("fieldId");
                    String value = field.getString("value");
                    switch ((int)fieldId){
                        case 186341: department = value;break;
                        case 59391:
                            JSONObject associatedDetail = field.getJSONObject("associatedObjectValueDetail");
                            if(associatedDetail != null && !associatedDetail.isEmpty()) {
                                add = associatedDetail.getString("vendorContactAddress");
                            }
                            break;
                        case 59332: SalesOrderNumber = value;break;
                        case 55674: PaymentStatus = value;break;
                        case 42003: PortOfShipment = value;break;
                        case 42002: ShippingStatus = value;break;
                    }
                }
            }
        }
        /*开始封装数据*/
        //采购订单-基础信息
        HashMap formdata = new HashMap();
        formdata.put("textField_mfqia327",orderCode);
        formdata.put("textField_mfqia328",shortName);
        formdata.put("textField_mkaudmn6",gysnumber);
        formdata.put("dateField_mfqia329",purchaseTime);
        formdata.put("dateField_mfqia32a",planArrivalTime);
        formdata.put("employeeField_mfqia32g",getDDToken(purchaserName));
        formdata.put("numberField_mfqia32h",orderDiscount*100);
        //采购订单-自定义
        formdata.put("textField_mfqia32o",department);
        formdata.put("textField_mfqia32q",add);
        formdata.put("textField_mfqia32r",SalesOrderNumber);
        formdata.put("textField_mfqia32x",PaymentStatus);
        formdata.put("textField_mfqia32y",PortOfShipment);
        formdata.put("textField_mfqia32z",ShippingStatus);
        //采购订单-其他信息
        formdata.put("textField_mg4gqve0",contactName);
        formdata.put("textField_mg4gqve1",contactNumber);
        formdata.put("textareaField_mg4gqve2",contactAddress);
        //采购订单-子表
        JSONArray products = JSONObject.parseObject(jsonString).getJSONArray("data").getJSONObject(0).getJSONArray("purchaseSubOrderVOS");
        ArrayList<Map<String,Object>> tableData = new ArrayList();
        if(products != null){
            for (int i = 0; i < products.size(); i++) {
                JSONObject detail = products.getJSONObject(i);
                HashMap row = new HashMap();
                row.put("textField_mfqia332",detail.getString("productCode"));//产品编码
                row.put("textField_mfqia333",detail.getString("productName"));//产品名称
                row.put("textField_mfqia334",detail.getString("productSpec"));//产品规格
                row.put("numberField_mfqia335",detail.getInteger("purchaseNum"));//采购数量
                row.put("textField_mfqia336",detail.getString("unitName"));//单位
                row.put("numberField_mfqia337",detail.getDouble("purchasePrice"));//单价
                row.put("numberField_mg4gqvdm",detail.getDouble("purchaseAmount"));//报价金额
                row.put("numberField_mg4gqvdn",detail.getDouble("discount"));//折扣
                row.put("numberField_mg4gqvdo",detail.getDouble("taxInclusiveAmount"));//含税金额
                row.put("numberField_mg4gqvdp",detail.getDouble("taxRate"));//税率
                row.put("dateField_mg4gqvdq",detail.getLong("productArrivalTime"));//产品到货日期
                tableData.add(row);
            }
        }
        /*todo:新版栏目:客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别、生产工厂、采购单价、采购金额、利润率、美金汇率、辅料预估成本*/
        String customerName = "",styleNumber = "",productDescription = "",color = "",currency = "";
        Double number,unitPrice,salesAmount;
        Double rate = 1.00;Double saletotalAmount = 0.00;Double procuretotalAmount = 0.00;Double saletotalnum =0.00;
        Double estimatedtotalAmount = 0.00;Double estimatedPrice = 0.00;
        Double USDrate = 0.00;Double flygcb = 0.00;
        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");
                if(saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0){
                    orderNumber = saleOrders.get(0).asText();
                }
            }
        }
        HashMap body_A = new HashMap();
        body_A.put("orderNo",orderNumber);
        String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo：查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别
        JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据
        for(int i=0;i<array.size();i++){
            JSONObject data = array.getJSONObject(i);
            customerName = data.getString("customerCode");//客户名称
        }
        ObjectMapper objectMapper2 = new ObjectMapper();
        JsonNode dataNode2 = objectMapper2.readTree(jsonString2).get("data");//主表数据
        for (JsonNode item : dataNode2){
            JsonNode customFieldValues = item.get("customFieldValues");
            for (JsonNode field : customFieldValues){
                JsonNode fieldIdNode = field.get("fieldId");
                if(fieldIdNode != null && fieldIdNode.asInt() == 161769){
                    JsonNode valueNode = field.get("value");
                    if(valueNode != null){
                        estimatedPrice = valueNode.asDouble();//辅料预估单价
                        break;
                    }
                }
            }
        }
        JSONArray products_A = JSONObject.parseObject(jsonString2).getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");//销售订单明细数据
        List<Map<String,String>> tabledata = new ArrayList();
        if(products_A != null){
            for (int i=0;i<products_A.size();i++){
                JSONObject detail = products_A.getJSONObject(i);
                HashMap row = new HashMap();
                row.put("textField_mhsj6gtn",customerName);//todo:客户
                row.put("textField_mhsj6gto",orderNumber);//todo：订单号
                styleNumber = detail.getString("productCode");//款号
                row.put("textField_mhsj6gtp",styleNumber);//todo:款号
                productDescription = detail.getString("productName");//产品描述
                row.put("textField_mhsj6gtq",productDescription);//todo：产品描述
                JSONArray array1 = detail.getJSONArray("customFieldValues");
                color = array1.stream()
                        .map(obj -> (JSONObject) obj)
                        .filter(item -> item.getIntValue("fieldId") == 82259)
                        .map(item -> item.getString("value"))
                        .findFirst()
                        .orElse(null);
                ArrayList colorList = new ArrayList();
                colorList.add(color);
                String color_AAA = getProductColor(colorList);
                row.put("textField_mhsj6gtr",color_AAA);//todo：颜色
                number = detail.getDoubleValue("qty");//数量
                row.put("numberField_mhsj6gts",number);//todo：数量
                saletotalnum = saletotalnum + number;
                unitPrice = detail.getDoubleValue("unitPrice");//销售单价
                row.put("numberField_mhsj6gtt",unitPrice);//todo：销售单价
                salesAmount = number * unitPrice;//销售金额
                row.put("numberField_mhsj6gtu",salesAmount);//todo：销售金额
                String customFieldValues = detail.getString("customFieldValues");
                ObjectMapper mapper = new ObjectMapper();
                JsonNode jsonarray = mapper.readTree(customFieldValues);
                for (JsonNode node : jsonarray){
                    if(node.get("fieldId").asInt() == 47919){
                        currency = node.get("value").asText();
                    }else if (node.get("fieldId").asInt() == 165251){
                        rate = node.get("value").asDouble();
                        USDrate = rate;
                    }else if (node.get("fieldId").asInt() == 161783) {
                        flygcb = node.get("value").asDouble();
                    }
                }
                row.put("textField_mhtxft3p",currency);//todo：币别
                row.put("numberField_ml85btkc",USDrate);//todo:美金汇率
                row.put("numberField_ml85btkd",flygcb);//todo:辅料预估成本
                //下面是采购订单的明细数据
                row.put("textField_mhsj6gtv",shortName);//todo：生产工厂
                for(int j=0;j<products.size();j++){
                    if(styleNumber.equals(products.getJSONObject(j).getString("productCode"))){
                        //找到对应的采购一行数据
                        row.put("numberField_mhsj6gtw",products.getJSONObject(j).getDouble("purchasePrice"));//todo:采购单价
                        row.put("numberField_mhtxft3q",products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购数量
                        row.put("numberField_mhsj6gtx",products.getJSONObject(j).getDouble("purchasePrice") * products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购金额
                    }
                }
                //销售总金额  币别：人民币 数量*单价    美元：数量*单价*美元汇率
                saletotalAmount  = (currency.equals("CNY") ? number*unitPrice : number*unitPrice*rate) + saletotalAmount;
                //采购订单总金额  均为人民币不存在汇率
                procuretotalAmount = products.getJSONObject(i).getDouble("purchasePrice") * products.getJSONObject(i).getDouble("purchaseNum") + procuretotalAmount;
                tabledata.add(row);
            }
        }
        //预估辅料总成本   订单总数量*辅料预估单价
        estimatedtotalAmount = saletotalnum * estimatedPrice;
        //毛利率 （销售总金额-采购订单总金额-辅料预估总成本）/（销售总金额）
        double margin = (saletotalAmount - procuretotalAmount - estimatedtotalAmount) / saletotalAmount;
        formdata.put("numberField_mhvp9qy0",margin);
        formdata.put("tableField_mhsj6gtm",tabledata);
        System.out.println(formdata);
        /*发起流程*/
        String userId = getDDToken(purchaserName);
        String dd = ydClient.operateData(YDParam.builder()
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .formUuid(FormUuType)
                .userId(userId)
                .formDataJson(JSON.toJSONString(formdata))
                .build(), YDConf.FORM_OPERATION.start).toString();
        log.info("------------【采购订单】审批已发起-----------");
        return McR.success(dd);
    }

    @SneakyThrows
    @Override
    public McR SyncOrderStatus(String formInstanceId,String Approvalresult) throws JsonProcessingException {
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        Map formdata = ydClient.queryData(YDParam.builder().formInstId(formInstanceId)
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        HashMap body = new HashMap();
        body.put("orderNo",formdata.get("textField_mfqgmwcw"));//订单编号
        body.put("customerCode",formdata.get("textField_mfqgmwdh"));//客户编号(名称)
        String aa = formdata.get("dateField_mfqgmwcy").toString();
        String xdrq = Instant.ofEpochMilli(Long.parseLong(aa))
                .atZone(ZoneId.of("Asia/Shanghai"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        body.put("orderTime",xdrq);//下单日期
        String bb = formdata.get("dateField_mfqgmwcz").toString();
        String jhjfrq = Instant.ofEpochMilli(Long.parseLong(bb))
                .atZone(ZoneId.of("Asia/Shanghai"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        body.put("arrivalPlanTime",jhjfrq);//计划交付日期
        body.put("operatorName",formdata.get("textField_mgc0kc5u"));//业务人员名称
        ArrayList<Map<String,String>> customFiled = new ArrayList();
        HashMap field = new HashMap();
        field.put("name","销售订单钉钉审批状态");
        field.put("value",Approvalresult);//审批状态
        customFiled.add(field);
        body.put("saleOrderCustomFieldsValue",customFiled);//订单状态明细
        String dd = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/update", header, null, body);
        log.info("---------【回传销售订单状态完成】----------");
        return McR.success(dd);
    }

    @SneakyThrows
    @Override
    public McR SyncPurchaseOrderStatus(String formInstanceId,String Approvalresult) throws JsonProcessingException {
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        Map formdata = ydClient.queryData(YDParam.builder().formInstId(formInstanceId)
                .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                .userId(ddConf.getOperator()).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        String jsonString  = formdata.get("tableField_ml7ch2pj").toString();
        JSONArray tableField_ml7ch2pj  = JSON.parseArray(jsonString);
        for (int i=0;i<tableField_ml7ch2pj.size();i++){
            String poNumber = tableField_ml7ch2pj.getJSONObject(i).getString("textField_ml7ch2pk");//拿到采购订单号
            HashMap body = new HashMap();
            body.put("orderCode",poNumber);//订单编号
            String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//todo:查询采购订单
            JSONArray dataArray = JSONObject.parseObject(jsonString2).getJSONArray("data");
            for (int k=0;k<dataArray.size();k++) {
                JSONObject data = dataArray.getJSONObject(k);
                //提取订单基本信息 并赋值
                HashMap body1 = new HashMap();
                body1.put("orderCode",data.getString("orderCode"));//订单编号：orderCode
                body1.put("vendorCode",data.getString("vendorCode"));//供应商编码：gysnumber
                String aa = data.getLong("purchaseTime").toString();
                String purchaseTime = Instant.ofEpochMilli(Long.parseLong(aa))
                        .atZone(ZoneId.of("Asia/Shanghai"))
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                body1.put("purchaseTime",purchaseTime);//采购日期：purchaseTime
                String bb = data.getLong("planArrivalTime").toString();
                String planArrivalTime = Instant.ofEpochMilli(Long.parseLong(bb))
                        .atZone(ZoneId.of("Asia/Shanghai"))
                        .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                body1.put("planArrivalTime",planArrivalTime);//计划到货日期：planArrivalTime
                ArrayList<Map<String,String>> customFiled = new ArrayList();
                HashMap field = new HashMap();
                field.put("name","采购订单钉钉审批状态");
                field.put("value",Approvalresult);//审批状态
                customFiled.add(field);
                body1.put("purchaseOrderCustomFieldsValue",customFiled);
                UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/update", header, null, body1);
                log.info("---------【回传,{},采购订单状态完成】-----------",data.getString("orderCode"));
            }
        }
        return McR.success();
    }

    @Override
    @SneakyThrows
    public McR salesAproval(Map body) throws JacksonException {
        StartYidaAproval(body.get("order").toString(),"FORM-472F0C1BD8DF41FA965A0B4525779B67S421");//todo:发起销售订单流程档案
        HashMap formdata = new HashMap();
        formdata.put("textField_mgq90lwf",body.get("order").toString());
        Instant now = Instant.now();
        long timestampMillis = now.toEpochMilli();
        formdata.put("dateField_mgq90lwg",timestampMillis);
        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();//todo：销售合同档案
        log.info("[销售订单流程发起，销售汇总表已同步]");
        return McR.success();
    }

    @Override
    @SneakyThrows
    public McR Procurement(Map body_new) throws JacksonException {
        //1、每次创建的时候才去查询宜搭采购订单底表
        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 = "";
        ArrayList<String> procureList = new ArrayList();//采购订单汇总-订单号
        for (Map li : dataList) {
            i++;
            jsonStr = li.get("formData").toString();
            String orderNumber  = new ObjectMapper().readTree(jsonStr).get("textField_mgq932hi").asText();
            procureList.add(orderNumber);
        }
        //2、其次就是在查询下黑湖工单，时间为当前时间
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime todayMidnight = LocalDate.now().atStartOfDay();
        String formattedToday = todayMidnight.format(formatter);
        body.put("createdAtGte",formattedToday);//创建时间大于等于
        /*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 = "";//销售订单编号
        List<String> orderNumberList = new ArrayList<>();//todo：存在关联多个销售订单
        String purchaseOrderNo = "";//采购订单编号
        String orderType = "";//销售订单类型

        if (dataNode != null && dataNode.isArray()) {
            for (JsonNode item : dataNode) {
                JsonNode orderNoNode = item.get("orderCode");
                if (orderNoNode != null) {
                    purchaseOrderNo = orderNoNode.asText();
                }
                JsonNode saleOrders = item.get("relationSaleOrders");
                if (saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0) {
                    for (int j = 0; j < saleOrders.size(); j++) {
                        orderNumberList.add(saleOrders.get(j).asText());
                    }
                    orderNumber = saleOrders.get(0).asText();
                }
                //每次查询下是否为“样品订单”推过来的采购订单
                HashMap body2 = new HashMap();
                body2.put("orderNo",orderNumber);
                String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body2);//TODO: 查询销售订单
                ObjectMapper objectMapper2 = new ObjectMapper();
                JsonNode dataNode2 = objectMapper2.readTree(jsonString2).get("data");
                if(dataNode2 != null && dataNode2.isArray()){
                    for (JsonNode item2 : dataNode2){
                        JsonNode customFieldValues = item2.get("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) {
                                        orderType = valueNode.asText();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (orderNoNode != null && !orderType.equals("样品订单") ) {
                    orderNoList.add(orderNoNode.asText());
                }
            }
        }
        //3、两者比较[procureList\orderList]，差别的一个发起审批流程，排除订单类型为“样品订单”外
        Set<String> orderNoSet = new HashSet<>(orderNoList);
        Set<String> procureSet = new HashSet<>(procureList);
        List<String> onlyInSalesList = new ArrayList<>();
        for (String item : procureList) {
            if (!orderNoSet.contains(item)) {
                onlyInSalesList.add(item);
            }
        }

        List<String> onlyInOrderNoList = new ArrayList<>();
        for (String item : orderNoList) {
            if (!procureSet.contains(item)) {
                onlyInOrderNoList.add(item);
            }
        }
        System.out.println("要发起的采购订单: " + onlyInOrderNoList);//这里的orderNoList中的元素可能为[]，为空的话就不发起流程
        //4、非样品订单发起宜搭审批流程
        if(orderType.equals("样品订单")){
            HashMap formdata2 = new HashMap();
            formdata2.put("textField_mgq932hi",purchaseOrderNo);
            formdata2.put("textField_mhyh7ues",orderNumber);
            Instant now = Instant.now();
            long timestampMillis = now.toEpochMilli();
            formdata2.put("dateField_mgq932hj",timestampMillis);
            ydClient.operateData(YDParam.builder()
                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                    .formUuid("FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91")
                    .userId("3320511511-1158713155")
                    .formDataJson(JSON.toJSONString(formdata2))
                    .build(),YDConf.FORM_OPERATION.create).toString();
            log.info("[样品订单流程不发起，采购汇总表已同步]");
        }

        for (int j=0;j< onlyInOrderNoList.size();j++){
            String orderNo = onlyInOrderNoList.get(j);
            startYidaProcurementAproval(orderNo,"FORM-5BD5B7F6C8B249A5ADD6E1C82DEAA2C086FY");
            //5、发起流程写入采购订单汇总表
            HashMap formdata = new HashMap();
            formdata.put("textField_mgq932hi",orderNo);
            formdata.put("textField_mhyh7ues",orderNumber);
            Instant now = Instant.now();
            long timestampMillis = now.toEpochMilli();
            formdata.put("dateField_mgq932hj",timestampMillis);

            ydClient.operateData(YDParam.builder()
                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                    .formUuid("FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91")
                    .userId("3320511511-1158713155")
                    .formDataJson(JSON.toJSONString(formdata))
                    .build(), YDConf.FORM_OPERATION.create).toString();
            log.info("[采购订单流程发起，采购汇总表已同步]");
        }
        //6、样品订单也要写入采购订单汇总表内
        if(orderType.equals("样品订单")){
            HashMap formdata2 = new HashMap();
            formdata2.put("textField_mgq932hi",purchaseOrderNo);
            formdata2.put("textField_mhyh7ues",orderNumber);
            Instant now = Instant.now();
            long timestampMillis = now.toEpochMilli();
            formdata2.put("dateField_mgq932hj",timestampMillis);
            ydClient.operateData(YDParam.builder()
                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                    .formUuid("FORM-56E11C4FAB6E4FB594169BB779736FF0ZG91")
                    .userId("3320511511-1158713155")
                    .formDataJson(JSON.toJSONString(formdata2))
                    .build(),YDConf.FORM_OPERATION.create).toString();
            log.info("[样品订单流程不发起，采购汇总表已同步]");
        }
        return McR.success();
    }

    // 定义核心字段KEY数组
    private static final List<String> CORE_KEY_LIST=Arrays.asList("numberField_mfqgmwe6","numberField_mfqgmwe8","textField_mk0jz9i1");//数量 单价 中文颜色
    private static final String MATCH_KEY = "textField_mhsj6gtp";

    @Override
    public McR salesUpdate(Map body_new) throws JacksonException {
        /*todo:1、修改销售明细的颜色、数量、单价（已实现） 2、修改计划交货日期（进行中）*/

        // 查询销售订单明细
        HashMap head = new HashMap();
        head.put("X-AUTH",HeiHuAccessToken().getData().toString());
        head.put("Content-Type","application/json");
        HashMap bodyy = new HashMap();
        bodyy.put("orderNo",body_new.get("order").toString());
        String saleDetails = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", head, null, bodyy);
        JSONArray datas = JSONObject.parseObject(saleDetails).getJSONArray("data");
        JSONArray prods = JSONObject.parseObject(saleDetails).getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");
        List<Map<String,Object>> tabledata = new ArrayList();
        String customerCode = "";String orderNo = "";
        String arrivalPlanTime_New = "";
        for (int b=0;b< datas.size();b++){
            JSONObject object = datas.getJSONObject(b);
            customerCode = object.getString("customerCode");//客户
            orderNo = object.getString("orderNo");//订单号
            arrivalPlanTime_New = object.getString("arrivalPlanTime");//计划交货日期
        }
        for (int a=0;a< prods.size();a++){
            JSONObject detail = prods.getJSONObject(a);
            HashMap row = new HashMap();
            String productCode = detail.getString("productCode");//款号
            String productName = detail.getString("productName");//产品描述
            Double qty = detail.getDouble("qty");//数量
            Double unitPrice = detail.getDouble("unitPrice");//单价
            double saleamount = detail.getDouble("qty") * detail.getDouble("unitPrice");//销售金额
            String color = "";
            JSONArray array1 = detail.getJSONArray("customFieldValues");
            color = array1.stream()
                    .map(obj -> (JSONObject) obj)
                    .filter(item -> item.getIntValue("fieldId") == 82259)
                    .map(item -> item.getString("value"))
                    .findFirst()
                    .orElse(null);
            String currency = "";
            currency = array1.stream()
                    .map(obj -> (JSONObject) obj)
                    .filter(item -> item.getIntValue("fieldId") == 47919)
                    .map(item -> item.getString("value"))
                    .findFirst()
                    .orElse(null); //币别
            ArrayList colorList = new ArrayList();
            colorList.add(color);
            String color_AAA = getProductColor(colorList);//颜色
            row.put("textField_mhsj6gtn",customerCode);
            row.put("textField_mhsj6gto",orderNo);
            row.put("textField_mhsj6gtp",productCode);
            row.put("textField_mhsj6gtq",productName);
            row.put("textField_mk4rrk35",color_AAA);//
            row.put("numberField_mk4rrk3b",qty);//
            row.put("numberField_mk4rrk3d",unitPrice);//
            row.put("numberField_mk4rrk3e",saleamount);//
            row.put("textField_mhtxft3p",currency);
            tabledata.add(row);
        }
        // 销售订单明细转换为宜搭表单字段的 formData
        HashMap fromdata = new HashMap();
        fromdata.put("tableField_mhsj6gtm",tabledata);
        log.info("[修改后的销售明细值],{}",tabledata);
        // 查询修改前的宜搭数据 formData
        List<Map<String,Object>> tabledata_yida = new ArrayList();
        List<Map> list  = (List<Map>) ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-472F0C1BD8DF41FA965A0B4525779B67S421")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch(
                                "textField_mfqgmwcw", orderNo, "订单编号", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ))))
                        .build()
                ,YDConf.FORM_QUERY.retrieve_list).getData();
        String formInstanceId = (String) list.get(0).get("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();
        String arrivalPlanTime_Old = data.get("dateField_mfqgmwcz").toString();
        List<Map<String, Object>> table = (List<Map<String, Object>>) data.get("tableField_mfqgmwe0");
        for (Map<String, Object> row : table) {
            HashMap row_yida = new HashMap();
            row_yida.put("textField_mhsj6gtn",data.get("textField_mfqgmwcx"));
            row_yida.put("textField_mhsj6gto",data.get("textField_mfqgmwcw"));
            row_yida.put("textField_mhsj6gtp",row.get("textField_mfqgmwe1"));
            row_yida.put("textField_mhsj6gtq",row.get("textField_mfqgmwe2"));
            row_yida.put("textField_mk4rrk35",row.get("textField_mk0jz9i1"));
            row_yida.put("numberField_mk4rrk3b",row.get("numberField_mfqgmwe6"));
            row_yida.put("numberField_mk4rrk3d",row.get("numberField_mfqgmwe8"));
            row_yida.put("numberField_mk4rrk3e",row.get("numberField_mfqgmweb"));
            row_yida.put("textField_mhtxft3p",row.get("textField_mk0xio3b"));
            tabledata_yida.add(row_yida);
        }
        HashMap fromdata_yida = new HashMap();
        fromdata_yida.put("tableField_mhsj6gtm",tabledata_yida);
        log.info("[修改前的销售明细值],{}",tabledata_yida);
        // 对比获取变更的KEY列表 AI
        List<Map<String, Object>> result = compareAndGetChanges(tabledata_yida, tabledata);
        log.info("[变更的值],{}",result);
        // 包含 发起宜搭审批
        StartYidaAproval(orderNo,"FORM-9A44F1DA0F5B4D319A6D06692767564CFHDS");
        //查找销售订单变更审批的实例id
        List<Map> lis  = (List<Map>) ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-9A44F1DA0F5B4D319A6D06692767564CFHDS")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch(
                                "textField_mfqgmwcw", orderNo, "订单编号", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ))))
                        .build()
                ,YDConf.FORM_QUERY.retrieve_list).getData();
        String instanceId = (String) lis.get(0).get("formInstanceId");
        log.info("[销售订单审批变更的实例id],{}",instanceId);
        //把变更的数据整理去走operateData方法
        Map<String, List<Map<String, Object>>> grouped = result.stream()
                .collect(Collectors.groupingBy(m -> (String) m.get("billNo")));
        List<Map<String, Object>> ret = new ArrayList<>();
        for (List<Map<String, Object>> group : grouped.values()) {
            Map<String, Object> merged = new LinkedHashMap<>(); // 保持插入顺序（可选）
            for (Map<String, Object> item : group) {
                String field = (String) item.get("field");
                Object oldValue = item.get("oldValue");
                merged.put(field, oldValue);
            }
            ret.add(merged);
        }
        System.out.println("即将插入的数据" + ret);
        Map formdata = new HashMap();
        if(!arrivalPlanTime_New.equals(arrivalPlanTime_Old)){
            formdata.put("textareaField_mjghnmvv",AAAA(arrivalPlanTime_Old));
        }
        formdata.put("tableField_mk4rrk3k",ret);
        ydClient.operateData(YDParam.builder()
                .formInstanceId(instanceId)
                .updateFormDataJson(JSONObject.toJSONString(formdata))
                .build(),YDConf.FORM_OPERATION.update);
        return McR.success();
    }


    /**
     * 对比新旧列表，返回所有变更项（Java 8 兼容）
     *
     * 返回格式：List<Map<String, Object>>
     * 每个 Map 包含：
     *   - "billNo": 单号（textField_mhsj6gtp 的值）
     *   - "field": 变更的字段名
     *   - "oldValue": 旧值
     *   - "newValue": 新值
     */
    public static List<Map<String, Object>> compareAndGetChanges(
            List<Map<String, Object>> oldList,
            List<Map<String, Object>> newList) {

        Map<String, Map<String, Object>> oldIndex = toIndex(oldList);
        Map<String, Map<String, Object>> newIndex = toIndex(newList);

        List<Map<String, Object>> changes = new ArrayList<>();

        for (String billNo : oldIndex.keySet()) {
            Map<String, Object> oldRow = oldIndex.get(billNo);
            Map<String, Object> newRow = newIndex.get(billNo);
            if (newRow == null) {
                continue;
            }

            for (Map.Entry<String, Object> entry : oldRow.entrySet()) {
                String field = entry.getKey();
                Object oldValue = entry.getValue();
                Object newValue = newRow.get(field);

                if (!Objects.equals(oldValue, newValue)) {
                    Map<String, Object> change = new HashMap<>();
                    change.put("billNo", billNo);
                    change.put("field", field);
                    change.put("oldValue", oldValue);
                    change.put("newValue", newValue);
                    changes.add(change);
                }
            }
        }

        return changes;
    }

    // 构建以 textField_mhsj6gtp 为 key 的索引
    private static Map<String, Map<String, Object>> toIndex(List<Map<String, Object>> list) {
        Map<String, Map<String, Object>> index = new HashMap<>();
        for (Map<String, Object> row : list) {
            if (row.containsKey(MATCH_KEY)) {
                String key = String.valueOf(row.get(MATCH_KEY));
                // 避免重复 key 覆盖（保留第一个）
                if (!index.containsKey(key)) {
                    index.put(key, row);
                }
            }
        }
        return index;
    }

    /*返回备注信息*/
    public static String AAAA(String ccc){
        String aa = "";
        String dd = Instant.ofEpochMilli(Long.parseLong(ccc))
                .atZone(ZoneId.of("Asia/Shanghai"))
                .format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        aa = "{\"dateField_mfqgmwcz\":\"<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\\\">" + dd +"</span></p></article>\"}";
        return aa;
    }

    @Override
    public String getProductColor(List list) throws JacksonException {
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("type","PRODUCT");
        body.put("ids",list);
        String doPost = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/customField/associatedBusinessObject/entity/queryList", header, null, body);
        JSONObject jsonObject = JSONObject.parseObject(doPost);
        JSONArray dataArray = jsonObject.getJSONArray("data");
        System.out.println(dataArray);
      /*  String productName = "";
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            productName = data.getString("productName");
        }*/

        String colorValue = "";
        if (dataArray != null && dataArray.size() > 0) {
            JSONObject data = dataArray.getJSONObject(0);
            JSONObject customFieldValues = data.getJSONObject("customFieldValues");
            if (customFieldValues != null) {
                // 直接获取指定字段的值
                colorValue = customFieldValues.getString("product1741831360685211");
            }
        }

        return colorValue;
    }

    @SneakyThrows
    @Override
    public McR purchaseSchedule(List<Map<String, Object>> dataList) {
        HashMap header = new HashMap();
        header.put("X-AUTH", HeiHuAccessToken().getData().toString());
        header.put("Content-Type", "application/json");
        String targetValue = "合同确认，提交审批";
        String targetValueUpdate = "合同修改，修改审批";

        // 定义一个字符串集合，默认包含两个值："默认值1"、"默认值2"
        List<String> targetValues = new ArrayList() {{
            add("合同确认，提交审批");
            add("合同修改，修改审批");
        }};
        Map<String, List<String>> purchaserOrderCodes = new HashMap<>();


        if (ObjectUtil.isNotNull(dataList) && dataList.size() > 0) {
            for (Map<String, Object> item : dataList) {
                String purchaserName = (String) item.get("purchaserName");
                if (purchaserName == null) purchaserName = "未知";

//                boolean hasTargetStatus = false;
                List<Map<String, Object>> customFieldValues = (List<Map<String, Object>>) item.get("customFieldValues");
                if (customFieldValues != null) {
                    for (Map<String, Object> field : customFieldValues) {
                        if (targetValue.equals(field.get("value") ) || targetValueUpdate.equals(field.get("value"))) {
                            System.out.println("合同状态类型："+field.get("value"));
//                        if (targetValue.equals(field.get("value"))) {
//                            hasTargetStatus = true;
                            String orderCode = (String) item.get("orderCode");
                            if (orderCode != null) {
                                purchaserOrderCodes.computeIfAbsent(purchaserName + "-" + field.get("value"), k -> new ArrayList<>()).add(orderCode);
                            }
                            break;
                        }
                    }
                }

            }

        }

        // 输出所有采购员的待审批订单
        System.out.println("========== 所有采购员的待审批订单统计 ==========");

        if (purchaserOrderCodes.isEmpty()) {
            System.out.println("没有找到钉钉审批状态为'" + targetValue + "'的订单");
        } else {
            int totalPurchasers = purchaserOrderCodes.size();
            int totalOrders = purchaserOrderCodes.values().stream().mapToInt(List::size).sum();

            System.out.println("共找到 " + totalOrders + " 个待审批订单");
            System.out.println("涉及 " + totalPurchasers + " 位采购员");
            System.out.println();

            // 输出每个采购员的情况
            for (Map.Entry<String, List<String>> entry : purchaserOrderCodes.entrySet()) {
                String[] split = entry.getKey().split("-");
                String purchaserName = split[0];
                String type = split[1];
                List<String> orderCodes = entry.getValue();
                int orderCount = orderCodes.size();

                System.out.println("采购员: " + purchaserName);
                System.out.println("待审批订单数量: " + orderCount);
                System.out.println("审批类型: " + type);

                if (orderCount > 1) {
                    System.out.println("⚠️  注意：该采购员有 " + orderCount + " 个待审批订单");
                }
                System.out.println("订单编号: " + String.join(", ", orderCodes));
            }

            // 按订单数量排序输出
            System.out.println("========== 按待审批订单数量排序 ==========");
            purchaserOrderCodes.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
                    .forEach(entry -> {
                        String[] split = entry.getKey().split("-");
                        String purchaserName = split[0];
                        String type = split[1];
                        List<String> orderCodes = entry.getValue();

                        System.out.println(purchaserName + " (" + orderCodes.size() + "个): " +
                                String.join(", ", orderCodes));

                        // ========== 修改点1：声明两个列表分别存储不同毛利率的订单数据 ==========
                        // 针对同一个采购员，遍历下面的订单编号
                        System.out.println("开始处理采购员 " + purchaserName + " 的 " + orderCodes.size() + " 个待审批订单");

                        // 高毛利率表单数据 (mlv >= 0.15)
                        HashMap formdataHigh = new HashMap();
                        List<Map<String,Object>> tabledataHigh = new ArrayList();

                        // 低毛利率表单数据 (mlv < 0.15)
                        HashMap formdataLow = new HashMap();
                        List<Map<String,Object>> tabledataLow = new ArrayList();

                        // ========== 修改点2：为每个订单创建临时存储列表 ==========
                        // 用于暂存每个订单的明细数据，等计算出毛利率后再决定添加到哪个列表
//                        Map<String, List<Map<String, String>>> tempOrderDataMap = new HashMap<>();
                        // 用于存储每个订单的汇总数据，用于计算毛利率
//                        Map<String, Map<String, Double>> orderSummaryForMlv = new HashMap<>();
                        List<String> oldIds = new ArrayList<>();

                        for (String orderCode : orderCodes) {
                            System.out.println("正在处理订单: " + orderCode);
                            if (type.equals(targetValueUpdate)){
                                oldIds.add(orderCode);
                            }
                            // ========== 修改点3：为当前订单创建临时数据存储 ==========
                            List<Map<String, Object>> currentOrderRows = new ArrayList<>();
                            double orderTotalSalesAmount = 0.0;
                            double orderTotalPurchaseAmount = 0.0;
                            double orderTotalFlygcb = 0.0;

                            //todo:查询订单的销售订单 | 客户  销售订单号  款式  产品描述  颜色 | 数量  销售单价  销售金额 | 币别 美金汇率 辅料预估成本 销售总金额 税率
                            String customerName = "",orderNumber ="",styleNumber ="",productDescription = "",color = "";
                            Double number,unitPrice,salesAmount;
                            String currency = ""; Double USDrate = 0.00; Double flygcb = 0.00; Double saletotalAmount = 0.00;
                            Double estimatedPrice = 0.00;//辅料预估单价
                            double orderFax = 1.13;

                            HashMap body = new HashMap();
                            body.put("orderCode",orderCode);//订单编号
                            String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);
                            //todo:查询采购订单 生产工厂（供应商）
                            String shortName = "";
                            JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data");
                            for (int i=0;i<dataArray.size();i++) {
                                JSONObject data = dataArray.getJSONObject(i);
                                shortName = data.getString("shortName");//供应商：shortName
                            }
                            JSONArray products = JSONObject.parseObject(jsonString).getJSONArray("data").getJSONObject(0).getJSONArray("purchaseSubOrderVOS");
                            ObjectMapper objectMapper = new ObjectMapper();
                            JsonNode rootNode = null;
                            try {
                                rootNode = objectMapper.readTree(jsonString);
                            } catch (JsonProcessingException e) {
                                throw new RuntimeException(e);
                            }
                            JsonNode dataNode = rootNode.get("data");
                            if(dataNode != null && dataNode.isArray()){
                                for(JsonNode item : dataNode){
                                    JsonNode orderNoNode = item.get("orderCode");
                                    JsonNode saleOrders = item.get("relationSaleOrders");
                                    if(saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0){
                                        orderNumber = saleOrders.get(0).asText();//销售订单号
                                    }
                                    JsonNode customFieldValues = item.get("customFieldValues");
                                    for (JsonNode field : customFieldValues) {
                                        JsonNode fieldIdNode = field.get("fieldId");
                                        if (fieldIdNode != null && fieldIdNode.asInt() == 503296) {
                                            JsonNode valueNode = field.get("value");
                                            if (valueNode != null) {
                                                orderFax = valueNode.asDouble() == 0.0 ? 1.13 : valueNode.asDouble() + 1;//税率
                                                log.info("采购订单税率：{}",orderFax);
                                            }
                                        }
                                    }
                                }
                            }

                            HashMap body_A = new HashMap();
                            body_A.put("orderNo",orderNumber);
                            String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo：查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别
                            log.info("saleOrder/queryList2:{}",jsonString2);
                            JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据
                            String finalOrderNumber = orderNumber;
                            boolean isSample = false;//销售订单若为样品订单则不发起钉钉流程
                            for(int i=0;i<array.size();i++){
                                JSONObject data = array.getJSONObject(i);
                                customerName = data.getString("customerCode");//客户
                                if (finalOrderNumber.equals(data.getString("contractNo"))){
                                    log.info("customer123:{}",customerName);
                                }
                            }
                            ObjectMapper objectMapper2 = new ObjectMapper();
                            JsonNode dataNode2 = null;//主表数据
                            List<JsonNode> list = new ArrayList<>();
                            try {
                                dataNode2 = objectMapper2.readTree(jsonString2).get("data");
                                list = StreamSupport.stream(dataNode2.spliterator(), false)
                                        .filter(node -> finalOrderNumber.equals(node.get("orderNo").asText()))
                                        .collect(Collectors.toList());
                                for (JsonNode item : list){
                                    JsonNode customFieldValues = item.get("customFieldValues");
                                    for (JsonNode field : customFieldValues){
                                        JsonNode fieldIdNode = field.get("fieldId");
                                        if(fieldIdNode != null && fieldIdNode.asInt() == 161769){
                                            JsonNode valueNode = field.get("value");
                                            if(valueNode != null){
                                                estimatedPrice = valueNode.asDouble();//辅料预估单价
                                            }
                                        }
                                        else if(fieldIdNode != null && fieldIdNode.asInt() == 47771){
                                            JsonNode valueNode = field.get("value");
                                            log.info("销售订单类型:{}",valueNode.asText());
                                            if("样品订单".equals(valueNode.asText())){
                                                isSample = true;
                                            }
                                        }
                                    }
                                }
                            } catch (JsonProcessingException e) {
                                e.printStackTrace();
                            }

                            if (!isSample){
                                JSONArray products_A = JSONObject.parseObject(jsonString2).getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");//销售订单明细数据

                                if(products_A != null) {
                                    for (int i = 0; i < products_A.size(); i++) {
                                        JSONObject detail = products_A.getJSONObject(i);
                                        HashMap row = new HashMap();
                                        row.put("textField_mm2t71jm",orderCode);//todo：采购订单单号
                                        row.put("textField_ml6g7k5e", customerName);//todo:客户
                                        row.put("textField_ml6g7k5f", orderNumber);//todo：订单号

                                        styleNumber = detail.getString("productCode");//款号
                                        row.put("textField_ml7c3yhq", styleNumber);//todo:款号

                                        productDescription = detail.getString("productName");//产品描述
                                        row.put("textField_ml7c3yhr", productDescription);//todo：产品描述

                                        JSONArray array1 = detail.getJSONArray("customFieldValues");
                                        color = array1.stream()
                                                .map(obj -> (JSONObject) obj)
                                                .filter(item -> item.getIntValue("fieldId") == 82259)
                                                .map(item -> item.getString("value"))
                                                .findFirst()
                                                .orElse(null);
                                        ArrayList colorList = new ArrayList();
                                        colorList.add(color);
                                        String color_AAA = null;
                                        try {
                                            color_AAA = getProductColor(colorList);
                                        } catch (JacksonException e) {
                                            e.printStackTrace();
                                        }
                                        row.put("textField_ml7c3yhs", color_AAA);//todo：颜色

                                        number = detail.getDoubleValue("qty");//数量
                                        row.put("numberField_ml7c3yht", number);//todo：数量

                                        unitPrice = detail.getDoubleValue("unitPrice");//销售单价
                                        row.put("numberField_ml7c3yhu", unitPrice);//todo：销售单价

                                        salesAmount = number * unitPrice;//销售金额
                                        row.put("numberField_ml7c3yhv", salesAmount);//todo：销售金额
                                        String customFieldValues = detail.getString("customFieldValues");
                                        ObjectMapper mapper = new ObjectMapper();
                                        JsonNode jsonarray = null;
                                        try {
                                            jsonarray = mapper.readTree(customFieldValues);
                                        } catch (JsonProcessingException e) {
                                            throw new RuntimeException(e);
                                        }
                                        for (JsonNode node : jsonarray) {
                                            if (node.get("fieldId").asInt() == 47919) {
                                                currency = node.get("value").asText();
                                            } else if (node.get("fieldId").asInt() == 165251) {
                                                USDrate = node.get("value").asDouble();
                                            } else if (node.get("fieldId").asInt() == 161783) {
                                                flygcb = node.get("value").asDouble();
                                            }
                                        }
                                        row.put("textField_ml7c3yhw", currency);//todo：币别
                                        row.put("numberField_ml86221y", USDrate);//todo:美金汇率
                                        row.put("numberField_ml86221z", flygcb);//todo:辅料预估成本
                                        if(currency.equals("USD")){
                                            Double newUSDrate = USDrate == 0.0 ? 7.0 : USDrate;
                                            saletotalAmount = salesAmount * newUSDrate;
                                        }else {
                                            saletotalAmount = salesAmount;
                                        }
                                        row.put("numberField_ml862220",saletotalAmount);
                                        //下面是采购订单的明细数据
                                        row.put("textField_ml7c3yhx",shortName);//todo：生产工厂
                                        for(int j=0;j<products.size();j++){
                                            if(detail.getString("seq").equals(products.getJSONObject(j).getString("seq"))){
                                                //找到对应的采购一行数据
                                                row.put("numberField_ml7c3yhy",products.getJSONObject(j).getDouble("purchasePrice"));//todo:采购单价
                                                row.put("numberField_ml7c3yhz",products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购数量
                                                row.put("numberField_ml7c3yi0",products.getJSONObject(j).getDouble("purchasePrice") * products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购金额
                                            }
                                        }

                                        // ========== 修改点4：将当前行转换为Map<String,String>并暂存 ==========
                                        Map<String, Object> rowMap = new HashMap<>();
                                        for (Object key : row.keySet()) {
                                            Object value = row.get(key);
                                            rowMap.put(key.toString(), value != null ? value.toString() : "");
                                        }
                                        rowMap.put("orderFax",orderFax);
                                        currentOrderRows.add(rowMap);

                                        // ========== 修改点5：累加当前订单的汇总数据用于计算毛利率 ==========
                                        orderTotalSalesAmount += saletotalAmount;
                                        orderTotalPurchaseAmount += UtilMap.getDouble(row,"numberField_ml7c3yi0");
                                        orderTotalFlygcb += flygcb;
                                    }
                                }

                                // ========== 修改点6：计算当前订单的毛利率 ==========
                                double mlv = 0.0;
                                if (orderTotalSalesAmount > 0) {
                                    mlv = (orderTotalSalesAmount - orderTotalPurchaseAmount/orderFax - orderTotalFlygcb) / orderTotalSalesAmount;
                                }

                                System.out.println("订单 " + orderCode + " 毛利率: " + String.format("%.2f%%", mlv * 100));

                                // ========== 修改点7：根据毛利率决定添加到哪个列表 ==========
                                if (mlv >= 0.15) {
                                    // 高毛利率订单
                                    tabledataHigh.addAll(currentOrderRows);
                                    System.out.println("订单 " + orderCode + " 归类到高毛利率审批（>=15%）");
                                } else {
                                    // 低毛利率订单
                                    tabledataLow.addAll(currentOrderRows);
                                    System.out.println("订单 " + orderCode + " 归类到低毛利率审批（<15%）");
                                }
                            } else {
                                try {
                                    log.info("采购订单编号:{}将不发起钉钉审批",orderCode);
                                    HashMap body1 = new HashMap();
                                    body1.put("orderCode",orderCode);//订单编号：orderCode
                                    body1.put("vendorCode",dataArray.getJSONObject(0).getString("vendorCode"));//供应商编码：gysnumber
                                    String aa = dataArray.getJSONObject(0).getLong("purchaseTime").toString();
                                    String purchaseTime = Instant.ofEpochMilli(Long.parseLong(aa))
                                            .atZone(ZoneId.of("Asia/Shanghai"))
                                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    body1.put("purchaseTime",purchaseTime);//采购日期：purchaseTime
                                    String bb = dataArray.getJSONObject(0).getLong("planArrivalTime").toString();
                                    String planArrivalTime = Instant.ofEpochMilli(Long.parseLong(bb))
                                            .atZone(ZoneId.of("Asia/Shanghai"))
                                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    body1.put("planArrivalTime",planArrivalTime);//计划到货日期：planArrivalTime
                                    ArrayList<Map<String,String>> customFiled = new ArrayList();
                                    HashMap field = new HashMap();
                                    field.put("name","采购订单钉钉审批状态");
                                    field.put("value","审批完成");//审批状态
                                    customFiled.add(field);
                                    body1.put("purchaseOrderCustomFieldsValue",customFiled);
                                    UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/update", header, null, body1);
                                    log.info("---------【回传,{},采购订单状态完成】-----------",dataArray.getJSONObject(0).getString("orderCode"));
                                } catch (Exception e) {
                                    log.info("样品订单的采购订单自动通过审批失败，采购订单编号为：{}",orderCode);
                                    e.printStackTrace();
                                }
                            }
                        }

                        List<Map<String, Object>> oldList = new ArrayList<>();
                        List<Map<String, Object>> faxList = new ArrayList<>();
                        if (type.equals(targetValueUpdate)){
                            oldIds.forEach(h->{
                                List<Map> oldDataList = ydService.queryFormData_all(YDParam.builder()
                                        .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                        .formUuid("FORM-278D56A5065641F8AC95BCA0A8CE8447D8QY")
                                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_mmx9gyct", h)))
                                        .build());
                                if (ObjectUtil.isNotNull(oldDataList) && oldDataList.size()>0){
                                    List<Map> sonList = ydService.queryDetails(YDParam.builder()
                                            .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                            .formInstanceId(UtilMap.getString(oldDataList.get(0),"textField_mmx9gycu"))
                                            .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")
                                            .tableFieldId("tableField_ml6g7k5d")
                                            .build());
                                    if (ObjectUtil.isNotNull(sonList) && sonList.size() > 0){
                                        sonList.forEach(s->{
                                            Map<String, Object> map = new HashMap<>();
                                            TABLEFIELD_ENUM.forEach((k,v)->{
                                                map.put(v,UtilMap.getString(s,k));
                                            });
                                            oldList.add(map);
                                        });
                                    }
                                    List<Map> sonFaxList = ydService.queryDetails(YDParam.builder()
                                            .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                            .formInstanceId(UtilMap.getString(oldDataList.get(0),"textField_mmx9gycu"))
                                            .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")
                                            .tableFieldId("tableField_ml7ch2pj")
                                            .build());
                                    if (ObjectUtil.isNotNull(sonFaxList) && sonFaxList.size() > 0){
                                        sonFaxList.forEach(s->{
                                            Map<String, Object> map = new HashMap<>();
                                            TABLEFIELD_ENUM2.forEach((k,v)->{
                                                map.put(v,UtilMap.getString(s,k));
                                            });
                                            faxList.add(map);
                                        });
                                    }
                                }
                            });
                            log.info("oldList:{}",oldList.toString());
                            log.info("faxList:{}",faxList.toString());
                        }

                        // ========== 修改点8：分别处理高低毛利率的审批 ==========

                        // 处理高毛利率的审批 (mlv >= 0.15)
                        if (!tabledataHigh.isEmpty()) {
                            System.out.println("\n========== 开始处理分类汇总前高毛利率审批（>=15%），共 " + tabledataHigh.size() + " 条明细 ==========");
                            List<Map<String, Object>> mapList = groupAndSum(tabledataHigh);
                            System.out.println("\n========== 开始处理分类汇总后高毛利率审批（>=15%），共 " + mapList.size() + " 条明细 ==========");
                            //组装数据塞到采购明细表
                            formdataHigh.put("tableField_ml6g7k5d", mapList);

                            //组装数据塞到采购审批单号明细
                            List<Map<String, String>> orderSummaryListHigh = calculateOrderSummary(tabledataHigh);
                            formdataHigh.put("tableField_ml7ch2pj", orderSummaryListHigh);
                            formdataHigh.put("tableField_mmx6gata", oldList);
                            formdataHigh.put("tableField_mnekj8oq", faxList);

                            //数值统计毛利率
                            int szHigh = 0;
                            for (Map map : orderSummaryListHigh) {
                                Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo");
                                log.info((String) numberFieldMm2t71jo);
                                szHigh += Integer.parseInt((String) numberFieldMm2t71jo);
                            }
                            formdataHigh.put("numberField_mm2t71jp", szHigh);

                            /*发起流程 - 高毛利率审批*/
                            String userId = getDDToken(purchaserName);
                            ydClient.operateData(YDParam.builder()
                                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                    .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")  // 高毛利率使用原表单
                                    .userId(userId)
                                    .formDataJson(JSON.toJSONString(formdataHigh))
                                    .build(), YDConf.FORM_OPERATION.start).toString();

                            /*修改采购订单为审批中*/
                            for (Map map : orderSummaryListHigh) {
                                String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk");
                                callback(textFieldMl7ch2pk);
                            }

                            System.out.println("高毛利率审批流程发起完成");
                        }

                        // 处理低毛利率的审批 (mlv < 0.15)
                        if (!tabledataLow.isEmpty()) {
                            System.out.println("\n========== 开始处理分类汇总前低毛利率审批（<15%），共 " + tabledataLow.size() + " 条明细 ==========");
                            List<Map<String, Object>> mapList = groupAndSum(tabledataLow);
                            System.out.println("\n========== 开始处理分类汇总后低毛利率审批（<15%），共 " + mapList.size() + " 条明细 ==========");

                            //组装数据塞到采购明细表
                            formdataLow.put("tableField_ml6g7k5d", mapList);
                            formdataLow.put("tableField_mmx6gata", oldList);
                            formdataLow.put("tableField_mnekj8oq", faxList);

                            //组装数据塞到采购审批单号明细
                            List<Map<String, String>> orderSummaryListLow = calculateOrderSummary(tabledataLow);
                            formdataLow.put("tableField_ml7ch2pj", orderSummaryListLow);

                            //数值统计毛利率
                            int szLow = 0;
                            for (Map map : orderSummaryListLow) {
                                Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo");
                                log.info((String) numberFieldMm2t71jo);
                                szLow += Integer.parseInt((String) numberFieldMm2t71jo);
                            }
                            formdataLow.put("numberField_mm2t71jp", szLow);

                            /*发起流程 - 低毛利率审批*/
                            String userId = getDDToken(purchaserName);
                            // ========== 修改点9：如果低毛利率需要不同表单，可以在这里修改formUuid ==========
                            ydClient.operateData(YDParam.builder()
                                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                    .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")  // 如果需要不同流程，替换这里的UUID
                                    .userId(userId)
                                    .formDataJson(JSON.toJSONString(formdataLow))
                                    .build(), YDConf.FORM_OPERATION.start).toString();

                            /*修改采购订单为审批中*/
                            for (Map map : orderSummaryListLow) {
                                String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk");
                                callback(textFieldMl7ch2pk);
                            }

                            System.out.println("低毛利率审批流程发起完成");
                        }

                    });
        }

        return null;
    }

    @SneakyThrows
    @Override
    public McR purchaseScheduleTest(List<Map<String, Object>> dataList) {
        HashMap header = new HashMap();
        header.put("X-AUTH", HeiHuAccessToken().getData().toString());
        header.put("Content-Type", "application/json");
        String targetValue = "合同确认，提交审批";
        String targetValueUpdate = "合同修改，修改审批";

        // 定义一个字符串集合，默认包含两个值："默认值1"、"默认值2"
        List<String> targetValues = new ArrayList() {{
            add("合同确认，提交审批");
            add("合同修改，修改审批");
        }};
        Map<String, List<String>> purchaserOrderCodes = new HashMap<>();


        if (ObjectUtil.isNotNull(dataList) && dataList.size() > 0) {
            for (Map<String, Object> item : dataList) {
                String purchaserName = (String) item.get("purchaserName");
                if (purchaserName == null) purchaserName = "未知";

//                boolean hasTargetStatus = false;
                List<Map<String, Object>> customFieldValues = (List<Map<String, Object>>) item.get("customFieldValues");
                if (customFieldValues != null) {
                    for (Map<String, Object> field : customFieldValues) {
                        if (targetValue.equals(field.get("value") ) || targetValueUpdate.equals(field.get("value"))) {
                            System.out.println("合同状态类型："+field.get("value"));
//                        if (targetValue.equals(field.get("value"))) {
//                            hasTargetStatus = true;
                            String orderCode = (String) item.get("orderCode");
                            if (orderCode != null) {
                                purchaserOrderCodes.computeIfAbsent(purchaserName + "-" + field.get("value"), k -> new ArrayList<>()).add(orderCode);
                            }
                            break;
                        }
                    }
                }

            }

        }

        // 输出所有采购员的待审批订单
        System.out.println("========== 所有采购员的待审批订单统计 ==========");

        if (purchaserOrderCodes.isEmpty()) {
            System.out.println("没有找到钉钉审批状态为'" + targetValue + "'的订单");
        } else {
            int totalPurchasers = purchaserOrderCodes.size();
            int totalOrders = purchaserOrderCodes.values().stream().mapToInt(List::size).sum();

            System.out.println("共找到 " + totalOrders + " 个待审批订单");
            System.out.println("涉及 " + totalPurchasers + " 位采购员");
            System.out.println();

            // 输出每个采购员的情况
            for (Map.Entry<String, List<String>> entry : purchaserOrderCodes.entrySet()) {
                String[] split = entry.getKey().split("-");
                String purchaserName = split[0];
                String type = split[1];
                List<String> orderCodes = entry.getValue();
                int orderCount = orderCodes.size();

                System.out.println("采购员: " + purchaserName);
                System.out.println("待审批订单数量: " + orderCount);
                System.out.println("审批类型: " + type);

                if (orderCount > 1) {
                    System.out.println("⚠️  注意：该采购员有 " + orderCount + " 个待审批订单");
                }
                System.out.println("订单编号: " + String.join(", ", orderCodes));
            }

            // 按订单数量排序输出
            System.out.println("========== 按待审批订单数量排序 ==========");
            purchaserOrderCodes.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
                    .forEach(entry -> {
                        String[] split = entry.getKey().split("-");
                        String purchaserName = split[0];
                        String type = split[1];
                        List<String> orderCodes = entry.getValue();

                        System.out.println(purchaserName + " (" + orderCodes.size() + "个): " +
                                String.join(", ", orderCodes));

                        // ========== 修改点1：声明两个列表分别存储不同毛利率的订单数据 ==========
                        // 针对同一个采购员，遍历下面的订单编号
                        System.out.println("开始处理采购员 " + purchaserName + " 的 " + orderCodes.size() + " 个待审批订单");

                        // 高毛利率表单数据 (mlv >= 0.15)
                        HashMap formdataHigh = new HashMap();
                        List<Map<String,Object>> tabledataHigh = new ArrayList();

                        // 低毛利率表单数据 (mlv < 0.15)
                        HashMap formdataLow = new HashMap();
                        List<Map<String,Object>> tabledataLow = new ArrayList();

                        // ========== 修改点2：为每个订单创建临时存储列表 ==========
                        // 用于暂存每个订单的明细数据，等计算出毛利率后再决定添加到哪个列表
//                        Map<String, List<Map<String, String>>> tempOrderDataMap = new HashMap<>();
                        // 用于存储每个订单的汇总数据，用于计算毛利率
//                        Map<String, Map<String, Double>> orderSummaryForMlv = new HashMap<>();
                        List<String> oldIds = new ArrayList<>();

                        for (String orderCode : orderCodes) {
                            System.out.println("正在处理订单: " + orderCode);
                            if (type.equals(targetValueUpdate)){
                                oldIds.add(orderCode);
                            }
                            // ========== 修改点3：为当前订单创建临时数据存储 ==========
                            List<Map<String, Object>> currentOrderRows = new ArrayList<>();
                            double orderTotalSalesAmount = 0.0;
                            double orderTotalPurchaseAmount = 0.0;
                            double orderTotalFlygcb = 0.0;

                            //todo:查询订单的销售订单 | 客户  销售订单号  款式  产品描述  颜色 | 数量  销售单价  销售金额 | 币别 美金汇率 辅料预估成本 销售总金额
                            String customerName = "",orderNumber ="",styleNumber ="",productDescription = "",color = "";
                            Double number,unitPrice,salesAmount;
                            String currency = ""; Double USDrate = 0.00; Double flygcb = 0.00; Double saletotalAmount = 0.00;
                            Double estimatedPrice = 0.00;//辅料预估单价

                            HashMap body = new HashMap();
                            body.put("orderCode",orderCode);//订单编号
                            String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);
                            //todo:查询采购订单 生产工厂（供应商）
                            String shortName = "";
                            JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data");
                            for (int i=0;i<dataArray.size();i++) {
                                JSONObject data = dataArray.getJSONObject(i);
                                shortName = data.getString("shortName");//供应商：shortName
                            }
                            JSONArray products = JSONObject.parseObject(jsonString).getJSONArray("data").getJSONObject(0).getJSONArray("purchaseSubOrderVOS");

                            List<Map<String, Object>> purchaseRows = new ArrayList<>();
                            for(int j=0;j<products.size();j++){
                                Map<String,Object> purchaseRow = new HashMap();
//                                row.put("textField_mm2t71jm",orderCode);//todo：采购订单单号
//                                row.put("textField_ml6g7k5e", customerName);//todo:客户
//                                row.put("textField_ml6g7k5f", orderNumber);//todo：订单号
//                                //下面是采购订单的明细数据
//                                row.put("textField_ml7c3yhx",shortName);//todo：生产工厂
                                    //找到对应的采购一行数据
                                purchaseRow.put("productCode",products.getJSONObject(j).getString("productCode"));
                                purchaseRow.put("numberField_ml7c3yhy",products.getJSONObject(j).getDouble("purchasePrice"));//todo:采购单价
                                purchaseRow.put("numberField_ml7c3yhz",products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购数量
                                purchaseRow.put("numberField_ml7c3yi0",products.getJSONObject(j).getDouble("purchasePrice") * products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购金额
                                purchaseRows.add(purchaseRow);
                            }


                            ObjectMapper objectMapper = new ObjectMapper();
                            JsonNode rootNode = null;
                            try {
                                rootNode = objectMapper.readTree(jsonString);
                            } catch (JsonProcessingException e) {
                                throw new RuntimeException(e);
                            }
                            JsonNode dataNode = rootNode.get("data");
                            if(dataNode != null && dataNode.isArray()){
                                for(JsonNode item : dataNode){
                                    JsonNode orderNoNode = item.get("orderCode");
                                    JsonNode saleOrders = item.get("relationSaleOrders");
                                    if(saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0){
                                        orderNumber = saleOrders.get(0).asText();//销售订单号
                                    }
                                }
                            }

                            HashMap body_A = new HashMap();
                            body_A.put("orderNo",orderNumber);
                            String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo：查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别
                            log.info("saleOrder/queryList2:{}",jsonString2);
                            JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据
                            String finalOrderNumber = orderNumber;
                            boolean isSample = false;//销售订单若为样品订单则不发起钉钉流程
                            for(int i=0;i<array.size();i++){
                                JSONObject data = array.getJSONObject(i);
                                customerName = data.getString("customerCode");//客户
                                if (finalOrderNumber.equals(data.getString("contractNo"))){
                                    log.info("customer123:{}",customerName);
                                }
                            }
                            ObjectMapper objectMapper2 = new ObjectMapper();
                            JsonNode dataNode2 = null;//主表数据
                            List<JsonNode> list = new ArrayList<>();
                            try {
                                dataNode2 = objectMapper2.readTree(jsonString2).get("data");
                                list = StreamSupport.stream(dataNode2.spliterator(), false)
                                        .filter(node -> finalOrderNumber.equals(node.get("orderNo").asText()))
                                        .collect(Collectors.toList());
                                for (JsonNode item : list){
                                    JsonNode customFieldValues = item.get("customFieldValues");
                                    for (JsonNode field : customFieldValues){
                                        JsonNode fieldIdNode = field.get("fieldId");
                                        if(fieldIdNode != null && fieldIdNode.asInt() == 161769){
                                            JsonNode valueNode = field.get("value");
                                            if(valueNode != null){
                                                estimatedPrice = valueNode.asDouble();//辅料预估单价
                                            }
                                        }
                                        else if(fieldIdNode != null && fieldIdNode.asInt() == 47771){
                                            JsonNode valueNode = field.get("value");
                                            log.info("销售订单类型:{}",valueNode.asText());
                                            if("样品订单".equals(valueNode.asText())){
                                                isSample = true;
                                            }
                                        }
                                    }
                                }
                            } catch (JsonProcessingException e) {
                                e.printStackTrace();
                            }

                            if (!isSample){
                                JSONArray products_A = JSONObject.parseObject(jsonString2).getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");//销售订单明细数据

                                if(products_A != null) {
                                    List<Map<String, Object>> saleRows = new ArrayList<>();
                                    for (int i = 0; i < products_A.size(); i++) {
                                        JSONObject detail = products_A.getJSONObject(i);
                                        Map<String,Object> saleRow = new HashMap();

                                        styleNumber = detail.getString("productCode");//款号
                                        saleRow.put("textField_ml7c3yhq", styleNumber);//todo:款号

                                        productDescription = detail.getString("productName");//产品描述
                                        saleRow.put("textField_ml7c3yhr", productDescription);//todo：产品描述

                                        JSONArray array1 = detail.getJSONArray("customFieldValues");
                                        color = array1.stream()
                                                .map(obj -> (JSONObject) obj)
                                                .filter(item -> item.getIntValue("fieldId") == 82259)
                                                .map(item -> item.getString("value"))
                                                .findFirst()
                                                .orElse(null);
                                        ArrayList colorList = new ArrayList();
                                        colorList.add(color);
                                        String color_AAA = null;
                                        try {
                                            color_AAA = getProductColor(colorList);
                                        } catch (JacksonException e) {
                                            e.printStackTrace();
                                        }
                                        saleRow.put("textField_ml7c3yhs", color_AAA);//todo：颜色

                                        number = detail.getDoubleValue("qty");//数量
                                        saleRow.put("numberField_ml7c3yht", number);//todo：数量

                                        unitPrice = detail.getDoubleValue("unitPrice");//销售单价
                                        saleRow.put("numberField_ml7c3yhu", unitPrice);//todo：销售单价

                                        salesAmount = number * unitPrice;//销售金额
                                        saleRow.put("numberField_ml7c3yhv", salesAmount);//todo：销售金额
                                        String customFieldValues = detail.getString("customFieldValues");
                                        ObjectMapper mapper = new ObjectMapper();
                                        JsonNode jsonarray = null;
                                        try {
                                            jsonarray = mapper.readTree(customFieldValues);
                                        } catch (JsonProcessingException e) {
                                            throw new RuntimeException(e);
                                        }
                                        for (JsonNode node : jsonarray) {
                                            if (node.get("fieldId").asInt() == 47919) {
                                                currency = node.get("value").asText();
                                            } else if (node.get("fieldId").asInt() == 165251) {
                                                USDrate = node.get("value").asDouble();

                                            } else if (node.get("fieldId").asInt() == 161783) {
                                                flygcb = node.get("value").asDouble();
                                            }
                                        }
                                        saleRow.put("textField_ml7c3yhw", currency);//todo：币别
                                        saleRow.put("numberField_ml86221y", USDrate);//todo:美金汇率
                                        saleRow.put("numberField_ml86221z", flygcb);//todo:辅料预估成本
                                        if(currency.equals("USD")){
                                            saletotalAmount = salesAmount * USDrate;
                                        }else {
                                            saletotalAmount = salesAmount;
                                        }
                                        saleRow.put("numberField_ml862220",saletotalAmount);

                                        saleRows.add(saleRow);

                                        // ========== 修改点5：累加当前订单的汇总数据用于计算毛利率 ==========
                                        orderTotalSalesAmount += saletotalAmount;
//                                        orderTotalPurchaseAmount += (Double)row.get("numberField_ml7c3yi0");
                                        orderTotalFlygcb += flygcb;
                                    }
                                }

                                // ========== 修改点6：计算当前订单的毛利率 ==========
                                double mlv = 0.0;
                                if (orderTotalSalesAmount > 0) {
                                    mlv = (orderTotalSalesAmount - orderTotalPurchaseAmount - orderTotalFlygcb) / orderTotalSalesAmount;
                                }

                                System.out.println("订单 " + orderCode + " 毛利率: " + String.format("%.2f%%", mlv * 100));

                                // ========== 修改点7：根据毛利率决定添加到哪个列表 ==========
                                if (mlv >= 0.15) {
                                    // 高毛利率订单
                                    tabledataHigh.addAll(currentOrderRows);
                                    System.out.println("订单 " + orderCode + " 归类到高毛利率审批（>=15%）");
                                } else {
                                    // 低毛利率订单
                                    tabledataLow.addAll(currentOrderRows);
                                    System.out.println("订单 " + orderCode + " 归类到低毛利率审批（<15%）");
                                }
                            } else {
                                try {
                                    log.info("采购订单编号:{}将不发起钉钉审批",orderCode);
                                    HashMap body1 = new HashMap();
                                    body1.put("orderCode",orderCode);//订单编号：orderCode
                                    body1.put("vendorCode",dataArray.getJSONObject(0).getString("vendorCode"));//供应商编码：gysnumber
                                    String aa = dataArray.getJSONObject(0).getLong("purchaseTime").toString();
                                    String purchaseTime = Instant.ofEpochMilli(Long.parseLong(aa))
                                            .atZone(ZoneId.of("Asia/Shanghai"))
                                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    body1.put("purchaseTime",purchaseTime);//采购日期：purchaseTime
                                    String bb = dataArray.getJSONObject(0).getLong("planArrivalTime").toString();
                                    String planArrivalTime = Instant.ofEpochMilli(Long.parseLong(bb))
                                            .atZone(ZoneId.of("Asia/Shanghai"))
                                            .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                                    body1.put("planArrivalTime",planArrivalTime);//计划到货日期：planArrivalTime
                                    ArrayList<Map<String,String>> customFiled = new ArrayList();
                                    HashMap field = new HashMap();
                                    field.put("name","采购订单钉钉审批状态");
                                    field.put("value","审批完成");//审批状态
                                    customFiled.add(field);
                                    body1.put("purchaseOrderCustomFieldsValue",customFiled);
                                    UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/update", header, null, body1);
                                    log.info("---------【回传,{},采购订单状态完成】-----------",dataArray.getJSONObject(0).getString("orderCode"));
                                } catch (Exception e) {
                                    log.info("样品订单的采购订单自动通过审批失败，采购订单编号为：{}",orderCode);
                                    e.printStackTrace();
                                }
                            }
                        }

                        List<Map<String, Object>> oldList = new ArrayList<>();
                        List<Map<String, Object>> faxList = new ArrayList<>();
                        if (type.equals(targetValueUpdate)){
                            oldIds.forEach(h->{
                                List<Map> oldDataList = ydService.queryFormData_all(YDParam.builder()
                                        .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                        .formUuid("FORM-278D56A5065641F8AC95BCA0A8CE8447D8QY")
                                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_mmx9gyct", h)))
                                        .build());
                                if (ObjectUtil.isNotNull(oldDataList) && oldDataList.size()>0){
                                    List<Map> sonList = ydService.queryDetails(YDParam.builder()
                                            .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                            .formInstanceId(UtilMap.getString(oldDataList.get(0),"textField_mmx9gycu"))
                                            .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")
                                            .tableFieldId("tableField_ml6g7k5d")
                                            .build());
                                    if (ObjectUtil.isNotNull(sonList) && sonList.size() > 0){
                                        sonList.forEach(s->{
                                            Map<String, Object> map = new HashMap<>();
                                            TABLEFIELD_ENUM.forEach((k,v)->{
                                                map.put(v,UtilMap.getString(s,k));
                                            });
                                            oldList.add(map);
                                        });
                                    }
                                    List<Map> sonFaxList = ydService.queryDetails(YDParam.builder()
                                            .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                            .formInstanceId(UtilMap.getString(oldDataList.get(0),"textField_mmx9gycu"))
                                            .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")
                                            .tableFieldId("tableField_ml7ch2pj")
                                            .build());
                                    if (ObjectUtil.isNotNull(sonFaxList) && sonFaxList.size() > 0){
                                        sonFaxList.forEach(s->{
                                            Map<String, Object> map = new HashMap<>();
                                            TABLEFIELD_ENUM2.forEach((k,v)->{
                                                map.put(v,UtilMap.getString(s,k));
                                            });
                                            faxList.add(map);
                                        });
                                    }
                                }
                            });
                            log.info("oldList:{}",oldList.toString());
                            log.info("faxList:{}",faxList.toString());
                        }

                        // ========== 修改点8：分别处理高低毛利率的审批 ==========

                        // 处理高毛利率的审批 (mlv >= 0.15)
                        if (!tabledataHigh.isEmpty()) {
                            System.out.println("\n========== 开始处理分类汇总前高毛利率审批（>=15%），共 " + tabledataHigh.size() + " 条明细 ==========");
                            List<Map<String, Object>> mapList = groupAndSum(tabledataHigh);
                            System.out.println("\n========== 开始处理分类汇总后高毛利率审批（>=15%），共 " + mapList.size() + " 条明细 ==========");
                            //组装数据塞到采购明细表
                            formdataHigh.put("tableField_ml6g7k5d", mapList);

                            //组装数据塞到采购审批单号明细
                            List<Map<String, String>> orderSummaryListHigh = calculateOrderSummary(tabledataHigh);
                            formdataHigh.put("tableField_ml7ch2pj", orderSummaryListHigh);
                            formdataHigh.put("tableField_mmx6gata", oldList);
                            formdataHigh.put("tableField_mnekj8oq", faxList);

                            //数值统计毛利率
                            int szHigh = 0;
                            for (Map map : orderSummaryListHigh) {
                                Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo");
                                log.info((String) numberFieldMm2t71jo);
                                szHigh += Integer.parseInt((String) numberFieldMm2t71jo);
                            }
                            formdataHigh.put("numberField_mm2t71jp", szHigh);

                            /*发起流程 - 高毛利率审批*/
                            String userId = getDDToken(purchaserName);
                            ydClient.operateData(YDParam.builder()
                                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                    .formUuid("FORM-6D814824193941BC9D4FD2A046E986E0R74Y")  // 高毛利率使用原表单
                                    .userId(userId)
                                    .formDataJson(JSON.toJSONString(formdataHigh))
                                    .build(), YDConf.FORM_OPERATION.start).toString();

                            /*修改采购订单为审批中*/
                            for (Map map : orderSummaryListHigh) {
                                String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk");
                                callback(textFieldMl7ch2pk);
                            }

                            System.out.println("高毛利率审批流程发起完成");
                        }

                        // 处理低毛利率的审批 (mlv < 0.15)
                        if (!tabledataLow.isEmpty()) {
                            System.out.println("\n========== 开始处理分类汇总前低毛利率审批（<15%），共 " + tabledataLow.size() + " 条明细 ==========");
                            List<Map<String, Object>> mapList = groupAndSum(tabledataLow);
                            System.out.println("\n========== 开始处理分类汇总后低毛利率审批（<15%），共 " + mapList.size() + " 条明细 ==========");

                            //组装数据塞到采购明细表
                            formdataLow.put("tableField_ml6g7k5d", mapList);
                            formdataLow.put("tableField_mmx6gata", oldList);
                            formdataLow.put("tableField_mnekj8oq", faxList);

                            //组装数据塞到采购审批单号明细
                            List<Map<String, String>> orderSummaryListLow = calculateOrderSummary(tabledataLow);
                            formdataLow.put("tableField_ml7ch2pj", orderSummaryListLow);

                            //数值统计毛利率
                            int szLow = 0;
                            for (Map map : orderSummaryListLow) {
                                Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo");
                                log.info((String) numberFieldMm2t71jo);
                                szLow += Integer.parseInt((String) numberFieldMm2t71jo);
                            }
                            formdataLow.put("numberField_mm2t71jp", szLow);

                            /*发起流程 - 低毛利率审批*/
                            String userId = getDDToken(purchaserName);
                            // ========== 修改点9：如果低毛利率需要不同表单，可以在这里修改formUuid ==========
                            ydClient.operateData(YDParam.builder()
                                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
                                    .formUuid("FORM-6D814824193941BC9D4FD2A046E986E0R74Y")  // 如果需要不同流程，替换这里的UUID
                                    .userId(userId)
                                    .formDataJson(JSON.toJSONString(formdataLow))
                                    .build(), YDConf.FORM_OPERATION.start).toString();

                            /*修改采购订单为审批中*/
                            for (Map map : orderSummaryListLow) {
                                String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk");
                                callback(textFieldMl7ch2pk);
                            }

                            System.out.println("低毛利率审批流程发起完成");
                        }

                    });
        }

        return null;
    }

    @SneakyThrows
    @Override
    public List<Map<String, Object>> queryAllPurchase() {
        HashMap header = new HashMap();
        header.put("X-AUTH", HeiHuAccessToken().getData().toString());
        header.put("Content-Type", "application/json");
        boolean hasMoreData = true;
        int pageNum = 1;
        int pageSize = 100;
        List<Map<String, Object>> dataList = new ArrayList<>();
        while (hasMoreData) {
            HashMap body = new HashMap();
            Map<String, Integer> page = new HashMap<>();
            page.put("pageNum", pageNum);
            page.put("pageSize", pageSize);
            List<Integer> status = Arrays.asList(1);
            body.put("page", page);
            body.put("status", status);

            String doPost = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//查询采购订单
            log.info("header:{}",header.toString());
            System.out.println("header:" + header.toString());
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> response = mapper.readValue(doPost, Map.class);

            if (!"01000000".equals(response.get("code"))) {
                System.out.println("请求失败: " + response.get("msg"));
                break;
            }

//            dataList.addAll(UtilMap.getList(response,"data"));
            List<Map<String, Object>> mapList = (List<Map<String, Object>>) response.get("data");
            if (ObjectUtil.isNotNull(mapList) && mapList.size() > 0){
                dataList.addAll(mapList);
                hasMoreData = mapList.size() >= pageSize;
            } else {
                hasMoreData = false;
            }
            pageNum++;
        }

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return dataList;
    }

    @Override
    public McR purchaseUpdateSchedule() throws JacksonException {
//        HashMap header = new HashMap();
//        header.put("X-AUTH", HeiHuAccessToken().getData().toString());
//        header.put("Content-Type", "application/json");
//        String targetValue = "合同修改，修改审批";
//        Map<String, List<String>> purchaserOrderCodes = new HashMap<>();
//
//        int pageNum = 1;
//        int pageSize = 100;
//        boolean hasMoreData = true;
//
//        while (hasMoreData) {
//            HashMap body = new HashMap();
//            Map<String, Integer> page = new HashMap<>();
//            page.put("pageNum", pageNum);
//            page.put("pageSize", pageSize);
//            List<Integer> status = Arrays.asList(1);
//            body.put("page", page);
//            body.put("status", status);
//
//            String doPost = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//查询采购订单
//
//            ObjectMapper mapper = new ObjectMapper();
//            Map<String, Object> response = mapper.readValue(doPost, Map.class);
//
//            if (!"01000000".equals(response.get("code"))) {
//                log.info("请求失败: {}" , response.get("msg"));
//                break;
//            }
//
//            List<Map<String, Object>> dataList = (List<Map<String, Object>>) response.get("data");
//            if (dataList != null) {
//                for (Map<String, Object> item : dataList) {
//                    String purchaserName = (String) item.get("purchaserName");
//                    if (purchaserName == null) purchaserName = "未知";
//
//                    boolean hasTargetStatus = false;
//                    List<Map<String, Object>> customFieldValues = (List<Map<String, Object>>) item.get("customFieldValues");
//                    if (customFieldValues != null) {
//                        for (Map<String, Object> field : customFieldValues) {
//                            if (targetValue.equals(field.get("value"))) {
//                                hasTargetStatus = true;
//                                break;
//                            }
//                        }
//                    }
//
//                    if (hasTargetStatus) {
//                        String orderCode = (String) item.get("orderCode");
//                        if (orderCode != null) {
//                            purchaserOrderCodes.computeIfAbsent(purchaserName, k -> new ArrayList<>()).add(orderCode);
//                        }
//                    }
//                }
//
//                hasMoreData = dataList.size() >= pageSize;
//            } else {
//                hasMoreData = false;
//            }
//
//            pageNum++;
//
//            try {
//                Thread.sleep(200);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//
//        // 输出所有采购员的待审批订单
//        System.out.println("========== 所有采购员的待审批订单统计 ==========");
//
//        if (purchaserOrderCodes.isEmpty()) {
//            System.out.println("没有找到钉钉审批状态为'" + targetValue + "'的订单");
//        } else {
//            int totalPurchasers = purchaserOrderCodes.size();
//            int totalOrders = purchaserOrderCodes.values().stream().mapToInt(List::size).sum();
//
//            System.out.println("共找到 " + totalOrders + " 个待审批订单");
//            System.out.println("涉及 " + totalPurchasers + " 位采购员");
//            System.out.println();
//
//            // 输出每个采购员的情况
//            for (Map.Entry<String, List<String>> entry : purchaserOrderCodes.entrySet()) {
//                String purchaserName = entry.getKey();
//                List<String> orderCodes = entry.getValue();
//                int orderCount = orderCodes.size();
//
//                System.out.println("采购员: " + purchaserName);
//                System.out.println("待审批订单数量: " + orderCount);
//
//                if (orderCount > 1) {
//                    System.out.println("⚠️  注意：该采购员有 " + orderCount + " 个待审批订单");
//                }
//
//                System.out.println("订单编号: " + String.join(", ", orderCodes));
//                System.out.println();
//            }
//
//            // 按订单数量排序输出
//            System.out.println("========== 按待审批订单数量排序 ==========");
//            purchaserOrderCodes.entrySet().stream()
//                    .sorted((e1, e2) -> Integer.compare(e2.getValue().size(), e1.getValue().size()))
//                    .forEach(entry -> {
//                        String purchaserName = entry.getKey();
//                        List<String> orderCodes = entry.getValue();
//                        System.out.println(purchaserName + " (" + orderCodes.size() + "个): " +
//                                String.join(", ", orderCodes));
//
//                        // ========== 修改点1：声明两个列表分别存储不同毛利率的订单数据 ==========
//                        // 针对同一个采购员，遍历下面的订单编号
//                        System.out.println("开始处理采购员 " + purchaserName + " 的 " + orderCodes.size() + " 个待审批订单");
//
//                        // 高毛利率表单数据 (mlv >= 0.15)
//                        HashMap formdataHigh = new HashMap();
//                        List<Map<String,Object>> tabledataHigh = new ArrayList();
//
//                        // 低毛利率表单数据 (mlv < 0.15)
//                        HashMap formdataLow = new HashMap();
//                        List<Map<String,Object>> tabledataLow = new ArrayList();
//
//                        // ========== 修改点2：为每个订单创建临时存储列表 ==========
//                        // 用于暂存每个订单的明细数据，等计算出毛利率后再决定添加到哪个列表
//                        Map<String, List<Map<String, String>>> tempOrderDataMap = new HashMap<>();
//                        // 用于存储每个订单的汇总数据，用于计算毛利率
//                        Map<String, Map<String, Double>> orderSummaryForMlv = new HashMap<>();
//                        List<String> oldHighIds = new ArrayList<>();
//                        List<String> oldLowIds = new ArrayList<>();
//
//                        for (String orderCode : orderCodes) {
//                            System.out.println("正在处理订单: " + orderCode);
//
//                            // ========== 修改点3：为当前订单创建临时数据存储 ==========
//                            List<Map<String, String>> currentOrderRows = new ArrayList<>();
//                            double orderTotalSalesAmount = 0.0;
//                            double orderTotalPurchaseAmount = 0.0;
//                            double orderTotalFlygcb = 0.0;
//
//                            //todo:查询订单的销售订单 | 客户  销售订单号  款式  产品描述  颜色 | 数量  销售单价  销售金额 | 币别 美金汇率 辅料预估成本 销售总金额
//                            String customerName = "",orderNumber ="",styleNumber ="",productDescription = "",color = "";
//                            Double number,unitPrice,salesAmount;
//                            String currency = ""; Double USDrate = 0.00; Double flygcb = 0.00; Double saletotalAmount = 0.00;
//                            Double estimatedPrice = 0.00;//辅料预估单价
//
//                            HashMap body = new HashMap();
//                            body.put("orderCode",orderCode);//订单编号
//                            String jsonString = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);
//                            //todo:查询采购订单 生产工厂（供应商）
//                            String shortName = "";
//                            JSONArray dataArray = JSONObject.parseObject(jsonString).getJSONArray("data");
//                            for (int i=0;i<dataArray.size();i++) {
//                                JSONObject data = dataArray.getJSONObject(i);
//                                shortName = data.getString("shortName");//供应商：shortName
//                            }
//                            JSONArray products = JSONObject.parseObject(jsonString).getJSONArray("data").getJSONObject(0).getJSONArray("purchaseSubOrderVOS");
//                            ObjectMapper objectMapper = new ObjectMapper();
//                            JsonNode rootNode = null;
//                            try {
//                                rootNode = objectMapper.readTree(jsonString);
//                            } catch (JsonProcessingException e) {
//                                throw new RuntimeException(e);
//                            }
//                            JsonNode dataNode = rootNode.get("data");
//                            if(dataNode != null && dataNode.isArray()){
//                                for(JsonNode item : dataNode){
//                                    JsonNode orderNoNode = item.get("orderCode");
//                                    JsonNode saleOrders = item.get("relationSaleOrders");
//                                    if(saleOrders != null && saleOrders.isArray() && saleOrders.size() > 0){
//                                        orderNumber = saleOrders.get(0).asText();//销售订单号
//                                    }
//                                }
//                            }
//
//                            HashMap body_A = new HashMap();
//                            body_A.put("orderNo",orderNumber);
//                            String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/saleOrder/queryList2", header, null, body_A);//todo：查询销售订单,获取客户、订单号、款号、产品描述、颜色、数量、销售单价、销售金额、币别
//                            JSONArray array = JSONObject.parseObject(jsonString2).getJSONArray("data");//主表数据
//                            for(int i=0;i<array.size();i++){
//                                JSONObject data = array.getJSONObject(i);
//                                customerName = data.getString("customerCode");//客户
//                            }
//                            ObjectMapper objectMapper2 = new ObjectMapper();
//                            JsonNode dataNode2 = null;//主表数据
//                            try {
//                                dataNode2 = objectMapper2.readTree(jsonString2).get("data");
//                            } catch (JsonProcessingException e) {
//                                throw new RuntimeException(e);
//                            }
//                            for (JsonNode item : dataNode2){
//                                JsonNode customFieldValues = item.get("customFieldValues");
//                                for (JsonNode field : customFieldValues){
//                                    JsonNode fieldIdNode = field.get("fieldId");
//                                    if(fieldIdNode != null && fieldIdNode.asInt() == 161769){
//                                        JsonNode valueNode = field.get("value");
//                                        if(valueNode != null){
//                                            estimatedPrice = valueNode.asDouble();//辅料预估单价
//                                            break;
//                                        }
//                                    }
//                                }
//                            }
//
//                            JSONArray products_A = JSONObject.parseObject(jsonString2).getJSONArray("data").getJSONObject(0).getJSONArray("saleManageOrderDetailRowApiVOList");//销售订单明细数据
//
//                            if(products_A != null) {
//                                for (int i = 0; i < products_A.size(); i++) {
//                                    JSONObject detail = products_A.getJSONObject(i);
//                                    HashMap row = new HashMap();
//                                    row.put("textField_mm2t71jm",orderCode);//todo：采购订单单号
//                                    row.put("textField_ml6g7k5e", customerName);//todo:客户
//                                    row.put("textField_ml6g7k5f", orderNumber);//todo：订单号
//
//                                    styleNumber = detail.getString("productCode");//款号
//                                    row.put("textField_ml7c3yhq", styleNumber);//todo:款号
//
//                                    productDescription = detail.getString("productName");//产品描述
//                                    row.put("textField_ml7c3yhr", productDescription);//todo：产品描述
//
//                                    JSONArray array1 = detail.getJSONArray("customFieldValues");
//                                    color = array1.stream()
//                                            .map(obj -> (JSONObject) obj)
//                                            .filter(item -> item.getIntValue("fieldId") == 82259)
//                                            .map(item -> item.getString("value"))
//                                            .findFirst()
//                                            .orElse(null);
//                                    ArrayList colorList = new ArrayList();
//                                    colorList.add(color);
//                                    String color_AAA = null;
//                                    try {
//                                        color_AAA = getProductColor(colorList);
//                                    } catch (JacksonException e) {
//                                        throw new RuntimeException(e);
//                                    }
//                                    row.put("textField_ml7c3yhs", color_AAA);//todo：颜色
//
//                                    number = detail.getDoubleValue("qty");//数量
//                                    row.put("numberField_ml7c3yht", number);//todo：数量
//
//                                    unitPrice = detail.getDoubleValue("unitPrice");//销售单价
//                                    row.put("numberField_ml7c3yhu", unitPrice);//todo：销售单价
//
//                                    salesAmount = number * unitPrice;//销售金额
//                                    row.put("numberField_ml7c3yhv", salesAmount);//todo：销售金额
//                                    String customFieldValues = detail.getString("customFieldValues");
//                                    ObjectMapper mapper = new ObjectMapper();
//                                    JsonNode jsonarray = null;
//                                    try {
//                                        jsonarray = mapper.readTree(customFieldValues);
//                                    } catch (JsonProcessingException e) {
//                                        throw new RuntimeException(e);
//                                    }
//                                    for (JsonNode node : jsonarray) {
//                                        if (node.get("fieldId").asInt() == 47919) {
//                                            currency = node.get("value").asText();
//                                        } else if (node.get("fieldId").asInt() == 165251) {
//                                            USDrate = node.get("value").asDouble();
//
//                                        } else if (node.get("fieldId").asInt() == 161783) {
//                                            flygcb = node.get("value").asDouble();
//                                        }
//                                    }
//                                    row.put("textField_ml7c3yhw", currency);//todo：币别
//                                    row.put("numberField_ml86221y", USDrate);//todo:美金汇率
//                                    row.put("numberField_ml86221z", flygcb);//todo:辅料预估成本
//                                    if(currency.equals("USD")){
//                                        saletotalAmount = salesAmount * USDrate;
//                                    }else {
//                                        saletotalAmount = salesAmount;
//                                    }
//                                    row.put("numberField_ml862220",saletotalAmount);
//                                    //下面是采购订单的明细数据
//                                    row.put("textField_ml7c3yhx",shortName);//todo：生产工厂
//                                    for(int j=0;j<products.size();j++){
//                                        if(styleNumber.equals(products.getJSONObject(j).getString("productCode"))){
//                                            //找到对应的采购一行数据
//                                            row.put("numberField_ml7c3yhy",products.getJSONObject(j).getDouble("purchasePrice"));//todo:采购单价
//                                            row.put("numberField_ml7c3yhz",products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购数量
//                                            row.put("numberField_ml7c3yi0",products.getJSONObject(j).getDouble("purchasePrice") * products.getJSONObject(j).getDouble("purchaseNum"));//todo：采购金额
//                                        }
//                                    }
//
//                                    // ========== 修改点4：将当前行转换为Map<String,String>并暂存 ==========
//                                    Map<String, String> rowMap = new HashMap<>();
//                                    for (Object key : row.keySet()) {
//                                        Object value = row.get(key);
//                                        rowMap.put(key.toString(), value != null ? value.toString() : "");
//                                    }
//                                    currentOrderRows.add(rowMap);
//
//                                    // ========== 修改点5：累加当前订单的汇总数据用于计算毛利率 ==========
//                                    orderTotalSalesAmount += saletotalAmount;
//                                    orderTotalPurchaseAmount += (Double)row.get("numberField_ml7c3yi0");
//                                    orderTotalFlygcb += flygcb;
//                                }
//                            }
//
//                            // ========== 修改点6：计算当前订单的毛利率 ==========
//                            double mlv = 0.0;
//                            if (orderTotalSalesAmount > 0) {
//                                mlv = (orderTotalSalesAmount - orderTotalPurchaseAmount - orderTotalFlygcb) / orderTotalSalesAmount;
//                            }
//
//                            System.out.println("订单 " + orderCode + " 毛利率: " + String.format("%.2f%%", mlv * 100));
//
//                            // ========== 修改点7：根据毛利率决定添加到哪个列表 ==========
//                            if (mlv >= 0.15) {
//                                // 高毛利率订单
//                                tabledataHigh.addAll(currentOrderRows);
//                                oldHighIds.add(orderCode);
//                                System.out.println("订单 " + orderCode + " 归类到高毛利率审批（>=15%）");
//                            } else {
//                                // 低毛利率订单
//                                tabledataLow.addAll(currentOrderRows);
//                                oldLowIds.add(orderCode);
//                                System.out.println("订单 " + orderCode + " 归类到低毛利率审批（<15%）");
//                            }
//                        }
//
//                        // ========== 修改点8：分别处理高低毛利率的审批 ==========
//
//                        // 处理高毛利率的审批 (mlv >= 0.15)
//                        if (!tabledataHigh.isEmpty()) {
//                            System.out.println("\n========== 开始处理高毛利率审批（>=15%），共 " + tabledataHigh.size() + " 条明细 ==========");
//                            List<Map<String, Object>> oldList = new ArrayList<>();
//                            oldHighIds.forEach(h->{
//                                List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
//                                        .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
//                                        .formUuid("FORM-278D56A5065641F8AC95BCA0A8CE8447D8QY")
//                                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_mmx9gyct", h)))
//                                        .build());
//                                if (ObjectUtil.isNotNull(dataList) && dataList.size()>0){
//                                    List<Map> sonList = ydService.queryDetails(YDParam.builder()
//                                            .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
//                                            .formInstanceId(UtilMap.getString(dataList.get(0),"textField_mmx9gycu"))
//                                            .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")
//                                            .tableFieldId("tableField_ml6g7k5d")
//                                            .build());
//                                    if (ObjectUtil.isNotNull(sonList) && sonList.size() > 0){
//                                        sonList.forEach(s->{
//                                            Map<String, Object> map = new HashMap<>();
//                                            TABLEFIELD_ENUM.forEach((k,v)->{
//                                                map.put(v,UtilMap.getString(s,k));
//                                            });
//                                            oldList.add(map);
//                                        });
//                                    }
//                                }
//                            });
//                            //组装数据塞到采购明细表
//                            formdataHigh.put("tableField_ml6g7k5d", tabledataHigh);
//                            formdataHigh.put("tableField_mmx6gata", oldList);
//
//                            //组装数据塞到采购审批单号明细
//                            List<Map<String, String>> orderSummaryListHigh = calculateOrderSummary(tabledataHigh);
//                            formdataHigh.put("tableField_ml7ch2pj", orderSummaryListHigh);
//
//                            //数值统计毛利率
//                            int szHigh = 0;
//                            for (Map map : orderSummaryListHigh) {
//                                Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo");
//                                log.info((String) numberFieldMm2t71jo);
//                                szHigh += Integer.parseInt((String) numberFieldMm2t71jo);
//                            }
//                            formdataHigh.put("numberField_mm2t71jp", szHigh);
//
//                            /*发起流程 - 高毛利率审批*/
//                            String userId = getDDToken(purchaserName);
//                            ydClient.operateData(YDParam.builder()
//                                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
//                                    .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")  // 高毛利率使用原表单
//                                    .userId(userId)
//                                    .formDataJson(JSON.toJSONString(formdataHigh))
//                                    .build(), YDConf.FORM_OPERATION.start).toString();
//
//                            /*修改采购订单为审批中*/
//                            for (Map map : orderSummaryListHigh) {
//                                String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk");
//                                callback(textFieldMl7ch2pk);
//                            }
//
//                            System.out.println("高毛利率审批流程发起完成");
//                        }
//
//                        // 处理低毛利率的审批 (mlv < 0.15)
//                        if (!tabledataLow.isEmpty()) {
//                            System.out.println("\n========== 开始处理低毛利率审批（<15%），共 " + tabledataLow.size() + " 条明细 ==========");
//                            List<Map<String, Object>> oldList = new ArrayList<>();
//                            oldLowIds.forEach(h->{
//                                List<Map> dataList = ydService.queryFormData_all(YDParam.builder()
//                                        .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
//                                        .formUuid("FORM-278D56A5065641F8AC95BCA0A8CE8447D8QY")
//                                        .searchFieldJson(JSON.toJSONString(UtilMap.map("textField_mmx9gyct", h)))
//                                        .build());
//                                if (ObjectUtil.isNotNull(dataList) && dataList.size()>0){
//                                    List<Map> sonList = ydService.queryDetails(YDParam.builder()
//                                            .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
//                                            .formInstanceId(UtilMap.getString(dataList.get(0),"textField_mmx9gycu"))
//                                            .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")
//                                            .tableFieldId("tableField_ml6g7k5d")
//                                            .build());
//                                    if (ObjectUtil.isNotNull(sonList) && sonList.size() > 0){
//                                        sonList.forEach(s->{
//                                            Map<String, Object> map = new HashMap<>();
//                                            TABLEFIELD_ENUM.forEach((k,v)->{
//                                                map.put(v,UtilMap.getString(s,k));
//                                            });
//                                            oldList.add(map);
//                                        });
//                                    }
//                                }
//                            });
//                            //组装数据塞到采购明细表
//                            formdataLow.put("tableField_mmx6gata", oldList);
//                            //组装数据塞到采购明细表
//                            formdataLow.put("tableField_ml6g7k5d", tabledataLow);
//
//                            //组装数据塞到采购审批单号明细
//                            List<Map<String, String>> orderSummaryListLow = calculateOrderSummary(tabledataLow);
//                            formdataLow.put("tableField_ml7ch2pj", orderSummaryListLow);
//
//                            //数值统计毛利率
//                            int szLow = 0;
//                            for (Map map : orderSummaryListLow) {
//                                Object numberFieldMm2t71jo = map.get("numberField_mm2t71jo");
//                                log.info((String) numberFieldMm2t71jo);
//                                szLow += Integer.parseInt((String) numberFieldMm2t71jo);
//                            }
//                            formdataLow.put("numberField_mm2t71jp", szLow);
//
//                            /*发起流程 - 低毛利率审批*/
//                            String userId = getDDToken(purchaserName);
//                            // ========== 修改点9：如果低毛利率需要不同表单，可以在这里修改formUuid ==========
//                            ydClient.operateData(YDParam.builder()
//                                    .appType(ydConf.getAppType()).systemToken(ydConf.getSystemToken())
//                                    .formUuid("FORM-3A54B12BE3D241218A75242B935F2987YWV2")  // 如果需要不同流程，替换这里的UUID
//                                    .userId(userId)
//                                    .formDataJson(JSON.toJSONString(formdataLow))
//                                    .build(), YDConf.FORM_OPERATION.start).toString();
//
//                            /*修改采购订单为审批中*/
//                            for (Map map : orderSummaryListLow) {
//                                String textFieldMl7ch2pk = (String) map.get("textField_ml7ch2pk");
//                                callback(textFieldMl7ch2pk);
//                            }
//
//                            System.out.println("低毛利率审批流程发起完成");
//                        }
//
//                    });
//        }

        return null;
    }

    private static final Map<String,String> TABLEFIELD_ENUM =new HashMap<>();
    static {
        TABLEFIELD_ENUM.put("textField_mm2t71jm","textField_mmx6gast");
        TABLEFIELD_ENUM.put("textField_ml6g7k5e","textField_mmx6gasu");
        TABLEFIELD_ENUM.put("textField_ml6g7k5f","textField_mmx6gasv");
        TABLEFIELD_ENUM.put("textField_ml7c3yhq","textField_mmx6gasw");
        TABLEFIELD_ENUM.put("textField_ml7c3yhr","textField_mmx6gasx");
        TABLEFIELD_ENUM.put("textField_ml7c3yhs","textField_mmx6gasy");
        TABLEFIELD_ENUM.put("numberField_ml7c3yht","numberField_mmx6gasz");
        TABLEFIELD_ENUM.put("numberField_ml7c3yhu","numberField_mmx6gat0");
        TABLEFIELD_ENUM.put("numberField_ml7c3yhv","numberField_mmx6gat1");
        TABLEFIELD_ENUM.put("textField_ml7c3yhw","textField_mmx6gat2");
        TABLEFIELD_ENUM.put("numberField_ml86221y","numberField_mmx6gat3");
        TABLEFIELD_ENUM.put("numberField_ml86221z","numberField_mmx6gat4");
        TABLEFIELD_ENUM.put("numberField_ml862220","numberField_mmx6gat5");
        TABLEFIELD_ENUM.put("textField_ml7c3yhx","textField_mmx6gat6");
        TABLEFIELD_ENUM.put("numberField_ml7c3yhy","numberField_mmx6gat7");
        TABLEFIELD_ENUM.put("numberField_ml7c3yhz","numberField_mmx6gat8");
        TABLEFIELD_ENUM.put("numberField_ml7c3yi0","numberField_mmx6gat9");
    }
    private static final Map<String,String> TABLEFIELD_ENUM2 =new HashMap<>();//修改后：修改前
    static {
        TABLEFIELD_ENUM2.put("textField_ml7ch2pk","textField_mnekj8ok");
        TABLEFIELD_ENUM2.put("numberField_ml862225","numberField_mnekj8ol");
        TABLEFIELD_ENUM2.put("numberField_ml862226","numberField_mnekj8om");
        TABLEFIELD_ENUM2.put("numberField_ml862228","numberField_mnekj8on");
        TABLEFIELD_ENUM2.put("numberField_ml86222d","numberField_mnekj8oo");

    }
    /**
     * 根据orderCode对tabledata进行分类求和
     * @param tableData 原始明细数据
     * @return 按orderCode汇总后的数据列表（只包含求和结果）
     */
    private List<Map<String, String>> calculateOrderSummary(List<Map<String, Object>> tableData) {
        // 使用Map暂存每个orderCode的汇总数据
        Map<String, Map<String, Double>> summaryMap = new LinkedHashMap<>();

        for (Map<String, Object> row : tableData) {
//            String orderCode = row.get("textField_mm2t71jm"); // 采购订单号
            String orderCode = UtilMap.getString(row,"textField_mm2t71jm");
            String saleOrderCode = UtilMap.getString(row,"textField_ml6g7k5f");
            String orderFax = UtilMap.getString(row,"orderFax");
            if (orderCode == null || orderCode.isEmpty()) {
                continue;
            }

            // 获取或创建该订单的汇总Map
            Map<String, Double> orderSum = summaryMap.computeIfAbsent(orderCode+"~"+orderFax + "~"+saleOrderCode,
                    k -> {
                        Map<String, Double> newMap = new HashMap<>();
                        newMap.put("salesAmount", 0.0);      // 销售金额总和
                        newMap.put("purchaseAmount", 0.0);   // 采购金额总和
                        newMap.put("flygcb", 0.0);           // 辅料预估成本总和
                        return newMap;
                    });

            // 累加各项金额
            String salesAmountStr = UtilMap.getString(row,"numberField_ml862220");
            String purchaseAmountStr = UtilMap.getString(row,"numberField_ml7c3yi0");
            String flygcbStr = UtilMap.getString(row,"numberField_ml86221z");

            try {
                if (salesAmountStr != null && !salesAmountStr.isEmpty()) {
                    orderSum.put("salesAmount",
                            orderSum.get("salesAmount") + Double.parseDouble(salesAmountStr));
                }

                if (purchaseAmountStr != null && !purchaseAmountStr.isEmpty()) {
                    orderSum.put("purchaseAmount",
                            orderSum.get("purchaseAmount") + Double.parseDouble(purchaseAmountStr));
                }

                if (flygcbStr != null && !flygcbStr.isEmpty()) {
                    orderSum.put("flygcb",
                            orderSum.get("flygcb") + Double.parseDouble(flygcbStr));
                }



            } catch (NumberFormatException e) {
                System.err.println("数字格式错误: " + e.getMessage());
            }
        }

        // 转换为最终的List<Map<String, String>>
        List<Map<String, String>> result = new ArrayList<>();

        for (Map.Entry<String, Map<String, Double>> entry : summaryMap.entrySet()) {
            String[] split = entry.getKey().split("~");
            String orderCode = split[0];
            String saleOrderCode = split[2];
            Double orderFax = Double.parseDouble(split[1]);
            Map<String, Double> sums = entry.getValue();

            double salesAmount = sums.get("salesAmount");
            double purchaseAmount = sums.get("purchaseAmount");
            double flygcb = sums.get("flygcb");

            // 构建结果行
            Map<String, String> summaryRow = new LinkedHashMap<>();
            summaryRow.put("textField_ml7ch2pk", orderCode);//orderCode:采购审批单单号
            summaryRow.put("textField_motpbfwq", saleOrderCode);//saleOrderCode:销售订单单号
            summaryRow.put("numberField_ml862225", formatNumber(salesAmount));//salesAmount:销售总金额
            summaryRow.put("numberField_ml862226", formatNumber(purchaseAmount));//purchaseAmount:采购订单总金额
            summaryRow.put("numberField_ml862228", formatNumber(flygcb));//flygcb:辅料预估总成本
            summaryRow.put("numberField_ml86222d",formatNumber((salesAmount - purchaseAmount/orderFax - flygcb) / salesAmount * 100));//毛利率
            Double mlv = (salesAmount - purchaseAmount/orderFax - flygcb) / salesAmount;
            if(mlv >= 0.15){
                summaryRow.put("numberField_mm2t71jo", String.valueOf(1));
            }else {
                summaryRow.put("numberField_mm2t71jo", String.valueOf(0));
            }
            result.add(summaryRow);
        }

        return result;
    }

    /**
     * 格式化数字，去除多余的.0
     */
    private String formatNumber(double number) {
        if (Math.abs(number - Math.round(number)) < 0.000001) {
            return String.valueOf((long) number);
        } else {
            return String.format("%.2f", number);
        }
    }

    /*采购订单发起更新状态*/
    @SneakyThrows
    public McR callback(String orderNum){
        HashMap header = new HashMap();
        header.put("X-AUTH",HeiHuAccessToken().getData().toString());
        header.put("Content-Type","application/json");
        HashMap body = new HashMap();
        body.put("orderCode",orderNum);//订单编号
        String jsonString2 = UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/queryList2", header, null, body);//todo:查询采购订单
        JSONArray dataArray = JSONObject.parseObject(jsonString2).getJSONArray("data");
        for (int k=0;k<dataArray.size();k++) {
            JSONObject data = dataArray.getJSONObject(k);
            //提取订单基本信息 并赋值
            HashMap body1 = new HashMap();
            body1.put("orderCode",data.getString("orderCode"));//订单编号：orderCode
            body1.put("vendorCode",data.getString("vendorCode"));//供应商编码：gysnumber
            String aa = data.getLong("purchaseTime").toString();
            String purchaseTime = Instant.ofEpochMilli(Long.parseLong(aa))
                    .atZone(ZoneId.of("Asia/Shanghai"))
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            body1.put("purchaseTime",purchaseTime);//采购日期：purchaseTime
            String bb = data.getLong("planArrivalTime").toString();
            String planArrivalTime = Instant.ofEpochMilli(Long.parseLong(bb))
                    .atZone(ZoneId.of("Asia/Shanghai"))
                    .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            body1.put("planArrivalTime",planArrivalTime);//计划到货日期：planArrivalTime
            ArrayList<Map<String,String>> customFiled = new ArrayList();
            HashMap field = new HashMap();
            field.put("name","采购订单钉钉审批状态");
            field.put("value","审批中");//审批状态
            customFiled.add(field);
            body1.put("purchaseOrderCustomFieldsValue",customFiled);
            UtilHttp.doPost("https://liteweb.blacklake.cn/api/dytin/external/purchaseOrder/update", header, null, body1);
        }

        return McR.success();
    }



    /*获取宜搭采购订单汇总*/
    @SneakyThrows
    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);
    }
    // 定义需要汇总的字段名集合
    private static final Set<String> SUM_FIELDS = new HashSet<>(Arrays.asList(
            "numberField_ml7c3yhz",
            "numberField_ml7c3yi0",
            "numberField_ml862220",
            "numberField_ml86221z",
            "numberField_ml7c3yhv",
            "numberField_ml7c3yht"
    ));
    /**
     * 对 List<Map> 按非汇总字段分组，并对汇总字段使用 BigDecimal 求和
     *
     * @param list 原始数据列表
     * @return 分组汇总后的数据列表
     */
    public List<Map<String, Object>> groupAndSum(List<Map<String,Object>> list) {
        if (list == null || list.isEmpty()) {
            return new ArrayList<>();
        }

        // 1. 按非汇总字段作为分组键进行分组
        Map<Map<String, Object>, List<Map<String, Object>>> grouped = list.stream()
                .collect(Collectors.groupingBy(map -> {
                    // 提取非汇总字段，构造一个不可变 Map 作为分组键
                    Map<String, Object> keyMap = new HashMap<>();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        if (!SUM_FIELDS.contains(entry.getKey()) && !entry.getKey().contains("_value")) {
                            keyMap.put(entry.getKey(), entry.getValue());
                        }
                    }
                    return Collections.unmodifiableMap(keyMap);
                }));

        // 2. 对每个分组内的汇总字段进行累加，并组装结果 Map
        return grouped.entrySet().stream()
                .map(entry -> {
                    // 分组键（非汇总字段的集合）
                    Map<String, Object> groupKey = entry.getKey();
                    List<Map<String, Object>> groupList = entry.getValue();

                    // 初始化汇总结果的 Map，先放入所有分组字段
                    Map<String, Object> resultMap = new HashMap<>(groupKey);

                    // 对六个汇总字段分别求和
                    for (String sumField : SUM_FIELDS) {
                        BigDecimal sum = groupList.stream()
                                .map(m -> m.get(sumField))          // 获取字段值
                                .map(HeiHuOrderServiceImpl::toBigDecimal) // 转为 BigDecimal，null 视为 0
                                .reduce(BigDecimal.ZERO, BigDecimal::add);
                        resultMap.put(sumField, sum);
                    }
                    return resultMap;
                })
                .collect(Collectors.toList());
    }

    /**
     * 将 Object 转为 BigDecimal，支持 Number 和 String 类型
     */
    private static BigDecimal toBigDecimal(Object value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return BigDecimal.valueOf(((Number) value).doubleValue());
        }
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO; // 或根据业务抛出异常
        }
    }
}
