package com.malk.yiyao.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IORuntimeException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.yiyao.service.YiyaoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class YiyaoServiceImpl implements YiyaoService {

    @Autowired
    private YDClient ydClient;

    @Autowired
    private YDConf ydConf;

    @Autowired
    private DDClient ddClient;

    //更新逸曜合同档案子表省市
    public McR updateYiyao1(){
        /*List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","textField_m7lccg50");
        map.put("value","");
        map.put("type","TEXT");
        map.put("operator","eq");
        map.put("componentName","TextField");
        map.put("parentId","tableField_lvuku8m3");
        a.add(map);*/

        long beginTime = System.currentTimeMillis();
        //查询所有合同档案
        List<Map> dataList = getYdDataList("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB", "", YDConf.FORM_QUERY.retrieve_list_all);

        long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;
        log.info("查询所有合同耗时:{}秒", time);
        /*List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(a))
                .pageNumber(1)
                .pageSize(100).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();*/

        int i = 1;

        for (Map data : dataList) {
            Map formData = (Map) data.get("formData");
            String formInstId = data.get("formInstanceId").toString();

            //最终用户子表
            List<Map> customerList = UtilMap.getList(formData,"tableField_lvuku8m3");

            boolean flag = false;

            for (Map customer : customerList) {
                String customerName = UtilMap.getString(customer, "selectField_lw4jf0ys");

                if (Strings.isBlank(UtilMap.getString(customer,"textField_m7lccg50")) && Strings.isBlank(UtilMap.getString(customer,"textField_m7lccg51"))){
                    flag = true;
                    //查询客户省市
                    DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_lr60luaz", customerName)))
                            .build(), YDConf.FORM_QUERY.retrieve_list);
                    List<Map> data2 = (List<Map>) ddrNew.getData();
                    if (!data2.isEmpty()){
                        Map customerFormData = (Map) data2.get(0).get("formData");

                        if (Strings.isNotBlank(UtilMap.getString(customerFormData,"textField_m7u2p5n8")) && Strings.isNotBlank(UtilMap.getString(customerFormData,"textField_m7u2p5nd"))){
                            String province = customerFormData.get("textField_m7u2p5n8").toString();//省
                            String city = customerFormData.get("textField_m7u2p5nd").toString();//市

                            customer.put("textField_m7lccg50",province);
                            customer.put("textField_m7lccg51",city);
                        }
                    }
                }
            }

            if (flag){
                Map updateFormData = new HashMap();
                updateFormData.put("tableField_lvuku8m3",customerList);

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

                log.info("第{}条更新完成",i);
            }else {
                log.info("第{}条无需更新",i);
            }

            i++;
        }

        return McR.success();
    }

    @Override
    public McR updateYiyao2() {
        //查询所有审批通过的项目验收售后流程
        List<Map> conditions = new ArrayList<>();
        Map approve = new HashMap();
        approve.put("key", "processApprovedResult");
        approve.put("value", new String[]{"agree"});
        approve.put("type", "ARRAY");
        approve.put("operator", "in");
        approve.put("componentName", "SelectField");
        conditions.add(approve);

        List<Map> dataList = getYdDataList("FORM-4B4AE7C111604CDE85729D3FD8797807RG7J", JSONObject.toJSONString(conditions), YDConf.FORM_QUERY.retrieve_list_all);

        for (Map data : dataList) {
            //查询审核通过时间
            String formInstId = data.get("formInstanceId").toString();

            //获取审批记录
            Map param = new HashMap<>();
            param.put("appType",ydConf.getAppType());
            param.put("systemToken",ydConf.getSystemToken());
            param.put("userId","02145933103936490950");//shs
            param.put("processInstanceId",formInstId);

            DDR_New ddrNew2 = (DDR_New) UtilHttp.doGet("https://api.dingtalk.com/v1.0/yida/processes/operationRecords", ddClient.initTokenHeader(), param, DDR_New.class);
            List<Map> result = (List<Map>) ddrNew2.getResult();

            String endTime = result.get(result.size() - 1).get("operateTimeGMT").toString().replace("T", " ").replace("Z", "");

            //将日期字符串 年月日时分转化为时间戳
            endTime = String.valueOf(DateUtil.parse(endTime).getTime());

            ydClient.operateData(YDParam.builder()
                    .formInstId(formInstId)
                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("dateField_ma0nfifc", endTime)))
                    .useLatestVersion(true)
                    .build(), YDConf.FORM_OPERATION.update);


        }


        return null;
    }

    //更新合同档案客户关联表单、产品关联表单
    @Override
    public McR updateYiyao3() {
        /*List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","textField_lvbu33zk");
        map.put("value","202420026");
        map.put("type","TEXT");
        map.put("operator","eq");
        map.put("componentName","TextField");
        a.add(map);*/

        long beginTime = System.currentTimeMillis();

        //查询所有合同档案
//        List<Map> dataList = getYdDataList("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB", JSONObject.toJSONString(a), YDConf.FORM_QUERY.retrieve_list_all);
        List<Map> dataList = getYdDataList("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB", "", YDConf.FORM_QUERY.retrieve_list_all);

        long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;
        log.info("查询所有合同耗时:{}秒", time);
        /*List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(a))
                .pageNumber(1)
                .pageSize(100).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();*/

        int i = 1;

        boolean flag = false;

        for (Map data : dataList) {
            /*if (i <= 1542){
                i++;
                continue;
            }*/
            Map formData = (Map) data.get("formData");
            String formInstId = data.get("formInstanceId").toString();

            //所有客户平铺
            List<Map> customerMapList = new ArrayList<>();
            //所有产品平铺
            List<Map> productMapList = new ArrayList<>();

            //最终用户子表
            List<Map> customerList = UtilMap.getList(formData,"tableField_lvuku8m3");

            for (Map customer : customerList) {
                //最终客户关联表单是否有值
                if (Objects.nonNull(customer.get("associationFormField_lxwns03h_id"))){
                    String jsonString3 = customer.get("associationFormField_lxwns03h_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    customerMapList.addAll(materialMap);

                    continue;
                }

                String customerName = UtilMap.getString(customer, "selectField_lw4jf0ys");

                if (Strings.isBlank(customerName)){
                    continue;
                }

                //查询客户
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    //最终用户关联表单
                    Map customerMap = new HashMap();
                    customerMap.put("formType", "receipt");
                    customerMap.put("formUuid", "FORM-2A666T61HPMCPMEX8BBVV6R1XFKI23ZTWECKLV");
                    customerMap.put("instanceId", formInstanceId);
                    customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    customerMap.put("title", customerName);

                    List<Map> list = new ArrayList<>();
                    list.add(customerMap);

                    customer.put("associationFormField_lxwns03h",list);

                    customerMapList.add(customerMap);

                    flag = true;
                }
            }

            //合同他方子表
            List<Map> customerList2 = UtilMap.getList(formData,"tableField_lv0mefjq");


            for (Map customer : customerList2) {
                //合同他方关联表单是否有值
                if (Objects.nonNull(customer.get("associationFormField_lxwns03i_id"))){
                    String jsonString3 = customer.get("associationFormField_lxwns03i_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    customerMapList.addAll(materialMap);

                    continue;
                }

                String customerName = UtilMap.getString(customer, "selectField_lv0mf6ew");

                if (Strings.isBlank(customerName)){
                    continue;
                }

                //查询客户
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    //合同他方关联表单
                    Map customerMap = new HashMap();
                    customerMap.put("formType", "receipt");
                    customerMap.put("formUuid", "FORM-2A666T61HPMCPMEX8BBVV6R1XFKI23ZTWECKLV");
                    customerMap.put("instanceId", formInstanceId);
                    customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    customerMap.put("title", customerName);

                    List<Map> list = new ArrayList<>();
                    list.add(customerMap);

                    customer.put("associationFormField_lxwns03i",list);

                    customerMapList.add(customerMap);

                    flag = true;
                }
            }

            //标的物（产品/服务）分项价格表
            List<Map> productList = UtilMap.getList(formData,"tableField_ltdyaj0x");
            for (Map product : productList) {
                //产品关联表单是否有值
                if (Objects.nonNull(product.get("associationFormField_lu2hd407_id"))){

                    String jsonString3 = product.get("associationFormField_lu2hd407_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    productMapList.addAll(materialMap);

                    continue;
                }

                String productName = UtilMap.getString(product, "selectField_ltdyaj0y");

                if (Strings.isBlank(productName)){
                    continue;
                }

                //查询产品
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-8CFC5CD540EF4889813C98401D2EA65A35D3")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("selectField_lwg3mtaa", productName,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    //产品关联表单
                    Map productMap = new HashMap();
                    productMap.put("formType", "receipt");
                    productMap.put("formUuid", "FORM-8CFC5CD540EF4889813C98401D2EA65A35D3");
                    productMap.put("instanceId", formInstanceId);
                    productMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    productMap.put("title", productName);

                    List<Map> list = new ArrayList<>();
                    list.add(productMap);

                    product.put("associationFormField_lu2hd407",list);

                    productMapList.add(productMap);

                    flag = true;
                }
            }

            Map updateFormData = new HashMap();

            boolean flag2 = false;


            if ((Objects.isNull(formData.get("associationFormField_m9rwbzc7_id")) || formData.get("associationFormField_m9rwbzc7_id").toString().equals("\"[]\"")) && !customerMapList.isEmpty()){
                //根据instanceId去重
                List<Map> distinctList = customerMapList.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("instanceId"), // Key is instanceId
                                m -> m,                   // Value is the map itself
                                (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                        ))
                        .values()
                        .stream()
                        .collect(Collectors.toList());

                updateFormData.put("associationFormField_m9rwbzc7",distinctList);//所有客户平铺
                flag2 = true;
            }


            if ((Objects.isNull(formData.get("associationFormField_m9v36epw_id")) || formData.get("associationFormField_m9v36epw_id").toString().equals("\"[]\"")) && !productMapList.isEmpty()){
                //根据instanceId去重
                List<Map> distinctList = productMapList.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("instanceId"), // Key is instanceId
                                m -> m,                   // Value is the map itself
                                (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                        ))
                        .values()
                        .stream()
                        .collect(Collectors.toList());

                updateFormData.put("associationFormField_m9v36epw",distinctList);//所有产品平铺
                flag2 = true;
            }


            if (flag){
                updateFormData.put("tableField_lvuku8m3",customerList);//最终用户子表
                updateFormData.put("tableField_lv0mefjq",customerList2);//合同他方子表
                updateFormData.put("tableField_ltdyaj0x",productList);//产品子表

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

                log.info("第{}条更新完成,实例id：{}",i,formInstId);

                i++;

                continue;
            }

            if (flag2){
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);

                log.info("第{}条更新完成,实例id：{}",i,formInstId);
            }else {
                log.info("第{}条无需更新,实例id：{}",i,formInstId);
            }

            i++;
        }

        return McR.success();
    }

    //更新销售合同流程客户关联表单、产品关联表单、合同档案关联表单
    @Override
    public McR updateYiyao4() {
        /*List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","serialNumberField_lswvfews");
        map.put("value","YZL202413541");
        map.put("type","TEXT");
        map.put("operator","eq");
        map.put("componentName","TextField");
        a.add(map);*/

        long beginTime = System.currentTimeMillis();

        //查询所有合同档案
//        List<Map> dataList = getYdDataList("FORM-E07BCCD6DA2940F496880177435A20D4OSQK", JSONObject.toJSONString(a), YDConf.FORM_QUERY.retrieve_list_all);
        List<Map> dataList = getYdDataList("FORM-E07BCCD6DA2940F496880177435A20D4OSQK", "", YDConf.FORM_QUERY.retrieve_list_all);

        long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;
        log.info("查询所有合同耗时:{}秒", time);
        /*List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(a))
                .pageNumber(1)
                .pageSize(100).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();*/

        int i = 1;

        for (Map data : dataList) {
            /*if (i <= 1542){
                i++;
                continue;
            }*/
            Map formData = (Map) data.get("formData");
            String formInstId = data.get("formInstanceId").toString();

            //所有客户平铺
            List<Map> customerMapList = new ArrayList<>();
            //所有产品平铺
            List<Map> productMapList = new ArrayList<>();

            //最终用户子表
            List<Map> customerList = UtilMap.getList(formData,"tableField_lvuku8m3");

            for (Map customer : customerList) {
                //最终客户关联表单是否有值
                if (Objects.nonNull(customer.get("associationFormField_lxwns03h_id"))){
                    String jsonString3 = customer.get("associationFormField_lxwns03h_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    customerMapList.addAll(materialMap);
                }
            }

            //合同他方子表
            List<Map> customerList2 = UtilMap.getList(formData,"tableField_lv0mefjq");

            for (Map customer : customerList2) {
                //合同他方关联表单是否有值
                if (Objects.nonNull(customer.get("associationFormField_lxwns03i_id"))){
                    String jsonString3 = customer.get("associationFormField_lxwns03i_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    customerMapList.addAll(materialMap);
                }
            }

            //标的物（产品/服务）分项价格表
            List<Map> productList = UtilMap.getList(formData,"tableField_ltdyaj0x");
            for (Map product : productList) {
                //产品关联表单是否有值
                if (Objects.nonNull(product.get("associationFormField_lu2hd407_id"))){

                    String jsonString3 = product.get("associationFormField_lu2hd407_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    productMapList.addAll(materialMap);
                }
            }

            Map updateFormData = new HashMap();

            if ((Objects.isNull(formData.get("associationFormField_m9rwbzc7_id")) || formData.get("associationFormField_m9rwbzc7_id").toString().equals("\"[]\"")) && !customerMapList.isEmpty()){
                //根据instanceId去重
                List<Map> distinctList = customerMapList.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("instanceId"), // Key is instanceId
                                m -> m,                   // Value is the map itself
                                (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                        ))
                        .values()
                        .stream()
                        .collect(Collectors.toList());

                updateFormData.put("associationFormField_m9rwbzc7",distinctList);//所有客户平铺
            }

            if ((Objects.isNull(formData.get("associationFormField_m9v36epw_id")) || formData.get("associationFormField_m9v36epw_id").toString().equals("\"[]\"")) && !productMapList.isEmpty()){
                //根据instanceId去重
                List<Map> distinctList = productMapList.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("instanceId"), // Key is instanceId
                                m -> m,                   // Value is the map itself
                                (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                        ))
                        .values()
                        .stream()
                        .collect(Collectors.toList());

                updateFormData.put("associationFormField_m9v36epw",distinctList);//所有产品平铺
            }

            //合同档案关联表单
            String code = UtilMap.getString(formData, "serialNumberField_lswvfews");

            if (Objects.isNull(formData.get("associationFormField_m9shwxb2_id")) || formData.get("associationFormField_m9shwxb2_id").toString().equals("\"[]\"")){
                //查询合同档案
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lu9l6otz", code,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    Map formData2 = (Map) data2.get(0).get("formData");

                    String code2 = formData2.get("serialNumberField_lswvfews").toString();


                    Map productMap = new HashMap();
                    productMap.put("formType", "receipt");
                    productMap.put("formUuid", "FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB");
                    productMap.put("instanceId", formInstanceId);
                    productMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    productMap.put("title", code2);

                    List<Map> list = new ArrayList<>();
                    list.add(productMap);

                    updateFormData.put("associationFormField_m9shwxb2",list);
                }

            }

            if (!updateFormData.keySet().isEmpty()){
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);

                log.info("第{}条更新完成,实例id：{}",i,formInstId);
            }else {
                log.info("第{}条无需更新,实例id：{}",i,formInstId);
            }

            i++;
        }

        return McR.success();


    }

    //更新销售合同流程客户关联表单、产品关联表单、合同档案关联表单
    @Override
    public McR updateYiyao5() {
        /*List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","serialNumberField_lswvfews");
        map.put("value","HZY202420002");
        map.put("type","TEXT");
        map.put("operator","eq");
        map.put("componentName","TextField");
        a.add(map);*/

        long beginTime = System.currentTimeMillis();

        //查询所有合同档案
//        List<Map> dataList = getYdDataList("FORM-EE13266CB2AA4784A9FF653C200CA170JEFN", JSONObject.toJSONString(a), YDConf.FORM_QUERY.retrieve_list_all);
        List<Map> dataList = getYdDataList("FORM-EE13266CB2AA4784A9FF653C200CA170JEFN", "", YDConf.FORM_QUERY.retrieve_list_all);

        long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;
        log.info("查询所有合同耗时:{}秒", time);
        /*List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(a))
                .pageNumber(1)
                .pageSize(100).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();*/

        int i = 1;

        for (Map data : dataList) {
            /*if (i <= 1542){
                i++;
                continue;
            }*/
            Map formData = (Map) data.get("formData");
            String formInstId = data.get("formInstanceId").toString();

            //所有客户平铺
            List<Map> customerMapList = new ArrayList<>();
            //所有产品平铺
            List<Map> productMapList = new ArrayList<>();

            //最终用户子表
            List<Map> customerList = UtilMap.getList(formData,"tableField_lv4ynlzg");

            boolean flag1 = false;
            boolean flag2 = false;
            boolean flag3 = false;

            Map updateFormData = new HashMap();

            for (Map customer : customerList) {
                //最终客户关联表单是否有值
                if (Objects.nonNull(customer.get("associationFormField_m1g3hbdb_id")) && !customer.get("associationFormField_m1g3hbdb_id").toString().equals("\"[]\"")){
                    String jsonString3 = customer.get("associationFormField_m1g3hbdb_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    customerMapList.addAll(materialMap);
                    continue;
                }

                String customerName = UtilMap.getString(customer, "selectField_ltdyaj0m");

                if (Strings.isBlank(customerName)){
                    continue;
                }

                //查询客户
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    //最终用户关联表单
                    Map customerMap = new HashMap();
                    customerMap.put("formType", "receipt");
                    customerMap.put("formUuid", "FORM-2A666T61HPMCPMEX8BBVV6R1XFKI23ZTWECKLV");
                    customerMap.put("instanceId", formInstanceId);
                    customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    customerMap.put("title", customerName);

                    List<Map> list = new ArrayList<>();
                    list.add(customerMap);

                    customer.put("associationFormField_m1g3hbdb",list);

                    customerMapList.add(customerMap);

                    flag1 = true;
                }
            }
            if (flag1){
                updateFormData.put("tableField_lv4ynlzg",customerList);
            }

            //合同他方子表
            List<Map> customerList2 = UtilMap.getList(formData,"tableField_lv0mefjq");

            for (Map customer : customerList2) {
                //合同他方关联表单是否有值
                if (Objects.nonNull(customer.get("associationFormField_lxwns03i_id")) && !customer.get("associationFormField_lxwns03i_id").toString().equals("\"[]\"")){
                    String jsonString3 = customer.get("associationFormField_lxwns03i_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    customerMapList.addAll(materialMap);

                    continue;
                }

                String customerName = UtilMap.getString(customer, "selectField_lucf348t");

                if (Strings.isBlank(customerName)){
                    continue;
                }

                //查询客户
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    //合同他方关联表单
                    Map customerMap = new HashMap();
                    customerMap.put("formType", "receipt");
                    customerMap.put("formUuid", "FORM-2A666T61HPMCPMEX8BBVV6R1XFKI23ZTWECKLV");
                    customerMap.put("instanceId", formInstanceId);
                    customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    customerMap.put("title", customerName);

                    List<Map> list = new ArrayList<>();
                    list.add(customerMap);

                    customer.put("associationFormField_lxwns03i",list);

                    customerMapList.add(customerMap);

                    flag2 = true;
                }
            }
            if (flag2){
                updateFormData.put("tableField_lv0mefjq",customerList2);
            }



            //标的物（产品/服务）分项价格表
            List<Map> productList = UtilMap.getList(formData,"tableField_m731nwwb");
            for (Map product : productList) {
                //产品关联表单是否有值
                if (Objects.nonNull(product.get("associationFormField_lu2hd407_id")) && !product.get("associationFormField_lu2hd407_id").toString().equals("\"[]\"")){

                    String jsonString3 = product.get("associationFormField_lu2hd407_id").toString();
                    String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                    List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                    productMapList.addAll(materialMap);

                    continue;
                }

                String productName = UtilMap.getString(product, "selectField_m731nwwa");

                if (Strings.isBlank(productName)){
                    continue;
                }

                //查询产品
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-8CFC5CD540EF4889813C98401D2EA65A35D3")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lwg48ppe", productName,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    //产品关联表单
                    Map productMap = new HashMap();
                    productMap.put("formType", "receipt");
                    productMap.put("formUuid", "FORM-8CFC5CD540EF4889813C98401D2EA65A35D3");
                    productMap.put("instanceId", formInstanceId);
                    productMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    productMap.put("title", productName);

                    List<Map> list = new ArrayList<>();
                    list.add(productMap);

                    product.put("associationFormField_lu2hd407",list);

                    productMapList.add(productMap);

                    flag3 = true;
                }
            }
            if (flag3){
                updateFormData.put("tableField_m731nwwb",productList);
            }



            if ((Objects.isNull(formData.get("associationFormField_m9rwbzc7_id")) || formData.get("associationFormField_m9rwbzc7_id").toString().equals("\"[]\"")) && !customerMapList.isEmpty()){
                //根据instanceId去重
                List<Map> distinctList = customerMapList.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("instanceId"), // Key is instanceId
                                m -> m,                   // Value is the map itself
                                (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                        ))
                        .values()
                        .stream()
                        .collect(Collectors.toList());

                updateFormData.put("associationFormField_m9rwbzc7",distinctList);//所有客户平铺
            }

            if ((Objects.isNull(formData.get("associationFormField_m9v36epw_id")) || formData.get("associationFormField_m9v36epw_id").toString().equals("\"[]\"")) && !productMapList.isEmpty()){
                //根据instanceId去重
                List<Map> distinctList = productMapList.stream()
                        .collect(Collectors.toMap(
                                m -> m.get("instanceId"), // Key is instanceId
                                m -> m,                   // Value is the map itself
                                (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                        ))
                        .values()
                        .stream()
                        .collect(Collectors.toList());

                updateFormData.put("associationFormField_m9v36epw",distinctList);//所有产品平铺
            }

            //合同档案关联表单
            String code = UtilMap.getString(formData, "serialNumberField_lswvfews");

            if (Objects.isNull(formData.get("associationFormField_m9shwxb2_id")) || formData.get("associationFormField_m9shwxb2_id").toString().equals("\"[]\"")){
                //查询合同档案
                DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                        .formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lvbu33zk", code,"eq"))))
                        .build(), YDConf.FORM_QUERY.retrieve_list);

                List<Map> data2 = (List<Map>) ddrNew.getData();

                if (!data2.isEmpty()){
                    String formInstanceId = data2.get(0).get("formInstanceId").toString();

                    Map formData2 = (Map) data2.get(0).get("formData");

                    String code2 = formData2.get("serialNumberField_lswvfews").toString();


                    Map productMap = new HashMap();
                    productMap.put("formType", "receipt");
                    productMap.put("formUuid", "FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB");
                    productMap.put("instanceId", formInstanceId);
                    productMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                    productMap.put("title", code2);

                    List<Map> list = new ArrayList<>();
                    list.add(productMap);

                    updateFormData.put("associationFormField_m9shwxb2",list);
                }

            }

            if (!updateFormData.keySet().isEmpty()){
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);

                log.info("第{}条更新完成,实例id：{}",i,formInstId);
            }else {
                log.info("第{}条无需更新,实例id：{}",i,formInstId);
            }

            i++;
        }

        return McR.success();


    }

    //更新项目档案客户关联表单
    @Override
    public McR updateYiyao6() {
        List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","serialNumberField_lw77nrz9");
        map.put("value","5747");
        map.put("type","TEXT");
        map.put("operator","eq");
        map.put("componentName","TextField");
        a.add(map);

        long beginTime = System.currentTimeMillis();

        //查询所有合同档案
//        List<Map> dataList = getYdDataList("FORM-A1024BB825D7462A8BDD52ABE890B484O63U", JSONObject.toJSONString(a), YDConf.FORM_QUERY.retrieve_list_all);
        List<Map> dataList = getYdDataList("FORM-A1024BB825D7462A8BDD52ABE890B484O63U", "", YDConf.FORM_QUERY.retrieve_list_all);

        long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;
        log.info("查询所有数据耗时:{}秒", time);
        /*List<Map> dataList = (List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-E83C9E307FFB4A978E0CB8DE1B899E9DXTXB")
                        .searchCondition(JSONObject.toJSONString(a))
                .pageNumber(1)
                .pageSize(100).build(), YDConf.FORM_QUERY.retrieve_list_all).getData();*/

        int i = 1;

        for (Map data : dataList) {
            Map formData = (Map) data.get("formData");
            String formInstId = data.get("formInstanceId").toString();

            Map updateFormData = new HashMap();
            if (Objects.isNull(formData.get("associationFormField_lw4kkjrb_id")) || formData.get("associationFormField_lw4kkjrb_id").toString().equals("\"[]\"")){
                String customerName = UtilMap.getString(formData, "textField_lw4m6q64");

                if (Strings.isNotBlank(customerName)){
                    //查询客户
                    DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                            .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName,"eq"))))
                            .build(), YDConf.FORM_QUERY.retrieve_list);

                    List<Map> data2 = (List<Map>) ddrNew.getData();

                    if (!data2.isEmpty()){
                        String formInstanceId = data2.get(0).get("formInstanceId").toString();

                        //客户关联表单
                        Map customerMap = new HashMap();
                        customerMap.put("formType", "receipt");
                        customerMap.put("formUuid", "FORM-4020139BCB3341349EE81F5332085D35C294");
                        customerMap.put("instanceId", formInstanceId);
                        customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                        customerMap.put("title", customerName);

                        List<Map> list = new ArrayList<>();
                        list.add(customerMap);

                        updateFormData.put("associationFormField_lw4kkjrb",list);
                    }
                }
            }

            if (!updateFormData.keySet().isEmpty()){
                ydClient.operateData(YDParam.builder()
                        .formInstId(formInstId)
                        .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                        .useLatestVersion(true)
                        .build(), YDConf.FORM_OPERATION.update);

                log.info("第{}条更新完成,实例id：{}",i,formInstId);
            }else {
                log.info("第{}条无需更新,实例id：{}",i,formInstId);
            }

            i++;
        }

        return McR.success();
    }

    //更新交付日报客户关联表单
    @Override
    public McR updateYiyao7() {
        /*List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","serialNumberField_lsyab9r1");
        map.put("value","0071");
        map.put("type","TEXT");
        map.put("operator","eq");
        map.put("componentName","TextField");
        a.add(map);*/

//        long beginTime = System.currentTimeMillis();

        //查询所有日报档案
//        List<Map> dataList = getYdDataList("FORM-F772E0DBE98340F690C2412B0A168EB4AG9H", JSONObject.toJSONString(a), YDConf.FORM_QUERY.retrieve_list_all);
//        List<Map> dataList = getYdDataList("FORM-F772E0DBE98340F690C2412B0A168EB4AG9H", "", YDConf.FORM_QUERY.retrieve_list_all);

        DDR_New ddrNew2 = new DDR_New();
        int pageNumber = 78;
        int pageSize = 100;
        do {
                ddrNew2 = ydClient.queryData(YDParam.builder().formUuid("FORM-F772E0DBE98340F690C2412B0A168EB4AG9H")
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), YDConf.FORM_QUERY.retrieve_list_all);

            List<Map> dataList = (List<Map>) ddrNew2.getData();

            int i = (pageNumber - 1) * pageSize + 1;

            for (Map data : dataList) {
                Map formData = (Map) data.get("formData");
                String formInstId = data.get("formInstanceId").toString();

                Map updateFormData = new HashMap();
                if (Objects.isNull(formData.get("associationFormField_m9rwbzc7_id")) || formData.get("associationFormField_m9rwbzc7_id").toString().equals("\"[]\"")) {
                    //实施内容
                    List<Map> list1 = UtilMap.getList(formData, "tableField_ltnynyzy");
                    //质保期、过保期等已交付无维保合同客户
                    List<Map> list2 = UtilMap.getList(formData, "tableField_lz0mdudy");
                    //维保内容
                    List<Map> list3 = UtilMap.getList(formData, "tableField_ltnynz04");

                    boolean flag1 = false;
                    boolean flag2 = false;
                    boolean flag3 = false;

                    //所有客户平铺
                    List<Map> customerMapList = new ArrayList<>();


                    for (Map map1 : list1) {
                        //移除其他键防止数据被重置
                        map1.keySet().removeIf(key -> !key.equals("associationFormField_maes524b_id") && !key.equals("selectField_luw0d483"));

                        //最终客户关联表单是否有值
                        if (Objects.nonNull(map1.get("associationFormField_maes524b_id")) && !map1.get("associationFormField_maes524b_id").toString().equals("\"[]\"")) {
                            String jsonString3 = map1.get("associationFormField_maes524b_id").toString();
                            String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                            List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                            customerMapList.addAll(materialMap);

                            continue;
                        }

                        String customerName = UtilMap.getString(map1, "selectField_luw0d483");
                        if (Strings.isNotBlank(customerName)) {
                            //查询客户
                            DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                                    .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName, "eq"))))
                                    .build(), YDConf.FORM_QUERY.retrieve_list);

                            List<Map> data2 = (List<Map>) ddrNew.getData();

                            if (!data2.isEmpty()) {
                                String formInstanceId = data2.get(0).get("formInstanceId").toString();

                                //客户关联表单
                                Map customerMap = new HashMap();
                                customerMap.put("formType", "receipt");
                                customerMap.put("formUuid", "FORM-4020139BCB3341349EE81F5332085D35C294");
                                customerMap.put("instanceId", formInstanceId);
                                customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                                customerMap.put("title", customerName);

                                List<Map> list = new ArrayList<>();
                                list.add(customerMap);

                                map1.put("associationFormField_maes524b",list);


                                customerMapList.add(customerMap);

                                flag1 = true;
                            }
                        }
                    }
                    if (flag1){
                        updateFormData.put("tableField_ltnynyzy", list1);
                    }

                    for (Map map1 : list2) {
                        //移除其他键防止数据被重置
                        map1.keySet().removeIf(key -> !key.equals("associationFormField_lxwns03h_id") && !key.equals("selectField_lz0mdudz"));

                        //最终客户关联表单是否有值
                        if (Objects.nonNull(map1.get("associationFormField_lxwns03h_id")) && !map1.get("associationFormField_lxwns03h_id").toString().equals("\"[]\"")) {
                            String jsonString3 = map1.get("associationFormField_lxwns03hb_id").toString();
                            String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                            List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                            customerMapList.addAll(materialMap);

                            continue;
                        }

                        String customerName = UtilMap.getString(map1, "selectField_lz0mdudz");

                        if (Strings.isNotBlank(customerName)) {
                            //查询客户
                            DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                                    .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName, "eq"))))
                                    .build(), YDConf.FORM_QUERY.retrieve_list);

                            List<Map> data2 = (List<Map>) ddrNew.getData();

                            if (!data2.isEmpty()) {
                                String formInstanceId = data2.get(0).get("formInstanceId").toString();

                                //客户关联表单
                                Map customerMap = new HashMap();
                                customerMap.put("formType", "receipt");
                                customerMap.put("formUuid", "FORM-4020139BCB3341349EE81F5332085D35C294");
                                customerMap.put("instanceId", formInstanceId);
                                customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                                customerMap.put("title", customerName);

                                List<Map> list = new ArrayList<>();
                                list.add(customerMap);

                                map1.put("associationFormField_lxwns03h",list);

                                customerMapList.add(customerMap);

                                flag2 = true;
                            }
                        }
                    }
                    if (flag2){
                        updateFormData.put("tableField_lz0mdudy", list2);
                    }

                    for (Map map1 : list3) {
                        //移除其他键防止数据被重置
                        map1.keySet().removeIf(key -> !key.equals("associationFormField_m9v6h9fj_id") && !key.equals("selectField_lyz73etd"));

                        //最终客户关联表单是否有值
                        if (Objects.nonNull(map1.get("associationFormField_m9v6h9fj_id")) && !map1.get("associationFormField_m9v6h9fj_id").toString().equals("\"[]\"")) {
                            String jsonString3 = map1.get("associationFormField_m9v6h9fj_id").toString();
                            String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                            List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                            customerMapList.addAll(materialMap);

                            continue;
                        }

                        String customerName = UtilMap.getString(map1, "selectField_lyz73etd");

                        if (Strings.isNotBlank(customerName)) {
                            //查询客户
                            DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                                    .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName, "eq"))))
                                    .build(), YDConf.FORM_QUERY.retrieve_list);

                            List<Map> data2 = (List<Map>) ddrNew.getData();

                            if (!data2.isEmpty()) {
                                String formInstanceId = data2.get(0).get("formInstanceId").toString();

                                //客户关联表单
                                Map customerMap = new HashMap();
                                customerMap.put("formType", "receipt");
                                customerMap.put("formUuid", "FORM-4020139BCB3341349EE81F5332085D35C294");
                                customerMap.put("instanceId", formInstanceId);
                                customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                                customerMap.put("title", customerName);

                                List<Map> list = new ArrayList<>();
                                list.add(customerMap);

                                map1.put("associationFormField_m9v6h9fj",list);

                                customerMapList.add(customerMap);

                                flag3 = true;
                            }
                        }
                    }
                    if (flag3){
                        updateFormData.put("tableField_ltnynz04", list3);
                    }


                    //根据instanceId去重
                    List<Map> distinctList = customerMapList.stream()
                            .collect(Collectors.toMap(
                                    m -> m.get("instanceId"), // Key is instanceId
                                    m -> m,                   // Value is the map itself
                                    (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                            ))
                            .values()
                            .stream()
                            .collect(Collectors.toList());


                    if (!distinctList.isEmpty()){
                        updateFormData.put("associationFormField_m9rwbzc7",distinctList);//所有客户平铺
                    }
                }

                if (!updateFormData.keySet().isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                            .useLatestVersion(true)
                            .build(), YDConf.FORM_OPERATION.update);

                    log.info("第{}条更新完成,实例id：{}",i,formInstId);
                }else {
                    log.info("第{}条无需更新,实例id：{}",i,formInstId);
                }

                i++;
            }



            pageNumber++;
        }while (ddrNew2.getTotalCount() > ddrNew2.getPageNumber() * pageSize);

        /*long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;

        log.info("查询所有数据耗时:{}秒", time);*/


        return McR.success();
    }

    //更新研发日报客户关联表单
    @Override
    public McR updateYiyao8() {
        DDR_New ddrNew2 = new DDR_New();
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew2 = ydClient.queryData(YDParam.builder().formUuid("FORM-82C4B599CFB1404392BB92E3AB1867D9E0U1")
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), YDConf.FORM_QUERY.retrieve_list_all);

            List<Map> dataList = (List<Map>) ddrNew2.getData();

            int i = (pageNumber - 1) * pageSize + 1;

            for (Map data : dataList) {
                Map formData = (Map) data.get("formData");
                String formInstId = data.get("formInstanceId").toString();

                Map updateFormData = new HashMap();
                if (Objects.isNull(formData.get("associationFormField_m9rwbzc7_id")) || formData.get("associationFormField_m9rwbzc7_id").toString().equals("\"[]\"")) {
                    //支持内容
                    List<Map> list1 = UtilMap.getList(formData, "tableField_lto5smcp");

                    boolean flag1 = false;

                    //所有客户平铺
                    List<Map> customerMapList = new ArrayList<>();

                    for (Map map1 : list1) {
                        //移除其他键防止数据被重置
                        map1.keySet().removeIf(key -> !key.equals("associationFormField_maes524b_id") && !key.equals("textField_lwkd6mex"));

                        //最终客户关联表单是否有值
                        if (Objects.nonNull(map1.get("associationFormField_maes524b_id")) && !map1.get("associationFormField_maes524b_id").toString().equals("\"[]\"")) {
                            String jsonString3 = map1.get("associationFormField_maes524b_id").toString();
                            String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                            List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                            customerMapList.addAll(materialMap);

                            continue;
                        }

                        String customerName = UtilMap.getString(map1, "textField_lwkd6mex");
                        if (Strings.isNotBlank(customerName)) {
                            //查询客户
                            DDR_New ddrNew = ydClient.queryData(YDParam.builder()
                                    .formUuid("FORM-4020139BCB3341349EE81F5332085D35C294")
                                    .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lr60luaz", customerName, "eq"))))
                                    .build(), YDConf.FORM_QUERY.retrieve_list);

                            List<Map> data2 = (List<Map>) ddrNew.getData();

                            if (!data2.isEmpty()) {
                                String formInstanceId = data2.get(0).get("formInstanceId").toString();

                                //客户关联表单
                                Map customerMap = new HashMap();
                                customerMap.put("formType", "receipt");
                                customerMap.put("formUuid", "FORM-4020139BCB3341349EE81F5332085D35C294");
                                customerMap.put("instanceId", formInstanceId);
                                customerMap.put("appType", "APP_HJJ3X3QN4WEWDHU2BJR2");
                                customerMap.put("title", customerName);

                                List<Map> list = new ArrayList<>();
                                list.add(customerMap);

                                map1.put("associationFormField_maes524b",list);


                                customerMapList.add(customerMap);

                                flag1 = true;
                            }
                        }
                    }
                    if (flag1){
                        updateFormData.put("tableField_lto5smcp", list1);
                    }

                    //根据instanceId去重
                    List<Map> distinctList = customerMapList.stream()
                            .collect(Collectors.toMap(
                                    m -> m.get("instanceId"), // Key is instanceId
                                    m -> m,                   // Value is the map itself
                                    (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                            ))
                            .values()
                            .stream()
                            .collect(Collectors.toList());


                    if (!distinctList.isEmpty()){
                        updateFormData.put("associationFormField_m9rwbzc7",distinctList);//所有客户平铺
                    }
                }

                if (!updateFormData.keySet().isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                            .useLatestVersion(true)
                            .build(), YDConf.FORM_OPERATION.update);

                    log.info("第{}条更新完成,实例id：{}",i,formInstId);
                }else {
                    log.info("第{}条无需更新,实例id：{}",i,formInstId);
                }

                i++;
            }

            pageNumber++;
        }while (ddrNew2.getTotalCount() > ddrNew2.getPageNumber() * pageSize);


        return McR.success();
    }

    //更新项目验收售后流程客户关联表单
    @Override
    public McR updateYiyao9() {
        DDR_New ddrNew2 = new DDR_New();
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew2 = ydClient.queryData(YDParam.builder().formUuid("FORM-4B4AE7C111604CDE85729D3FD8797807RG7J")
//                            .searchCondition(JSONObject.toJSONString(UtilMap.map("serialNumberField_lsy8dpqi","0760")))
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), YDConf.FORM_QUERY.retrieve_list_all);

            List<Map> dataList = (List<Map>) ddrNew2.getData();

            int i = (pageNumber - 1) * pageSize + 1;

            for (Map data : dataList) {
                Map formData = (Map) data.get("formData");
                String formInstId = data.get("formInstanceId").toString();

                Map updateFormData = new HashMap();
                if (Objects.isNull(formData.get("associationFormField_m9rwbzc7_id")) || formData.get("associationFormField_m9rwbzc7_id").toString().equals("\"[]\"")) {
                    //项目信息
                    List<Map> list1 = UtilMap.getList(formData, "tableField_m3wpi8s6");

                    boolean flag1 = false;

                    //所有客户平铺
                    List<Map> customerMapList = new ArrayList<>();

                    for (Map map1 : list1) {
                        //移除其他键防止数据被重置
                        map1.keySet().removeIf(key -> !key.equals("associationFormField_maes524b_id") && !key.equals("associationFormField_m3wpi8sg_id"));

                        //最终客户关联表单是否有值
                        if (Objects.nonNull(map1.get("associationFormField_maes524b_id")) && !map1.get("associationFormField_maes524b_id").toString().equals("\"[]\"")) {
                            String jsonString3 = map1.get("associationFormField_maes524b_id").toString();
                            String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                            List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                            customerMapList.addAll(materialMap);

                            continue;
                        }

                        //项目关联表单是否有值
                        if (Objects.nonNull(map1.get("associationFormField_m3wpi8sg_id")) && !map1.get("associationFormField_m3wpi8sg_id").toString().equals("\"[]\"")) {
                            String jsonString3 = map1.get("associationFormField_m3wpi8sg_id").toString();
                            String materialJsonString = StringEscapeUtils.unescapeJava(jsonString3.substring(1, jsonString3.length() - 1));
                            List<Map> materialMap =((List<Map>) JSONArray.parse(materialJsonString));

                            Map map = materialMap.get(0);


                            //查询项目
                            Map formData1 = ydClient.queryData(YDParam.builder()
                                    .formInstId(map.get("instanceId").toString())
                                    .build(), YDConf.FORM_QUERY.retrieve_id).getFormData();

                            if (Objects.nonNull(formData1.get("associationFormField_lw4kkjrb_id")) && !formData1.get("associationFormField_lw4kkjrb_id").toString().equals("\"[]\"")) {
                                String jsonString4 = formData1.get("associationFormField_lw4kkjrb_id").toString();
                                String materialJsonString4 = StringEscapeUtils.unescapeJava(jsonString4.substring(1, jsonString4.length() - 1));
                                List<Map> materialMap4 =((List<Map>) JSONArray.parse(materialJsonString4));

                                customerMapList.addAll(materialMap4);

                                map1.put("associationFormField_maes524b",materialMap4);

                                flag1 = true;
                            }
                        }
                    }
                    if (flag1){
                        updateFormData.put("tableField_m3wpi8s6", list1);
                    }

                    //根据instanceId去重
                    List<Map> distinctList = customerMapList.stream()
                            .collect(Collectors.toMap(
                                    m -> m.get("instanceId"), // Key is instanceId
                                    m -> m,                   // Value is the map itself
                                    (existing, replacement) -> existing // In case of duplicate keys, keep the existing one
                            ))
                            .values()
                            .stream()
                            .collect(Collectors.toList());


                    if (!distinctList.isEmpty()){
                        updateFormData.put("associationFormField_m9rwbzc7",distinctList);//所有客户平铺
                    }
                }

                if (!updateFormData.keySet().isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                            .useLatestVersion(true)
                            .build(), YDConf.FORM_OPERATION.update);

                    log.info("第{}条更新完成,实例id：{}",i,formInstId);
                }else {
                    log.info("第{}条无需更新,实例id：{}",i,formInstId);
                }

                i++;
            }

            pageNumber++;
        }while (ddrNew2.getTotalCount() > ddrNew2.getPageNumber() * pageSize);


        return McR.success();
    }

    //更新交付项目日报最终用户文本
    @Override
    public McR updateYiyao10() {
        List<Map> a = new ArrayList<>();
        Map map = new HashMap();
        map.put("key","createTime");
        map.put("value","1751299200000");
        map.put("type","DOUBLE");
        map.put("operator","gt");
        map.put("componentName","DateField");
        a.add(map);

//        long beginTime = System.currentTimeMillis();

        //查询所有日报档案
//        List<Map> dataList = getYdDataList("FORM-F772E0DBE98340F690C2412B0A168EB4AG9H", JSONObject.toJSONString(a), YDConf.FORM_QUERY.retrieve_list_all);
//        List<Map> dataList = getYdDataList("FORM-F772E0DBE98340F690C2412B0A168EB4AG9H", "", YDConf.FORM_QUERY.retrieve_list_all);

        DDR_New ddrNew2 = new DDR_New();
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew2 = ydClient.queryData(YDParam.builder().formUuid("FORM-F772E0DBE98340F690C2412B0A168EB4AG9H")
                    .pageNumber(pageNumber)
                    .pageSize(pageSize)
                    .searchCondition(JSONObject.toJSONString(a))
                    .build(), YDConf.FORM_QUERY.retrieve_list_all);

            List<Map> dataList = (List<Map>) ddrNew2.getData();

            int i = (pageNumber - 1) * pageSize + 1;

            for (Map data : dataList) {
                Map formData = (Map) data.get("formData");
                String formInstId = data.get("formInstanceId").toString();

                Map updateFormData = new HashMap();

                //质保期、过保期等已交付无维保合同客户
                List<Map> list2 = UtilMap.getList(formData, "tableField_lz0mdudy");
                //维保内容
                List<Map> list3 = UtilMap.getList(formData, "tableField_ltnynz04");

                boolean flag1 = false;
                boolean flag2 = false;

                for (Map map1 : list2) {
                    //移除其他键防止数据被重置
                    map1.keySet().removeIf(key -> !key.equals("associationFormField_lxwns03h_id"));

                    if (Objects.nonNull(map1.get("associationFormField_lxwns03h_id"))){
                        String jsonString = map1.get("associationFormField_lxwns03h_id").toString();
                        String jsonString2 = StringEscapeUtils.unescapeJava(jsonString.substring(1, jsonString.length() - 1));
                        List<Map> customer =(List<Map>) JSONArray.parse(jsonString2);

                        if (!customer.isEmpty()){
                            map1.put("selectField_lz0mdudz",customer.get(0).get("title").toString());
                            flag1 = true;
                        }
                    }
                }
                if (flag1){
                    updateFormData.put("tableField_lz0mdudy",list2);
                }


                for (Map map1 : list3) {
                    //移除其他键防止数据被重置
                    map1.keySet().removeIf(key -> !key.equals("associationFormField_m9v6h9fj_id"));

                    if (Objects.nonNull(map1.get("associationFormField_m9v6h9fj_id"))){
                        String jsonString = map1.get("associationFormField_m9v6h9fj_id").toString();
                        String jsonString2 = StringEscapeUtils.unescapeJava(jsonString.substring(1, jsonString.length() - 1));
                        List<Map> customer =(List<Map>) JSONArray.parse(jsonString2);

                        if (!customer.isEmpty()){
                            map1.put("selectField_lyz73etd",customer.get(0).get("title").toString());
                            flag2 = true;
                        }
                    }

                }
                if (flag2){
                    updateFormData.put("tableField_ltnynz04",list3);
                }


                if (!updateFormData.keySet().isEmpty()){
                    ydClient.operateData(YDParam.builder()
                            .formInstId(formInstId)
                            .updateFormDataJson(JSONObject.toJSONString(updateFormData))
                            .useLatestVersion(true)
                            .build(), YDConf.FORM_OPERATION.update);

                    log.info("第{}条更新完成,实例id：{}",i,formInstId);
                }else {
                    log.info("第{}条无需更新,实例id：{}",i,formInstId);
                }

                i++;
            }



            pageNumber++;
        }while (ddrNew2.getTotalCount() > ddrNew2.getPageNumber() * pageSize);

        /*long endTime = System.currentTimeMillis();
        double time = (endTime - beginTime) / 1000.0;

        log.info("查询所有数据耗时:{}秒", time);*/


        return McR.success();
    }

    @Override
    public void getCheckInData(JSONObject eventJson) {
        int retryCount = 0;
        int maxRetries = 5;

        long timeStamp = roundToNearestThousand(Long.parseLong(eventJson.getString("timeStamp")));//签到时间戳
        String staffId = eventJson.getString("StaffId");//签到人userId
        String eventId = eventJson.getString("eventId");//签到事件id

        while (retryCount <= maxRetries) {
            try {
                //获取签到数据
                Map body = new HashMap();
                body.put("cursor",0);
                body.put("size",100);
                body.put("start_time",timeStamp);
                body.put("end_time",timeStamp);
                body.put("userid_list",staffId);

                //查询用户详情
                DDR_New ddrNew1 = (DDR_New) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/v2/user/get", null, ddClient.initTokenParams(), UtilMap.map("userid", staffId), DDR_New.class);
                Map result1 = (Map) ddrNew1.getResult();
                String userName = UtilMap.getString(result1, "name");

                //查询用户考勤数据
                DDR_New ddrNew = (DDR_New) UtilHttp.doPost("https://oapi.dingtalk.com/topapi/checkin/record/get", null, ddClient.initTokenParams(), body, DDR_New.class);
                Map result = (Map) ddrNew.getResult();
                List list = UtilMap.getList(result, "page_list");

                if (!list.isEmpty()){
                    Map formData = new HashMap();
                    Map checkInData = (Map) list.get(0);
                    Long checkinTime = UtilMap.getLong(checkInData, "checkin_time");
                    String detailPlace = UtilMap.getString(checkInData, "detail_place");
                    String remark = UtilMap.getString(checkInData,"remark");
                    formData.put("employeeField_mbypt8ro",Arrays.asList(staffId));//签到人
                    formData.put("textField_mbyq1cji",userName);//签到人-文本
                    formData.put("dateField_mbrb3qfy",checkinTime);//签到时间
                    formData.put("textField_mbrb3qfx",detailPlace);//签到地点
                    formData.put("textareaField_mbypt8rp",remark);//备注
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    String formattedDate = sdf.format(timeStamp);
                    formData.put("textField_mbrbdyl4","签到人：" +userName + "，签到时间：" + formattedDate + "，签到地点：" + detailPlace);//标题

                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-D4389CDAD1704F959E9D38CB64927AD8PKCH")
                            .formDataJson(JSONObject.toJSONString(formData))
                            .build(),YDConf.FORM_OPERATION.create);
                }

                break;
            } catch (IORuntimeException e) {
                if (retryCount < maxRetries){
                    retryCount++;
                    log.info("eventId：{}，第{}次重试，异常信息：{}",eventId, retryCount, e.getMessage());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();// 如果线程在等待期间被中断，恢复中断状态
                        throw new RuntimeException("Request interrupted", ie);// 抛出运行时异常，终止重试
                    }
                    continue;
                }
                throw new RuntimeException("eventId：" + eventId + "，超出最大重试次数，异常信息：" + e.getMessage());
            }catch (Exception e) {
                log.error("eventId：{}，请求失败：", eventId, e);
            }
        }
    }


    private List<Map> getYdDataList(String formUuid, String searchCondition, YDConf.FORM_QUERY formQuery) {
        List<Map> list = new ArrayList<>();
        DDR_New ddrNew = new DDR_New();
        int pageNumber = 1;
        int pageSize = 100;
        do {
            ddrNew = ydClient.queryData(YDParam.builder().formUuid(formUuid)
                    .searchCondition(searchCondition)
                    .pageNumber(pageNumber)
                    .pageSize(pageSize).build(), formQuery);

            list.addAll((List<Map>) ddrNew.getData());
            pageNumber++;
        }while (ddrNew.getTotalCount() > ddrNew.getPageNumber() * pageSize);
        return list;
    }

    public long roundToNearestThousand(long timestamp) {
        // 将时间戳除以1000，得到秒级部分（带毫秒的小数部分）
        double seconds = timestamp / 1000.0;

        // 对秒级部分的个位数进行四舍五入（即对毫秒的千位四舍五入）
        long roundedSeconds = Math.round(seconds);

        // 将四舍五入后的秒级部分转换回毫秒时间戳
        return roundedSeconds * 1000;
    }
}
