package com.malk.huagao.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.huagao.entity.*;
import com.malk.huagao.mapper.*;
import com.malk.huagao.service.YdHuaGaoService;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.service.aliwork.YDService;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class YdHuaGaoServiceImpl implements YdHuaGaoService {
    @Autowired
    private KdYdCustomerMapper kdYdCustomerMapper;
    @Autowired
    private YDClient ydClient;
    @Autowired
    private DDClient ddClient;
    @Autowired
    private YDService ydService;
    @Autowired
    private KdYdCustomerReferrerMapper kdYdCustomerReferrerMapper;
    @Autowired
    private KdYdOrderMapper kdYdOrderMapper;
    @Autowired
    private KdYdDeliveryMapper kdYdDeliveryMapper;
    @Autowired
    private KdYdOutboundMapper kdYdOutboundMapper;
    @Autowired
    private KdYdReceivableMapper kdYdReceivableMapper;
    @Autowired
    private KdYdOutboundDetailMapper kdYdOutboundDetailMapper;
    @Autowired
    private KdYdReceivableDetailMapper kdYdReceivableDetailMapper;
    @Autowired
    private KdYdDeliveryDetailMapper kdYdDeliveryDetailMapper;
    @Autowired
    private KdYdPaymentReceiptDetailMapper kdYdPaymentReceiptDetailMapper;
    @Autowired
    private KdYdPaymentReceiptMapper kdYdPaymentReceiptMapper;
    @Autowired
    private KdYdReceivalablePaymentMapper kdYdReceivalablePaymentMapper;
    @Autowired
    private KdYdZpMapper kdYdZpMapper;
    @Autowired
    private KdYdMaterialMapper kdYdMaterialMapper;
    @Autowired
    private KdYdTransferMapper kdYdTransferMapper;
    @Autowired
    private KdYdTransferDetailMapper kdYdTransferDetailMapper;
    @Autowired
    private YDConf ydConf;
    @Autowired
    private DDConf ddConf;

    @Override
    public void syncKdYdCustomer() {

    }

    @Override
    public void syncKdYDcustomerLiaison() {
        log.info("定时同步-客户推荐人");
        try {

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            List<KdYdCustomerReferrer> KdYdCustomerReferrers = kdYdCustomerReferrerMapper.selectRecentUpdated(fiveMinutesAgo);
            if (KdYdCustomerReferrers.isEmpty()) {
                log.info("【客户推荐人同步任务】无需要同步的数据，结束");
                return;
            }

            for (KdYdCustomerReferrer kdYdCustomerReferrer : KdYdCustomerReferrers) {
                try {
                    String bm = kdYdCustomerReferrer.getBm();
                    String tjruuid = kdYdCustomerReferrer.getTjruuid();
                    String formInstId = kdYdCustomerReferrer.getFormInstId();
                    if (ObjectUtil.hasEmpty(formInstId, bm)) {
                        log.warn("跳过同步: formInstId 或 khbm 为空, customer={}", kdYdCustomerReferrer.getId());
                        continue;
                    }
//                    if (tjruuid == null) {
//            List<Map> khdata = (List<Map>) ydClient.queryData(
//                    YDParam.builder()
//                            .formUuid("FORM-68154CC0A7054BF0B1C933752CD3881FB0SR")
//                            .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_mgqbiov3", tjruuid)))
//                            .build(),
//                    YDConf.FORM_QUERY.retrieve_list_all
//            ).getData();
//            if (khdata.size() > 0) {
//                 khbm = UtilMap.getString(khdata.get(0), "textField_meqhqqvg");
//            }
////        }
//                    LambdaQueryWrapper<KdYdCustomer> YdCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    YdCustomerLambdaQueryWrapper.eq(KdYdCustomer::getTjruuid, tjruuid);
//                    KdYdCustomer kdYdCustomer1 = kdYdCustomerMapper.selectOne(YdCustomerLambdaQueryWrapper);
//                    String formInstId1 = kdYdCustomer1.getFormInstId();
//                    ydClient.operateData(
//                            YDParam.builder()
//                                    .formInstanceId(formInstId1)
//                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mfdrrg87", bm)))
//                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);
                    ydClient.operateData(
                            YDParam.builder()
                                    .formInstanceId(formInstId)
                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mgqbiouy", bm)))
                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);

                } catch (Exception e) {
                    log.error("同步单条客户推荐人数据异常: formInstId={}", kdYdCustomerReferrer.getFormInstId(), e);
                }
            }

            log.info("【客户推荐人同步任务】执行完成，共处理 {} 条记录", KdYdCustomerReferrers.size());
        } catch (Exception e) {
            log.error("【客户推荐人同步任务】执行过程中发生严重错误", e);
        }
    }

    @Override
    public void syncKdYdOrder() {
        log.info("定时同步-订单");
        try {

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            List<KdYdOrder> KdYdOrders = kdYdOrderMapper.selectRecentUpdated(fiveMinutesAgo);
            if (KdYdOrders.isEmpty()) {
                log.info("【订单同步任务】无需要同步的数据，结束");
                return;
            }

            for (KdYdOrder kdYdOrder : KdYdOrders) {
                try {
                    String bm = kdYdOrder.getDjbh();
//                    String tjruuid = kdYdOrder.getTjruuid();
//                    String formInstId = kdYdOrder.getForminstid();
//                    if (ObjectUtil.hasEmpty(formInstId, bm)) {
//                        log.warn("跳过同步: formInstId 或 khbm 为空, customer={}", kdYdOrder.getId());
//                        continue;
//                    }
//                    if (tjruuid == null) {
//            List<Map> khdata = (List<Map>) ydClient.queryData(
//                    YDParam.builder()
//                            .formUuid("FORM-68154CC0A7054BF0B1C933752CD3881FB0SR")
//                            .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_mgqbiov3", tjruuid)))
//                            .build(),
//                    YDConf.FORM_QUERY.retrieve_list_all
//            ).getData();
//            if (khdata.size() > 0) {
//                 khbm = UtilMap.getString(khdata.get(0), "textField_meqhqqvg");
//            }
////        }
//                    LambdaQueryWrapper<KdYdCustomer> YdCustomerLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                    YdCustomerLambdaQueryWrapper.eq(KdYdCustomer::getTjruuid, tjruuid);
//                    KdYdCustomer kdYdCustomer1 = kdYdCustomerMapper.selectOne(YdCustomerLambdaQueryWrapper);
//                    String formInstId1 = kdYdCustomer1.getFormInstId();
//                    ydClient.operateData(
//                            YDParam.builder()
//                                    .formInstanceId(formInstId1)
//                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mfdrrg87", bm)))
//                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);
                    ydClient.operateData(
                            YDParam.builder()
//                                    .formInstanceId(formInstId)
                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mg327tqe", bm)))
                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);

                } catch (Exception e) {
//                    log.error("同步单条订单数据异常: formInstId={}", kdYdOrder.getForminstid(), e);
                }
            }

            log.info("【订单同步任务】执行完成，共处理 {} 条记录", KdYdOrders.size());
        } catch (Exception e) {
            log.error("【订单同步任务】执行过程中发生严重错误", e);
        }
    }

    @Override
    public void syncKdYdDelivery() {
        log.info("定时同步-发货单");
        try {

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            List<KdYdDelivery> KdYdDeliverys = kdYdDeliveryMapper.selectRecentUpdated(fiveMinutesAgo);
            if (KdYdDeliverys.isEmpty()) {
                log.info("【发货单同步任务】无需要同步的数据，结束");
                return;
            }

            for (KdYdDelivery kdYdDelivery : KdYdDeliverys) {
                try {
                    String djbh = kdYdDelivery.getDjbh();
//                    String tjruuid = kdYdOrder.getTjruuid();
//                    String formInstId = kdYdDelivery.getForminstid();
//                    if (ObjectUtil.hasEmpty(formInstId, djbh)) {
//                        log.warn("跳过同步: formInstId 或 khbm 为空, customer={}", kdYdDelivery.getId());
//                        continue;
//                    }

                    ydClient.operateData(
                            YDParam.builder()
//                                    .formInstanceId(formInstId)
                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mg3fuqvh", djbh)))
                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);

                } catch (Exception e) {
//                    log.error("同步单条发货单数据异常: formInstId={}", kdYdDelivery.getForminstid(), e);
                }
            }

            log.info("【发货单同步任务】执行完成，共处理 {} 条记录", KdYdDeliverys.size());
        } catch (Exception e) {
            log.error("【发货单同步任务】执行过程中发生严重错误", e);
        }
    }


    @Override
    public void synckdYdOutbound() {

        log.info("定时同步-出库单");
        // 查询需要删除的数据
        LambdaQueryWrapper<KdYdOutbound> outbounddel = new LambdaQueryWrapper<>();
        outbounddel.eq(KdYdOutbound::getOperationType, 3)
                .eq(KdYdOutbound::getSyncStatus, "0");
        List<KdYdOutbound> kdYdOutbounddels = kdYdOutboundMapper.selectList(outbounddel);

        // 批量删除处理
        if (!kdYdOutbounddels.isEmpty()) {
            log.info("开始处理出库单删除操作，共{}条数据", kdYdOutbounddels.size());
            ArrayList<String> deleteList = new ArrayList<>();
            int deleteSuccessCount = 0;

            for (KdYdOutbound kdYdOutbound : kdYdOutbounddels) {
                try {
                    String djbh = kdYdOutbound.getDjbh();

                    List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-AADBCDA8126F41A0ADDEE3353828583192M8")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg34txgm", djbh)))
                            .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                    if (list1 != null && !list1.isEmpty()) {
                        for (Map map : list1) {
                            String formInstanceId = UtilMap.getString(map, "formInstanceId");
                            if (formInstanceId != null) {
                                deleteList.add(formInstanceId);
                            }
                        }
                        deleteSuccessCount++;

                        // 同时删除对应的子表数据
                        Long outboundId = kdYdOutbound.getId();
                        LambdaQueryWrapper<KdYdOutboundDetail> detailDelqw = new LambdaQueryWrapper<>();
                        detailDelqw.eq(KdYdOutboundDetail::getOutboundId, outboundId);
                        List<KdYdOutboundDetail> detailDels = kdYdOutboundDetailMapper.selectList(detailDelqw);

                        if (!detailDels.isEmpty()) {
                            for (KdYdOutboundDetail detail : detailDels) {
                                detail.setSyncStatus("1");
                                kdYdOutboundDetailMapper.updateById(detail);
                            }
                        }
                    } else {
                        log.warn("未找到对应的出库单数据: djbh={}", djbh);
                    }

                    // 删除操作完成后更新状态
                    kdYdOutbound.setSyncStatus("1");
                    kdYdOutboundMapper.updateById(kdYdOutbound);

                } catch (Exception e) {
                    log.error("删除出库单数据查询异常: djbh={}", kdYdOutbound.getDjbh(), e);
                }
            }

            // 执行批量删除
            if (!deleteList.isEmpty()) {
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-AADBCDA8126F41A0ADDEE3353828583192M8")
                            .formInstanceIdList(deleteList)
                            .build(), YDConf.FORM_OPERATION.delete_batch);
                    log.info("出库单批量删除完成，共删除{}条数据", deleteList.size());
                } catch (Exception e) {
                    log.error("出库单批量删除操作异常", e);
                }
            }

            return;
        } else {
            log.info("【出库单删除任务】无需要删除的数据");
        }
        LambdaQueryWrapper<KdYdOutbound> outboundqw = new LambdaQueryWrapper<>();
        outboundqw.eq(KdYdOutbound::getSyncStatus, "0");
        List<KdYdOutbound> kdYdOutbounds = kdYdOutboundMapper.selectList(outboundqw);
        if (kdYdOutbounds.isEmpty()) {
            log.info("【出库单同步任务】无需要同步的数据，结束");
            return;
        }
        log.info("【出库单同步任务】开始同步，共{}条数据", kdYdOutbounds.size());

        int successCount = 0;
        int failCount = 0;

        for (KdYdOutbound kdYdOutbound : kdYdOutbounds) {
            try {
                Long outboundId = kdYdOutbound.getId();
                String djbh = kdYdOutbound.getDjbh();
                String deliveryId = kdYdOutbound.getDeliveryBm();

                log.debug("开始同步出库单: ID={}, 单据编号={}", outboundId, djbh);

                LambdaQueryWrapper<KdYdOutboundDetail> outbounddetailqw = new LambdaQueryWrapper<>();
                outbounddetailqw.eq(KdYdOutboundDetail::getOutboundId, outboundId)
                        .orderByAsc(KdYdOutboundDetail::getDetailId);
                List<KdYdOutboundDetail> kdYdOutboundDetails = kdYdOutboundDetailMapper.selectList(outbounddetailqw);

                ArrayList<Object> tableList = new ArrayList<>();
                List<Map<String, Object>> tableListxlh = new ArrayList<>(); // 在循环外初始化
                for (KdYdOutboundDetail kdYdOutboundDetail : kdYdOutboundDetails) {
                    HashMap<String, String> tablemap = new HashMap<>();
                    HashMap<String, String> tablemapxlh = new HashMap<>();
                    tablemap.put("textField_mejnamff", kdYdOutboundDetail.getWlbm());
                    tablemap.put("textField_mejnamfg", kdYdOutboundDetail.getWlmc());
                    tablemap.put("textField_mg34txh1", kdYdOutboundDetail.getTpsb());
                    tablemap.put("textField_mejnamfh", kdYdOutboundDetail.getGgxh());
                    tablemap.put("textField_mejnamfk", kdYdOutboundDetail.getKcdw());
                    tablemap.put("numberField_mejnamfl", String.valueOf(kdYdOutboundDetail.getYfsl() != null ? kdYdOutboundDetail.getYfsl().setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP)));
                    tablemap.put("numberField_mg34txh2", kdYdOutboundDetail.getSfsl() != null ? kdYdOutboundDetail.getSfsl().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mg34txh3", kdYdOutboundDetail.getDj() != null ? kdYdOutboundDetail.getDj().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mg34txh4", kdYdOutboundDetail.getHsdj() != null ? kdYdOutboundDetail.getHsdj().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("textField_mg34txh5", kdYdOutboundDetail.getPh());
                    tablemap.put("numberField_mg34txh6", kdYdOutboundDetail.getSl() != null ? kdYdOutboundDetail.getSl().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mg34txh7", kdYdOutboundDetail.getSe() != null ? kdYdOutboundDetail.getSe().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mg34txh8", kdYdOutboundDetail.getJe() != null ? kdYdOutboundDetail.getJe().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mg34txh9", kdYdOutboundDetail.getJshj() != null ? kdYdOutboundDetail.getJshj().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("textField_mf6a0h6l", kdYdOutboundDetail.getCk());
                    tablemap.put("textField_mf6a0h6k", kdYdOutboundDetail.getCw());
                    tablemap.put("textField_mf6a0h6p", kdYdOutboundDetail.getKczt());
                    tablemap.put("numberField_mg34txha", kdYdOutboundDetail.getJtc() != null ? kdYdOutboundDetail.getJtc().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("textField_mejnamf6", kdYdOutboundDetail.getSjr());
                    tablemap.put("textField_mejnamf7", kdYdOutboundDetail.getSjdh());
                    tablemap.put("textareaField_mf6a0h5e", kdYdOutboundDetail.getSjdz());
                    tablemap.put("textField_mejnamfx", kdYdOutboundDetail.getSsxl());
                    tablemap.put("textField_mf6a0h6u", kdYdOutboundDetail.getGg());
                    tablemap.put("textField_mhlqeoas", kdYdOutboundDetail.getZbq());
                    tablemap.put("dateField_mg34txhb", kdYdOutboundDetail.getFwdqr() != null ? String.valueOf(kdYdOutboundDetail.getFwdqr().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()) : "");
                    tablemap.put("textField_mf6a0h6w", kdYdOutboundDetail.getXlh());
                    tablemap.put("textField_mhlqeoat", kdYdOutboundDetail.getZbqsf());
                    tablemap.put("textField_mf6a0h6x", kdYdOutboundDetail.getKddh());
                    tablemap.put("textField_mf6a0h6y", kdYdOutboundDetail.getJx());
                    String xlhjh = kdYdOutboundDetail.getXlh();
                    if (xlhjh != null && !xlhjh.trim().isEmpty()) {
                        List<Map<String, Object>> currentXlhList = Arrays.stream(xlhjh.split(","))
                                .map(String::trim)
                                .filter(item -> !item.isEmpty())
                                .map(item -> {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("textField_mf6a0h6w", item); // 序列号
                                    map.put("textField_mjqst61l", kdYdOutboundDetail.getWlbm()); // 对应的物料编码
                                    map.put("textField_mjqst61m", kdYdOutboundDetail.getGgxh());
                                    return map;
                                })
                                .collect(Collectors.toList());

                        tableListxlh.addAll(currentXlhList); // 追加到总列表
                    }

                    // 主表仍保留原始 xlh（可选）
                    tablemap.put("textField_mf6a0h6w", kdYdOutboundDetail.getXlh());
                    tablemap.put("radioField_mf6a0h6h", kdYdOutboundDetail.getSfzp());

                    tableList.add(tablemap);

                    // 更新同步状态
                    kdYdOutboundDetail.setSyncStatus("1");
                    kdYdOutboundDetailMapper.updateById(kdYdOutboundDetail);
                }

                String fhdformInstanceId = null;
                String fhdbh = null;
                try {
                    log.debug("开始查询出库数据: deliveryId={}", deliveryId);

                    List<Map> ddlist = (List<Map>) ydClient.queryData(
                            YDParam.builder()
                                    .formUuid("FORM-FAE2575E112644ED914CAB4FEC9309F32AVR")
                                    .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                                    .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                                    .searchCondition(JSON.toJSONString(UtilMap.map("serialNumberField_mheazm7w", deliveryId)))
                                    .build(),
                            YDConf.FORM_QUERY.retrieve_list_all
                    ).getData();

                    if (ddlist != null && !ddlist.isEmpty()) {

                        for (Map<String, Object> khitem : ddlist) {
                            Map<String, Object> khformData = (Map<String, Object>) khitem.get("formData");

                            if (khformData != null && deliveryId.equals(khformData.get("serialNumberField_mheazm7w"))) {
                                fhdformInstanceId = (String) khitem.get("formInstanceId");
                                fhdbh = (String) khformData.get("serialNumberField_mheazm7w");
                                break;
                            }
                        }

                        if (fhdformInstanceId == null) {
                            log.warn("未找到与fhdbh={}完全匹配的订单数据", fhdbh);
                        }
                    } else {
                        log.warn("未查询到订单数据: fhdbh={}", fhdbh);
                    }

                } catch (Exception e) {
                    log.error("查询订单数据异常: fhdbh={}, 错误信息={}", fhdbh, e.getMessage(), e);
                }
                HashMap<Object, Object> updateMap = new HashMap<>();
                updateMap.put("tableField_mejnamfd", tableList);
                updateMap.put("tableField_mips137b", tableListxlh);
                if (fhdbh != null && fhdformInstanceId != null) {
                    updateMap.put("associationFormField_mejmml36",
                            Arrays.asList(getfhdAss(fhdformInstanceId,fhdbh)));
                }
                updateMap.put("dateField_krbgloam", kdYdOutbound.getDateTime() != null ? String.valueOf(kdYdOutbound.getDateTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()) : "");
                updateMap.put("textField_krnn5bmr", kdYdOutbound.getXsDept());
                updateMap.put("textField_mhjxw689", kdYdOutbound.getFhDept());
                updateMap.put("textField_mhjxw686", kdYdOutbound.getCgy());
                updateMap.put("selectField_mejowmna", kdYdOutbound.getDjlx());
                updateMap.put("textField_mg34txgm", kdYdOutbound.getDjbh());
                updateMap.put("textField_mhlqeoar", kdYdOutbound.getJsbb());
                updateMap.put("textField_mejnamf2", kdYdOutbound.getKh());
                updateMap.put("selectField_mejowmnc", kdYdOutbound.getXslx());
                updateMap.put("textField_mhjxw688", kdYdOutbound.getXsy());
                updateMap.put("selectField_mg34txgt", kdYdOutbound.getXssx());
                updateMap.put("selectField_megi74y8", kdYdOutbound.getKhsx());
                updateMap.put("textField_mg34txgy", kdYdOutbound.getKhtjr());
                updateMap.put("textField_mg34txgz", kdYdOutbound.getYsdh());
                updateMap.put("textField_migw33w6", deliveryId);

                // 添加同步操作（根据您的实际需求添加）
                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-AADBCDA8126F41A0ADDEE3353828583192M8")
                        .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg34txgm", kdYdOutbound.getDjbh())))
                        .formDataJson(JSONObject.toJSONString(updateMap))
                        .build(), YDConf.FORM_OPERATION.upsert
                );
                // 更新同步状态
                kdYdOutbound.setSyncStatus("1");
                kdYdOutboundMapper.updateById(kdYdOutbound);
                successCount++;

                log.info("出库单同步成功: 单据编号={}", djbh);

            } catch (Exception e) {
                failCount++;
                log.error("同步单条出库单数据异常: 单据编号={}, 错误信息={}",
                        kdYdOutbound.getDjbh(), e.getMessage(), e);
            }
        }

        log.info("【出库单同步任务】完成: 成功={}, 失败={}, 总计={}",
                successCount, failCount, kdYdOutbounds.size());
    }

    @Override
    public void syncKdYdReceivable() {
        log.info("定时同步-应收单");
        // 查询需要删除的数据
        LambdaQueryWrapper<KdYdReceivable> receivabledel = new LambdaQueryWrapper<>();
        receivabledel.eq(KdYdReceivable::getOperationType, 3)
                .eq(KdYdReceivable::getSyncStatus, "0");
        List<KdYdReceivable> kdYdReceivabledels = kdYdReceivableMapper.selectList(receivabledel);

        // 批量删除处理
        if (!kdYdReceivabledels.isEmpty()) {
            log.info("开始处理应收单删除操作，共{}条数据", kdYdReceivabledels.size());
            ArrayList<String> deleteList = new ArrayList<>();
            int deleteSuccessCount = 0;

            for (KdYdReceivable kdYdReceivable : kdYdReceivabledels) {
                try {
                    String djbh = kdYdReceivable.getDjbh();

                    List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg3a0tgs", djbh)))
                            .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                    if (list1 != null && !list1.isEmpty()) {
                        for (Map map : list1) {
                            String formInstanceId = UtilMap.getString(map, "formInstanceId");
                            if (formInstanceId != null) {
                                deleteList.add(formInstanceId);
                            }
                        }
                        deleteSuccessCount++;

                        // 同时删除对应的子表数据
                        Long receivableId = kdYdReceivable.getId();

                        // 删除应收单明细
                        LambdaQueryWrapper<KdYdReceivableDetail> detailDelqw = new LambdaQueryWrapper<>();
                        detailDelqw.eq(KdYdReceivableDetail::getReceivableId, receivableId);
                        List<KdYdReceivableDetail> detailDels = kdYdReceivableDetailMapper.selectList(detailDelqw);
                        if (!detailDels.isEmpty()) {
                            for (KdYdReceivableDetail detail : detailDels) {
                                detail.setSyncStatus("1");
                                kdYdReceivableDetailMapper.updateById(detail);
                            }
                            log.debug("更新了{}条应收单明细删除状态", detailDels.size());
                        }

                        // 删除收款计划
                        LambdaQueryWrapper<KdYdReceivablePayment> paymentDelqw = new LambdaQueryWrapper<>();
                        paymentDelqw.eq(KdYdReceivablePayment::getReceivableId, receivableId);
                        List<KdYdReceivablePayment> paymentDels = kdYdReceivalablePaymentMapper.selectList(paymentDelqw);
                        if (!paymentDels.isEmpty()) {
                            for (KdYdReceivablePayment payment : paymentDels) {
                                payment.setSyncStatus("1");
                                kdYdReceivalablePaymentMapper.updateById(payment);
                            }
                            log.debug("更新了{}条收款计划删除状态", paymentDels.size());
                        }
                    } else {
                        log.warn("未找到对应的应收单数据: djbh={}", djbh);
                    }

                    // 删除操作完成后更新状态
                    kdYdReceivable.setSyncStatus("1");
                    kdYdReceivableMapper.updateById(kdYdReceivable);

                } catch (Exception e) {
                    log.error("删除应收单数据查询异常: djbh={}", kdYdReceivable.getDjbh(), e);
                }
            }

            // 执行批量删除
            if (!deleteList.isEmpty()) {
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .formInstanceIdList(deleteList)
                            .build(), YDConf.FORM_OPERATION.delete_batch);
                    log.info("应收单批量删除完成，共删除{}条数据", deleteList.size());
                } catch (Exception e) {
                    log.error("应收单批量删除操作异常", e);
                }
            }

            log.info("应收单删除操作处理完成: 成功查询={}, 待删除={}", deleteSuccessCount, deleteList.size());
            return;
        } else {
            log.info("【应收单删除任务】无需要删除的数据");
        }
        LambdaQueryWrapper<KdYdReceivable> receivableqw = new LambdaQueryWrapper<>();
        receivableqw.eq(KdYdReceivable::getSyncStatus, "0");
        List<KdYdReceivable> kdYdReceivables = kdYdReceivableMapper.selectList(receivableqw);
        if (kdYdReceivables.isEmpty()) {
            log.info("【应收单同步任务】无需要同步的数据，结束");
            return;
        }

        log.info("【应收单同步任务】开始同步，共{}条数据", kdYdReceivables.size());
        int successCount = 0;
        int failCount = 0;

        for (KdYdReceivable kdYdReceivable : kdYdReceivables) {
            try {
                Long id = kdYdReceivable.getId();
                String djbh = kdYdReceivable.getDjbh();

                log.debug("开始同步应收单: ID={}, 单据编号={}", id, djbh);

                // 同步应收单明细
                LambdaQueryWrapper<KdYdReceivableDetail> receivabledetailqw = new LambdaQueryWrapper<>();
                receivabledetailqw.eq(KdYdReceivableDetail::getReceivableId, id)
                        .orderByAsc(KdYdReceivableDetail::getDetailId);
                List<KdYdReceivableDetail> kdYdReceivabledetails = kdYdReceivableDetailMapper.selectList(receivabledetailqw);
                if (kdYdReceivabledetails.isEmpty()) {
                    log.info("【应收单{}】无需要同步的明细数据", djbh);
                    continue;
                }
                int count = 1;
                ArrayList<Object> tableList = new ArrayList<>();
                for (KdYdReceivableDetail kdYdReceivableDetail : kdYdReceivabledetails) {
                    HashMap<Object, Object> tablemap = new HashMap<>();
                    String wlbm = kdYdReceivableDetail.getWlbm();
                    String wlmc = kdYdReceivableDetail.getWlmc();
                    String ggxh = kdYdReceivableDetail.getGgxh();
                    String jjdw = kdYdReceivableDetail.getJjdw();
                    String ssxl = kdYdReceivableDetail.getSsxl();
                    BigDecimal dj = kdYdReceivableDetail.getDj();
                    BigDecimal hsdj = kdYdReceivableDetail.getHsdj();
                    BigDecimal sl = kdYdReceivableDetail.getSl();
                    BigDecimal je = kdYdReceivableDetail.getJe();
                    BigDecimal zbjshj = kdYdReceivableDetail.getJshj();
                    String kcdw = kdYdReceivableDetail.getKcdw();
                    String ph = kdYdReceivableDetail.getPh();
                    BigDecimal se = kdYdReceivableDetail.getSe();
                    BigDecimal jjsl = kdYdReceivableDetail.getJjsl();
                    BigDecimal zkl = kdYdReceivableDetail.getZkl();
                    BigDecimal bhsje = kdYdReceivableDetail.getBhsje();
                    BigDecimal jjjbsl = kdYdReceivableDetail.getJjjbsl();
                    BigDecimal kcsl = kdYdReceivableDetail.getKcsl();
                    String sfzp = kdYdReceivableDetail.getSfzp();
                    String gg = kdYdReceivableDetail.getGg();
                    BigDecimal tc = kdYdReceivableDetail.getTc();
                    String jx = kdYdReceivableDetail.getJx();
                    BigDecimal zke = kdYdReceivableDetail.getZke();
                    String detailId = kdYdReceivableDetail.getDetailId();

                    // 优化：确保所有金额字段保留两位小数
                    tablemap.put("textField_mgt4w4ip", count);
                    tablemap.put("textField_mf6el3zy", wlbm);
                    tablemap.put("textField_mf6el3zz", wlmc);
                    tablemap.put("textField_mejmtic5", ggxh);
                    tablemap.put("textField_mf6el400", jjdw);
                    tablemap.put("textField_mhllijwo", ssxl);
                    tablemap.put("numberField_mf6el402", dj != null ? dj.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mejmticb", hsdj != null ? hsdj.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mf6el403", sl != null ? sl.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mejmtic7", zbjshj != null ? zbjshj.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("textField_mf6el409", kcdw);
                    tablemap.put("textField_mf6el408", ph);
                    tablemap.put("numberField_mf6el406", se != null ? se.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mejmtic6", jjsl != null ? jjsl.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mf6el404", zkl != null ? zkl.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mejmticc", bhsje != null ? bhsje.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mf6el407", jjjbsl != null ? jjjbsl.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("numberField_mf6el40a", kcsl != null ? kcsl.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("radioField_mejnamfn", sfzp);
                    tablemap.put("numberField_mf6el40c", tc != null ? tc.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    tablemap.put("textField_mf6el40d", jx);
                    tablemap.put("textField_mf6el40b", gg);
                    tablemap.put("numberField_mf6el405", zke != null ? zke.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                    count++;
                    tableList.add(tablemap);

                    kdYdReceivableDetail.setSyncStatus("1");
                    kdYdReceivableDetailMapper.updateById(kdYdReceivableDetail);
                }

                // 同步收款计划
                LambdaQueryWrapper<KdYdReceivablePayment> receivablepayqw = new LambdaQueryWrapper<>();
                receivablepayqw
                        .eq(KdYdReceivablePayment::getReceivableId, id)
                        .orderByAsc(KdYdReceivablePayment::getDetailId);
                List<KdYdReceivablePayment> kdYdReceivablePayments = kdYdReceivalablePaymentMapper.selectList(receivablepayqw);

                ArrayList<Object> tableListPay = new ArrayList<>();
                if (!kdYdReceivablePayments.isEmpty()) {
                    for (KdYdReceivablePayment kdYdReceivablePayment : kdYdReceivablePayments) {
                        HashMap<Object, Object> tablemap1 = new HashMap<>();
                        long timestamp = kdYdReceivablePayment.getEndTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
                        String xsddh = kdYdReceivablePayment.getXsddh();
                        BigDecimal ysje = kdYdReceivablePayment.getYsje();
                        BigDecimal ysbl = kdYdReceivablePayment.getYsbl();
                        BigDecimal ysjebwb = kdYdReceivablePayment.getYsjebwb();
                        BigDecimal stkdglje = kdYdReceivablePayment.getStkdglje();

                        tablemap1.put("textField_mhiui6va", xsddh);
                        tablemap1.put("dateField_mhiui6v9", timestamp);
                        tablemap1.put("numberField_mhiui6v8", ysje != null ? ysje.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                        tablemap1.put("numberField_mhiui6v6", ysbl != null ? ysbl.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                        tablemap1.put("numberField_mhiui6vb", ysjebwb != null ? ysjebwb.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                        tablemap1.put("numberField_mhjy9hzj", stkdglje != null ? stkdglje.setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                        tableListPay.add(tablemap1);
                        kdYdReceivablePayment.setSyncStatus("1");
                        kdYdReceivalablePaymentMapper.updateById(kdYdReceivablePayment);
                    }
                }
                String ckddjbh = kdYdReceivable.getCkddjbh();
                String ckdformInstanceId = null;
                String ckdbh = null;

                try {
                    List<Map> ddlist = (List<Map>) ydClient.queryData(
                            YDParam.builder()
                                    .formUuid("FORM-AADBCDA8126F41A0ADDEE3353828583192M8")
                                    .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                                    .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                                    .searchCondition(JSON.toJSONString(UtilMap.map("textField_mg34txgm", ckddjbh)))
                                    .build(),
                            YDConf.FORM_QUERY.retrieve_list_all
                    ).getData();

                    if (ddlist != null && !ddlist.isEmpty()) {
                        for (Map<String, Object> khitem : ddlist) {
                            Map<String, Object> khformData = (Map<String, Object>) khitem.get("formData");
                            if (khformData != null && ckddjbh.equals(khformData.get("textField_mg34txgm"))) {
                                ckdformInstanceId = (String) khitem.get("formInstanceId");
                                ckdbh = (String) khformData.get("textField_mg34txgm");
                                break;
                            }
                        }

                        if (ckdformInstanceId == null) {
                            log.warn("未找到与ckdbh={}完全匹配的订单数据", ckdbh);
                        }
                    } else {
                        log.warn("未查询到订单数据: ckdbh={}", ckdbh);
                    }

                } catch (Exception e) {
                    log.error("查询订单数据异常: ckdbh={}, 错误信息={}", ckdbh, e.getMessage(), e);
                }


                // 构建主表数据
                HashMap<Object, Object> updateData = new HashMap<>();
                updateData.put("tableField_mf6el3zx", tableList);
                if (ckdbh != null && ckdformInstanceId != null) {
                    updateData.put("associationFormField_mejmtick",
                            Arrays.asList(getysdAss(ckdbh, ckdformInstanceId)));
                }
                updateData.put("tableField_mhiui6v5", tableListPay);
                updateData.put("textField_mg3a0tgs", kdYdReceivable.getDjbh());
                updateData.put("textField_mj15q3dk", ckddjbh);
                updateData.put("selectField_mg3a0th4", kdYdReceivable.getDjlx());
                updateData.put("selectField_mev13l3r", kdYdReceivable.getSktj());
                updateData.put("dateField_mejmtic3", kdYdReceivable.getEndTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
                updateData.put("dateField_mejmtic2", kdYdReceivable.getBusinessTime().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli());
                updateData.put("numberField_mejmtic8", kdYdReceivable.getJshj() != null ? kdYdReceivable.getJshj().setScale(2, java.math.RoundingMode.HALF_UP) : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                updateData.put("textField_mejmml3k", kdYdReceivable.getKh());
                updateData.put("textField_mhjy9hzh", kdYdReceivable.getXsy());
                updateData.put("selectField_mejowmnc", kdYdReceivable.getXslx());
                updateData.put("selectField_megi74y8", kdYdReceivable.getKhsx());
                updateData.put("textField_krnn5bmr", kdYdReceivable.getXsbm());
                updateData.put("textField_mhjy9hzi", kdYdReceivable.getLzlx());
                updateData.put("textareaField_mg3a0tgx", kdYdReceivable.getBz());
                updateData.put("selectField_mg3fuqvn", kdYdReceivable.getBb());

                log.debug("开始同步到宜搭: 单据编号={}, 表单UUID=FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU", djbh);

                // 执行同步
                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-4E1CE4550339494A9BE5498FB119FF2E9ERU")
                        .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mg3a0tgs", kdYdReceivable.getDjbh())))
                        .formDataJson(JSONObject.toJSONString(updateData))
                        .build(), YDConf.FORM_OPERATION.upsert
                );

                kdYdReceivable.setSyncStatus("1");
                kdYdReceivableMapper.updateById(kdYdReceivable);
                successCount++;

                log.info("应收单同步成功: 单据编号={}", djbh);

            } catch (Exception e) {
                failCount++;
                log.error("同步应收单异常: ID={}, 单据编号={}, 错误信息={}",
                        kdYdReceivable.getId(), kdYdReceivable.getDjbh(), e.getMessage(), e);
            }
        }

        log.info("【应收单同步任务】完成: 成功={}, 失败={}, 总计={}",
                successCount, failCount, kdYdReceivables.size());
    }

    @Override
    public void synckdYdZp() {
        log.info("定时同步-发票单");
        try {

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            List<KdYdZp> kdYdZps = kdYdZpMapper.selectRecentUpdated(fiveMinutesAgo);
            if (kdYdZps.isEmpty()) {
                log.info("【发票单同步任务】无需要同步的数据，结束");
                return;
            }

            for (KdYdZp kdYdZp : kdYdZps) {
                try {
                    String djbh = kdYdZp.getDjbh();
                    String fph = kdYdZp.getFph();
//                    String formInstId = kdYdZp.getForminstid();
//                    if (ObjectUtil.hasEmpty(formInstId, djbh, fph)) {
//                        log.warn("跳过同步: formInstId 或 khbm 为空, customer={}", kdYdZp.getId());
//                        continue;
//                    }

                    ydClient.operateData(
                            YDParam.builder()
//                                    .formInstanceId(formInstId)
                                    .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_mgt6lcqq, textField_mejmml3a", djbh, fph)))
                                    .useLatestVersion(true).build(), YDConf.FORM_OPERATION.update);

                } catch (Exception e) {
//                    log.error("同步单条发票单数据异常: formInstId={}", kdYdZp.getForminstid(), e);
                }
            }

            log.info("【发票单同步任务】执行完成，共处理 {} 条记录", kdYdZps.size());
        } catch (Exception e) {
            log.error("【发票单同步任务】执行过程中发生严重错误", e);
        }
    }

    @Override
    public void synckdYdMaterial() {
        log.info("定时同步-物料单");
        // 查询需要删除的数据
        LambdaQueryWrapper<KdYdMaterial> materialdel = new LambdaQueryWrapper<>();
        materialdel.eq(KdYdMaterial::getOperationType, "3")
                .eq(KdYdMaterial::getSyncStatus, "0");
        List<KdYdMaterial> kdYdMaterialdels = kdYdMaterialMapper.selectList(materialdel);

        // 批量删除处理
        if (!kdYdMaterialdels.isEmpty()) {
            log.info("开始处理删除操作，共{}条数据", kdYdMaterialdels.size());
            ArrayList<String> list = new ArrayList<>();
            int deleteSuccessCount = 0;

            for (KdYdMaterial kdYdMaterial : kdYdMaterialdels) {
                try {
                    String wlbm = String.valueOf(kdYdMaterial.getFMATERIALID());
                    List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")  // 新增：添加应用参数
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")  // 新增：添加系统令牌
                            .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_misfb2ft", wlbm)))
                            .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                    if (list1 != null && !list1.isEmpty()) {
                        for (Map map : list1) {
                            String formInstanceId = UtilMap.getString(map, "formInstanceId");
                            if (formInstanceId != null) {
                                list.add(formInstanceId);
                                log.debug("找到待删除的表单实例: formInstanceId={}", formInstanceId);
                            }
                        }
                        deleteSuccessCount++;
                    } else {
                        log.warn("未找到对应的物料数据: wlbm={}", wlbm);
                    }

                    // 删除操作完成后更新状态
                    kdYdMaterial.setSyncStatus("1");
                    kdYdMaterialMapper.updateById(kdYdMaterial);

                } catch (Exception e) {
                    log.error("删除物料数据查询异常: wlbm={}", kdYdMaterial.getWlbm(), e);
                }
            }

            // 执行批量删除
            if (!list.isEmpty()) {
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .formInstanceIdList(list)
                            .build(), YDConf.FORM_OPERATION.delete_batch);
                    log.info("批量删除完成，共删除{}条数据", list.size());
                } catch (Exception e) {
                    log.error("批量删除操作异常", e);
                }
            }

            return;
        }
        LambdaQueryWrapper<KdYdMaterial> materialqw = new LambdaQueryWrapper<>();
        materialqw.eq(KdYdMaterial::getSyncStatus, "0");
        List<KdYdMaterial> kdYdMaterials = kdYdMaterialMapper.selectList(materialqw);
        log.info("本次需要同步的物料单数量: {}", kdYdMaterials.size());
        // 同步新增/更新数据
        if (kdYdMaterials.isEmpty()) {
            log.info("【物料单同步任务】无需要同步的数据，结束");
            return;
        }
        int successCount = 0;
        int failCount = 0;

        for (KdYdMaterial kdYdMaterial : kdYdMaterials) {
            try {
                String wlbm = kdYdMaterial.getWlbm();
                String wlmc = kdYdMaterial.getWlmc();
                String xh = kdYdMaterial.getXh();
                String gg = kdYdMaterial.getGg();
                String jdnm = String.valueOf(kdYdMaterial.getFMATERIALID());
                String wlfz = kdYdMaterial.getWlfz();
                String wlsx = kdYdMaterial.getWlsx();
                String jbdw = kdYdMaterial.getJbdw();
                String ssxl = kdYdMaterial.getSsxl();
                String jx = kdYdMaterial.getJx();
                Integer sd = kdYdMaterial.getSd();
                String mrsl = kdYdMaterial.getMrsl();
                String chlb = kdYdMaterial.getChlb();
                String xsy = kdYdMaterial.getXsy();
                BigDecimal xsjzj = kdYdMaterial.getXsjzj();
                String smzs = kdYdMaterial.getSmzs();
                String sjzt = kdYdMaterial.getSjzt();
                String jyzt = kdYdMaterial.getJyzt();
                String dzl = kdYdMaterial.getDzl();
                String pzzt = kdYdMaterial.getPzzt();
                String sdbb = kdYdMaterial.getSpeedname();
                String wlbt = wlmc + wlbm;
//                String materialtitle = kdYdMaterial.getMaterialtitle();
                Map updateFormData = new HashMap();
                updateFormData.put("textField_l43jpnsf", wlmc);
                updateFormData.put("textField_mfxbtcdh", wlbm);
                updateFormData.put("textField_l43jpnsg", xh);
                updateFormData.put("textField_lqbxkzbq", gg);
                updateFormData.put("textField_misfb2ft", jdnm);
                updateFormData.put("textField_mhlbx8hi", wlfz);
                updateFormData.put("textField_l43jpnsh", wlsx);
                updateFormData.put("textField_mfxbtcdo", jbdw);
                updateFormData.put("textField_mfxbtcdp", ssxl);
                updateFormData.put("textField_mejl9nrs", jx);
                updateFormData.put("numberField_mfxbtceb", sd);
                updateFormData.put("textField_mejl9nrp", dzl);
                updateFormData.put("selectField_mejl9nrq", pzzt);
                updateFormData.put("textField_mfxbtcdq", mrsl);
                updateFormData.put("textField_mhabp7y0", sdbb);
                updateFormData.put("textField_mfxbtcdr", chlb);
                updateFormData.put("textField_mfxbtce5", xsy);
                updateFormData.put("textField_mfxbtce6", sjzt);

                updateFormData.put("dateField_ml4ikfa0",
                        kdYdMaterial.getKsrq() != null && !kdYdMaterial.getKsrq().trim().isEmpty() ?
                                java.time.LocalDate.parse(kdYdMaterial.getKsrq().trim())
                                        .atStartOfDay(java.time.ZoneId.systemDefault())
                                        .toInstant()
                                        .toEpochMilli() :
                                null
                );
                updateFormData.put("dateField_ml4ikfa1",
                        kdYdMaterial.getJzrq() != null && !kdYdMaterial.getJzrq().trim().isEmpty() ?
                                java.time.LocalDate.parse(kdYdMaterial.getJzrq().trim())
                                        .atStartOfDay(java.time.ZoneId.systemDefault())
                                        .toInstant()
                                        .toEpochMilli() :
                                null
                );

                //确保金额字段保留两位小数
                if (xsjzj != null) {
                    updateFormData.put("numberField_mejl9nsc", xsjzj.setScale(2, java.math.RoundingMode.HALF_UP));
                } else {
                    updateFormData.put("numberField_mejl9nsc", java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP));
                }

                updateFormData.put("textField_mfxbtce4", smzs);
                updateFormData.put("textField_mfxbtcea", jyzt);
                updateFormData.put("textField_mg4h6mz5", wlbt);
                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                        .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                        .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                        .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch(
                                "textField_misfb2ft", jdnm, "金蝶内码", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ))))
                        .formDataJson(JSONObject.toJSONString(updateFormData))
                        .build(), YDConf.FORM_OPERATION.upsert);

                // 同步成功，更新状态
                kdYdMaterial.setSyncStatus("1");
                kdYdMaterialMapper.updateById(kdYdMaterial);
                successCount++;

                log.info("物料单同步成功: wlbm={}, wlmc={}", wlbm, wlmc);

            } catch (Exception e) {
                failCount++;
                log.error("同步单条物料单数据异常: wlbm={}, wlmc={}",
                        kdYdMaterial.getWlbm(), kdYdMaterial.getWlmc(), e);
            }
        }

        // 添加同步结果统计日志
        log.info("物料单同步完成: 成功={}, 失败={}, 总计={}",
                successCount, failCount, kdYdMaterials.size());
    }

    @Override
    public void syncKdYdDeliveryDetail() {
        log.info("定时同步-发货单详情");
        try {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);

            // 1. 查询最近更新的 delivery detail
            List<KdYdDeliveryDetail> kdYdDeliveryDetails = kdYdDeliveryDetailMapper.selectRecentUpdated(fiveMinutesAgo);

            if (kdYdDeliveryDetails.isEmpty()) {
                log.info("【发货详情单同步任务】无需要同步的数据，结束");
                return;
            }

            // 2. 按 deliveryId 提取主单 ID 列表，避免重复查询
            Set<Long> deliveryIds = kdYdDeliveryDetails.stream()
                    .map(KdYdDeliveryDetail::getDeliveryId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toSet());

            // 3. 批量查询主单信息（包含 formInstId）
            List<KdYdDelivery> mainDeliveries = kdYdDeliveryMapper.selectBatchIds(deliveryIds);
            Map<Long, KdYdDelivery> deliveryMap = mainDeliveries.stream()
                    .collect(Collectors.toMap(KdYdDelivery::getId, d -> d));

            // 4. 按 formInstId 分组，减少 API 调用次数
//            Map<String, List<KdYdDeliveryDetail>> detailsByFormInstId = kdYdDeliveryDetails.stream()
//                    .filter(detail -> deliveryMap.containsKey(detail.getDeliveryId()))
//                    .collect(Collectors.groupingBy(detail -> {
//                        KdYdDelivery main = deliveryMap.get(detail.getDeliveryId());
//                        return main != null ? main.getForminstid() : null;
//                    }));

            int successCount = 0;
            int errorCount = 0;

            // 5. 遍历每个 formInstId，只调用一次 query + 一次 update
//            for (Map.Entry<String, List<KdYdDeliveryDetail>> entry : detailsByFormInstId.entrySet()) {
//                String formInstId = entry.getKey();
//                if (formInstId == null || formInstId.trim().isEmpty()) {
//                    log.warn("跳过空 formInstId 的记录");
//                    continue;
//                }
//
//                try {
//                    // 查询当前表单数据
//                    Map formData = ydClient.queryData(
//                            YDParam.builder()
//                                    .formInstId(formInstId)
//                                    .appType(ydConf.getAppType())
//                                    .systemToken(ydConf.getSystemToken())
//                                    .userId(ddConf.getOperator())
//                                    .build(),
//                            YDConf.FORM_QUERY.retrieve_id
//                    ).getFormData();
//
//                    if (formData == null) {
//                        log.warn("formInstId={} 的 formData 为空", formInstId);
//                        continue;
//                    }
//
//                    List<Map<String, Object>> tableData = (List<Map<String, Object>>) formData.get("tableField_mejnamfd");
//                    if (tableData == null || tableData.isEmpty()) {
//                        log.warn("formInstId={} 的子表 tableField_mejnamfd 为空", formInstId);
//                        continue;
//                    }
//                    // 标记是否需要更新
//                    boolean modified = false;
//
//                    // 处理当前 formInstId 下的所有待同步 detail
//                    for (KdYdDeliveryDetail detail : entry.getValue()) {
//                        String wlbm = detail.getWlbm();
//                        String mdh = detail.getMdh();
//
//                        for (Map<String, Object> row : tableData) {
//                            Object wlbmIdObj = row.get("textField_mejnamff");
//                            if (wlbmIdObj != null && wlbm.equals(wlbmIdObj.toString())) {
//                                row.put("textField_mf6a0h6y", mdh);
//                                modified = true;
//                                successCount++;
//                                break; // 找到匹配行即可跳出
//                            }
//                        }
//                    }
//
//                    // 只有修改了才提交
//                    if (modified) {
//                        ydClient.operateData(
//                                YDParam.builder()
//                                        .formInstanceId(formInstId)
//                                        .updateFormDataJson(JSON.toJSONString(Collections.singletonMap("tableField_mejnamfd", tableData)))
//                                        .useLatestVersion(true)
//                                        .build(),
//                                YDConf.FORM_OPERATION.update
//                        );
//                        log.debug("已更新 formInstId={} 的子表数据", formInstId);
//                    } else {
//                        log.debug("formInstId={} 无需更新", formInstId);
//                    }
//
//                } catch (Exception e) {
//                    errorCount += entry.getValue().size(); // 统计失败数量
//                    log.error("同步 formInstId={} 时发生异常", formInstId, e);
//                }
//            }
//
//            log.info("【发货详情单同步任务】执行完成，共处理 {} 条记录，成功 {} 条，失败 {} 条",
//                    kdYdDeliveryDetails.size(), successCount, errorCount);
//
        } catch (Exception e) {
            log.error("【发货单同步任务】执行过程中发生严重错误", e);
        }
    }

    @Override
    public void synckdYdPayment() {
        log.info("定时同步-收款单");
        LambdaQueryWrapper<KdYdPaymentReceipt> paymentdel = new LambdaQueryWrapper<>();
        paymentdel.eq(KdYdPaymentReceipt::getOperationType, 3)
                .eq(KdYdPaymentReceipt::getSyncStatus, "0");
        List<KdYdPaymentReceipt> kdYdPaymentReceiptdels = kdYdPaymentReceiptMapper.selectList(paymentdel);

        // 批量删除处理
        if (!kdYdPaymentReceiptdels.isEmpty()) {
            log.info("开始处理收款单删除操作，共{}条数据", kdYdPaymentReceiptdels.size());
            ArrayList<String> deleteList = new ArrayList<>();
            int deleteSuccessCount = 0;

            for (KdYdPaymentReceipt kdYdPaymentReceipt : kdYdPaymentReceiptdels) {
                try {
                    String djbh = kdYdPaymentReceipt.getDjbh();
                    log.debug("查询需要删除的收款单: djbh={}", djbh);

                    List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mh9woamt", djbh)))
                            .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                    if (list1 != null && !list1.isEmpty()) {
                        for (Map map : list1) {
                            String formInstanceId = UtilMap.getString(map, "formInstanceId");
                            if (formInstanceId != null) {
                                deleteList.add(formInstanceId);
                            }
                        }
                        deleteSuccessCount++;

                        // 同时删除对应的子表数据
                        Long paymentReceiptId = kdYdPaymentReceipt.getId();
                        LambdaQueryWrapper<KdYdPaymentReceiptDetail> detailDelqw = new LambdaQueryWrapper<>();
                        detailDelqw.eq(KdYdPaymentReceiptDetail::getPayreceiptId, paymentReceiptId);
                        List<KdYdPaymentReceiptDetail> detailDels = kdYdPaymentReceiptDetailMapper.selectList(detailDelqw);

                        if (!detailDels.isEmpty()) {
                            for (KdYdPaymentReceiptDetail detail : detailDels) {
                                detail.setSyncStatus("1");
                                kdYdPaymentReceiptDetailMapper.updateById(detail);
                            }
                        }
                    } else {
                        log.warn("未找到对应的收款单数据: djbh={}", djbh);
                    }

                    // 删除操作完成后更新状态
                    kdYdPaymentReceipt.setSyncStatus("1");
                    kdYdPaymentReceiptMapper.updateById(kdYdPaymentReceipt);

                } catch (Exception e) {
                    log.error("删除收款单数据查询异常: djbh={}", kdYdPaymentReceipt.getDjbh(), e);
                }
            }

            // 执行批量删除
            if (!deleteList.isEmpty()) {
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .formInstanceIdList(deleteList)
                            .build(), YDConf.FORM_OPERATION.delete_batch);
                    log.info("收款单批量删除完成，共删除{}条数据", deleteList.size());
                } catch (Exception e) {
                    log.error("收款单批量删除操作异常", e);
                }
            }

            log.info("收款单删除操作处理完成: 成功查询={}, 待删除={}", deleteSuccessCount, deleteList.size());
            return;
        } else {
            log.info("【收款单删除任务】无需要删除的数据");
        }
        LambdaQueryWrapper<KdYdPaymentReceipt> paymentqw = new LambdaQueryWrapper<>();
        paymentqw.eq(KdYdPaymentReceipt::getSyncStatus, "0");
        List<KdYdPaymentReceipt> kdYdPaymentReceipts = kdYdPaymentReceiptMapper.selectList(paymentqw);
        if (kdYdPaymentReceipts.isEmpty()) {
            log.info("【收款单同步任务】无需要同步的数据，结束");
            return;
        }
        log.info("【收款单同步任务】开始同步，共{}条数据", kdYdPaymentReceipts.size());

        int successCount = 0;
        int failCount = 0;

        for (KdYdPaymentReceipt kdYdPaymentReceipt : kdYdPaymentReceipts) {
            try {
                Long paymentReceiptId = kdYdPaymentReceipt.getId();
                String djbh = kdYdPaymentReceipt.getDjbh();

                log.debug("开始同步收款单: ID={}, 单据编号={}", paymentReceiptId, djbh);

                LambdaQueryWrapper<KdYdPaymentReceiptDetail> receivedetailqw = new LambdaQueryWrapper<>();
                receivedetailqw.eq(KdYdPaymentReceiptDetail::getPayreceiptId, paymentReceiptId)
                        .orderByAsc(KdYdPaymentReceiptDetail::getDetailId);
                List<KdYdPaymentReceiptDetail> kdYDPaymentReceiptDetails = kdYdPaymentReceiptDetailMapper.selectList(receivedetailqw);
                ArrayList<Object> tableList = new ArrayList<>();
                for (KdYdPaymentReceiptDetail kdYdPaymentReceiptDetail : kdYDPaymentReceiptDetails) {
                    HashMap<String, String> tablemap = new HashMap<>();
                    tablemap.put("textField_mh9woanr", kdYdPaymentReceiptDetail.getJsfs());
                    tablemap.put("textField_mh9woans", kdYdPaymentReceiptDetail.getSkyt());
                    tablemap.put("textField_mh9woant", kdYdPaymentReceiptDetail.getYsxmlx());
                    tablemap.put("textField_mh9woanu", kdYdPaymentReceiptDetail.getYsxsdd());
                    tablemap.put("numberField_mh9woanv", kdYdPaymentReceiptDetail.getYsje() != null ? kdYdPaymentReceiptDetail.getYsje().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mh9woanw", kdYdPaymentReceiptDetail.getSxf() != null ? kdYdPaymentReceiptDetail.getSxf().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("textField_mhmr1ecr", kdYdPaymentReceiptDetail.getCdk());
                    tablemap.put("textField_mh9woany", kdYdPaymentReceiptDetail.getWfyhzh());
                    tablemap.put("textField_mh9woao2", kdYdPaymentReceiptDetail.getXsddh());
                    tablemap.put("textField_mh9woao1", kdYdPaymentReceiptDetail.getFyxm());
                    tablemap.put("numberField_mh9woanz", kdYdPaymentReceiptDetail.getSsje() != null ? kdYdPaymentReceiptDetail.getSsje().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    tablemap.put("numberField_mh9woao0", kdYdPaymentReceiptDetail.getZhje() != null ? kdYdPaymentReceiptDetail.getZhje().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                    kdYdPaymentReceiptDetail.setSyncStatus("1");
                    kdYdPaymentReceiptDetailMapper.updateById(kdYdPaymentReceiptDetail);
//                    tablemap.put("radioField_mf6a0h6h", kdYdOutboundDetail.getSfzp());
                    tableList.add(tablemap);

                }
                String xsddbh = kdYdPaymentReceipt.getXsddbh();
                String ddformInstanceId = null;
                String ddbh = null;

                try {
                    log.debug("开始查询订单数据: xsddbh={}", xsddbh);

                    List<Map> ddlist = (List<Map>) ydClient.queryData(
                            YDParam.builder()
                                    .formUuid("FORM-B62CAE3075CE4098B17BB86C90FFA21C9B7C")
                                    .searchCondition(JSON.toJSONString(UtilMap.map("textField_mjs6fuwo", xsddbh)))
                                    .build(),
                            YDConf.FORM_QUERY.retrieve_list_all
                    ).getData();

                    if (ddlist != null && !ddlist.isEmpty()) {
                        for (Map<String, Object> khitem : ddlist) {
                            Map<String, Object> khformData = (Map<String, Object>) khitem.get("formData");

                            if (khformData != null && xsddbh.equals(khformData.get("textField_mjs6fuwo"))) {
                                ddformInstanceId = (String) khitem.get("formInstanceId");
                                ddbh = (String) khformData.get("textField_mjs6fuwo");
                                break;
                            }
                        }

                        if (ddformInstanceId == null) {
                            log.warn("未找到与xsddbh={}完全匹配的订单数据", xsddbh);
                        }
                    } else {
                        log.warn("未查询到订单数据: xsddbh={}", xsddbh);
                    }

                } catch (Exception e) {
                    log.error("查询订单数据异常: xsddbh={}, 错误信息={}", xsddbh, e.getMessage(), e);
                }
                HashMap<Object, Object> updateMap = new HashMap<>();
                updateMap.put("tableField_mh9woanl", tableList);
                if (ddbh != null && ddformInstanceId != null) {
                    updateMap.put("associationFormField_mh9woamy",
                            Arrays.asList(getddAss(ddbh, ddformInstanceId)));
                }
                updateMap.put("textField_mh9woanm", kdYdPaymentReceipt.getDjlx());
                updateMap.put("textField_mh9woann", kdYdPaymentReceipt.getFkdwlx());
                updateMap.put("textField_mh9woamt", kdYdPaymentReceipt.getDjbh());
                updateMap.put("textField_mh9woamz", kdYdPaymentReceipt.getSkgld());
                updateMap.put("textField_mh9woano", kdYdPaymentReceipt.getBb());
                updateMap.put("dateField_mh9woan5", kdYdPaymentReceipt.getYwrq() != null ? String.valueOf(kdYdPaymentReceipt.getYwrq().atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()) : "");
                updateMap.put("textField_mh9woanp", kdYdPaymentReceipt.getWldwlx());
                updateMap.put("textField_mh9woanq", kdYdPaymentReceipt.getWldw());
                updateMap.put("numberField_mh9woanc", kdYdPaymentReceipt.getYsje() != null ? kdYdPaymentReceipt.getYsje().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                updateMap.put("numberField_mh9woand", kdYdPaymentReceipt.getSsje() != null ? kdYdPaymentReceipt.getSsje().setScale(2, java.math.RoundingMode.HALF_UP).toString() : java.math.BigDecimal.ZERO.setScale(2, java.math.RoundingMode.HALF_UP).toString());
                updateMap.put("textField_mhjxv2tf", kdYdPaymentReceipt.getXsy());
                updateMap.put("textField_mhjxv2tg", kdYdPaymentReceipt.getXsbm());
                updateMap.put("textareaField_mh9woank", kdYdPaymentReceipt.getBz());

                log.debug("开始同步到宜搭: 单据编号={}, 表单UUID=FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM", djbh);

                // 添加同步操作（根据您的实际需求添加）
                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-0569C06E47074C2981ADEEAFCE083EDAK5AM")
                        .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_mh9woamt", kdYdPaymentReceipt.getDjbh())))
                        .formDataJson(JSONObject.toJSONString(updateMap))
                        .build(), YDConf.FORM_OPERATION.upsert);

                // 更新同步状态
                kdYdPaymentReceipt.setSyncStatus("1");
                kdYdPaymentReceiptMapper.updateById(kdYdPaymentReceipt);
                successCount++;

                log.info("收款单同步成功: 单据编号={}", djbh);

            } catch (Exception e) {
                failCount++;
                log.error("同步单条收款单数据异常: 单据编号={}, 错误信息={}",
                        kdYdPaymentReceipt.getDjbh(), e.getMessage(), e);
            }
        }

        log.info("【收款单同步任务】完成: 成功={}, 失败={}, 总计={}",
                successCount, failCount, kdYdPaymentReceipts.size());
    }

    @Override
    public void synckdYdTRANSFER() {
        log.info("定时同步-调拨单");
        LambdaQueryWrapper<KdYdTransfer> transferdel = new LambdaQueryWrapper<>();
        transferdel.eq(KdYdTransfer::getOperationType, 3)
                .eq(KdYdTransfer::getSyncStatus, "0");
        List<KdYdTransfer> kdYdTRANSFERdels = kdYdTransferMapper.selectList(transferdel);

        // 批量删除处理
        if (!kdYdTRANSFERdels.isEmpty()) {
            log.info("开始处理调拨单删除操作，共{}条数据", kdYdTRANSFERdels.size());
            ArrayList<String> deleteList = new ArrayList<>();
            int deleteSuccessCount = 0;

            for (KdYdTransfer kdYdTransfer : kdYdTRANSFERdels) {
                try {
                    String djbh = kdYdTransfer.getDjbh();
                    log.debug("查询需要删除的调拨单: djbh={}", djbh);

                    List<Map> list1 = (List<Map>) ydClient.queryData(YDParam.builder()
                            .formUuid("FORM-F1B2BA2AF310476C88F4756F4DB50667VXDR")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_miptelgc", djbh)))
                            .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

                    if (list1 != null && !list1.isEmpty()) {
                        for (Map map : list1) {
                            String formInstanceId = UtilMap.getString(map, "formInstanceId");
                            if (formInstanceId != null) {
                                deleteList.add(formInstanceId);
                            }
                        }
                        deleteSuccessCount++;

                        // 同时删除对应的子表数据
                        Long transferId = kdYdTransfer.getId();
                        LambdaQueryWrapper<KdYdTransferDetail> detailDelqw = new LambdaQueryWrapper<>();
                        detailDelqw.eq(KdYdTransferDetail::getTransferId, transferId);
                        List<KdYdTransferDetail> detailDels = kdYdTransferDetailMapper.selectList(detailDelqw);

                        if (!detailDels.isEmpty()) {
                            for (KdYdTransferDetail detail : detailDels) {
                                detail.setSyncStatus("1");
                                kdYdTransferDetailMapper.updateById(detail);
                            }
                        }
                    } else {
                        log.warn("未找到对应的调拨单数据: djbh={}", djbh);
                    }

                    // 删除操作完成后更新状态
                    kdYdTransfer.setSyncStatus("1");
                    kdYdTransferMapper.updateById(kdYdTransfer);

                } catch (Exception e) {
                    log.error("删除调拨单数据查询异常: djbh={}", kdYdTransfer.getDjbh(), e);
                }
            }

            // 执行批量删除
            if (!deleteList.isEmpty()) {
                try {
                    ydClient.operateData(YDParam.builder()
                            .formUuid("FORM-F1B2BA2AF310476C88F4756F4DB50667VXDR")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .formInstanceIdList(deleteList)
                            .build(), YDConf.FORM_OPERATION.delete_batch);
                    log.info("调拨单批量删除完成，共删除{}条数据", deleteList.size());
                } catch (Exception e) {
                    log.error("调拨单批量删除操作异常", e);
                }
            }

            log.info("调拨单删除操作处理完成: 成功查询={}, 待删除={}", deleteSuccessCount, deleteList.size());
            return;
        } else {
            log.info("【调拨单删除任务】无需要删除的数据");
        }
        LambdaQueryWrapper<KdYdTransfer> paymentqw = new LambdaQueryWrapper<>();
        paymentqw.eq(KdYdTransfer::getSyncStatus, "0");
        List<KdYdTransfer> kdYdTransfers = kdYdTransferMapper.selectList(paymentqw);
        if (kdYdTransfers.isEmpty()) {
            log.info("【调拨单同步任务】无需要同步的数据，结束");
            return;
        }
        log.info("【调拨单同步任务】开始同步，共{}条数据", kdYdTransfers.size());

        int successCount = 0;
        int failCount = 0;

        for (KdYdTransfer kdYdTransfer : kdYdTransfers) {
            try {
                Long transferId = kdYdTransfer.getId();
                String djbh = kdYdTransfer.getDjbh();

                log.debug("开始同步调拨单: ID={}, 单据编号={}", transferId, djbh);

                LambdaQueryWrapper<KdYdTransferDetail> transferdetailqw = new LambdaQueryWrapper<>();
                transferdetailqw.eq(KdYdTransferDetail::getTransferId, transferId)
                        .orderByAsc(KdYdTransferDetail::getDetailId);
                List<KdYdTransferDetail> kdYdTransferDetails = kdYdTransferDetailMapper.selectList(transferdetailqw);
                ArrayList<Object> tableList = new ArrayList<>();
                List<Map<String, Object>> tableListxlh = new ArrayList<>();
                for (KdYdTransferDetail kdYdTransferDetail : kdYdTransferDetails) {
                    HashMap<String, String> tablemap = new HashMap<>();
                    tablemap.put("textField_mhubzsav", kdYdTransferDetail.getWlbm());
                    tablemap.put("textField_mhubzsaw", kdYdTransferDetail.getWlmc());
                    tablemap.put("textField_mhubzsax", kdYdTransferDetail.getGgxh());
                    tablemap.put("textField_mhubzsay", kdYdTransferDetail.getDw());
                    tablemap.put("textareaField_mjshnw4c", kdYdTransferDetail.getKddh());
                    tablemap.put("numberField_mhubzsaz", String.valueOf(kdYdTransferDetail.getDbsl()));
                    tablemap.put("textField_mhubzsb0", kdYdTransferDetail.getPh());
                    tablemap.put("textField_mhubzsb1", kdYdTransferDetail.getDcck());
                    tablemap.put("textField_mhubzsb5", kdYdTransferDetail.getDcckzt());
                    tablemap.put("textField_mhubzsb2", kdYdTransferDetail.getDccw());
                    tablemap.put("textField_mhubzsb3", kdYdTransferDetail.getDrck());
                    tablemap.put("textField_mhubzsb6", kdYdTransferDetail.getDrckzt());
                    tablemap.put("textField_mhubzsb4", kdYdTransferDetail.getDrcw());
                    String xlhjh = kdYdTransferDetail.getXlh();
                    if (xlhjh != null && !xlhjh.trim().isEmpty()) {
                        List<Map<String, Object>> currentXlhList = Arrays.stream(xlhjh.split(","))
                                .map(String::trim)
                                .filter(item -> !item.isEmpty())
                                .map(item -> {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("textField_mf6a0h6w", item); // 序列号
                                    map.put("textField_mjqst61l", kdYdTransferDetail.getWlbm()); // 对应的物料编码
                                    map.put("textField_mjqst61m", kdYdTransferDetail.getGgxh());
                                    return map;
                                })
                                .collect(Collectors.toList());

                        tableListxlh.addAll(currentXlhList); // 追加到总列表
                    }

                    // 主表仍保留原始 xlh（可选）
                    tablemap.put("textField_mf6a0h6w", kdYdTransferDetail.getXlh());
//                    tablemap.put("radioField_mf6a0h6h", kdYdTransferDetail.getSfzp());

                    tableList.add(tablemap);
                    kdYdTransferDetail.setSyncStatus("1");
                    kdYdTransferDetailMapper.updateById(kdYdTransferDetail);

                }
                String xsddbh = kdYdTransfer.getDdbh();
                String fhtzdbh = kdYdTransfer.getFhtzdbh();
                String ddformInstanceId = null;
                String fhdformInstanceId = null;
                String ddbh = null;
                String fhdbh = null;
                String jydate = null;
                String ghrq = null;
                String jyyy = null;
                String jtyy = null;
                String xsy = null;
                String khxypj = null;
                String fj = null;

                try {
                    log.debug("开始查询订单数据: xsddbh={}", xsddbh);

                    // 宜搭返回的数据结构：List<Map<String, Object>>
                    List<Map<String, Object>> ddlist = (List<Map<String, Object>>) ydClient.queryData(
                            YDParam.builder()
                                    .formUuid("FORM-B62CAE3075CE4098B17BB86C90FFA21C9B7C")
                                    .searchCondition(JSON.toJSONString(UtilMap.map("textField_mjs6fuwo", xsddbh)))
                                    .build(),
                            YDConf.FORM_QUERY.retrieve_list_all
                    ).getData();

                    List<Map<String, Object>> fhdlist = (List<Map<String, Object>>) ydClient.queryData(
                            YDParam.builder()
                                    .formUuid("FORM-FAE2575E112644ED914CAB4FEC9309F32AVR")
                                    .searchCondition(JSON.toJSONString(UtilMap.map("serialNumberField_mheazm7w", fhtzdbh)))
                                    .build(),
                            YDConf.FORM_QUERY.retrieve_list_all
                    ).getData();
                    if (fhdlist != null && !fhdlist.isEmpty()) {
                        for (Map<String, Object> fhditem : fhdlist) {
                            Map<String, Object> fhdformData = (Map<String, Object>) fhditem.get("formData");
                            if (fhdformData == null) continue;
                            Object serialObj1 = fhdformData.get("serialNumberField_mheazm7w");
                            String serialStr1 = serialObj1 != null ? serialObj1.toString() : null;
                            if (fhtzdbh.equals(serialStr1)) {
                                fhdformInstanceId = safeToString(fhditem.get("formInstanceId"));
                                fhdbh = serialStr1;
                                break;
                            }
                        }
                    }
                    if (ddlist != null && !ddlist.isEmpty()) {
                        for (Map<String, Object> khitem : ddlist) {
                            Map<String, Object> khformData = (Map<String, Object>) khitem.get("formData");
                            if (khformData == null) continue;

                            // 安全获取字段值（避免 ClassCastException）
                            Object serialObj = khformData.get("textField_mjs6fuwo");
                            String serialStr = serialObj instanceof String ? (String) serialObj : String.valueOf(serialObj);

                            if (xsddbh.equals(serialStr)) {
                                ddformInstanceId = safeToString(khitem.get("formInstanceId"));
                                ddbh = serialStr;
                                jydate = safeToString(khformData.get("dateField_mdya1lom"));
                                ghrq = safeToString(khformData.get("dateField_meqpbxsj"));
                                jyyy = safeToString(khformData.get("multiSelectField_meqpbxsc"));
                                jtyy = safeToString(khformData.get("textareaField_meqpbxsd"));
                                khxypj = safeToString(khformData.get("selectField_mewirdx4"));
                                xsy = safeToString(khformData.get("employeeField_mejowmng_id"));
                                fj = safeToString(khformData.get("attachmentField_mfoqcctz"));
                                break;
                            }
                        }

                        if (ddformInstanceId == null) {
                            log.warn("未找到与 xsddbh={} 完全匹配的订单数据", xsddbh);
                        }
                    } else {
                        log.warn("未查询到订单数据: xsddbh={}", xsddbh);
                    }

                } catch (Exception e) {
                    log.error("查询订单数据异常: xsddbh={}, 错误信息={}", xsddbh, e.getMessage(), e);
                }

// 构建更新数据
                HashMap<String, Object> updateMap = new HashMap<>();
                updateMap.put("tableField_mhubzsau", tableList);
                updateMap.put("tableField_mips137b", tableListxlh);
                if (ddbh != null && ddformInstanceId != null) {
                    updateMap.put("associationFormField_mhubzsaf",
                            Collections.singletonList(getddAss(ddbh, ddformInstanceId)));
                }
                if (fhdbh != null && fhdformInstanceId != null) {
                    updateMap.put("associationFormField_mjzervdt",
                            Collections.singletonList(getddAss(fhdbh, fhdformInstanceId)));

                }
// 只有所有必要字段都非空时才填充关联字段
                if (jydate != null && ghrq != null && jyyy != null && jtyy != null
                        && xsy != null && khxypj != null) {

                    updateMap.put("dateField_mdya1lom", jydate);
                    updateMap.put("dateField_meqpbxsj", ghrq);
                    updateMap.put("multiSelectField_meqpbxsc", jyyy);
                    updateMap.put("textareaField_meqpbxsd", jtyy); // 注意：原代码这里写成了 jyyy，已修正为 jtyy
                    updateMap.put("employeeField_mejowmng", xsy);
                    updateMap.put("selectField_mewirdx4", khxypj);
                    updateMap.put("attachmentField_mfoqcctz", fj);
                }
                updateMap.put("textField_mjzervdu", kdYdTransfer.getFhtzdbh());
// 基础字段同步（这些字段即使为空也会覆盖，符合原逻辑）
                updateMap.put("textField_miquh5zj", ddformInstanceId);
                updateMap.put("selectField_mhubzsa5", kdYdTransfer.getDjlx());
                updateMap.put("textField_mhubzsas", kdYdTransfer.getKh());
                updateMap.put("textField_miptelgh", kdYdTransfer.getDdbh());
                updateMap.put("textField_miptelgc", kdYdTransfer.getDjbh());
                updateMap.put("textField_miptelgd", kdYdTransfer.getCgy());
                updateMap.put("selectField_mhubzsa7", kdYdTransfer.getDchzlx());
                updateMap.put("textField_mhubzsa6", kdYdTransfer.getYwlx());

// 日期字段：转为毫秒字符串（保持原逻辑）
                String rqMillis = "";
                if (kdYdTransfer.getRq() != null) {
                    rqMillis = String.valueOf(kdYdTransfer.getRq()
                            .atZone(ZoneId.systemDefault())
                            .toInstant()
                            .toEpochMilli());
                }
                updateMap.put("dateField_mhubzsab", rqMillis);

                updateMap.put("selectField_mhubzsa9", kdYdTransfer.getDrhzlx());
                updateMap.put("selectField_mhubzsaa", kdYdTransfer.getDbfx());
                updateMap.put("selectField_mhubzsac", kdYdTransfer.getDbdlx());
                updateMap.put("textField_miptelge", kdYdTransfer.getDcbm());
                updateMap.put("textField_miptelgf", kdYdTransfer.getDchz());
                updateMap.put("textField_miptelgg", kdYdTransfer.getDrbm());
                updateMap.put("selectField_mhubzsah", kdYdTransfer.getHdfs());
                updateMap.put("selectField_mhubzsai", kdYdTransfer.getYsfs());
                updateMap.put("selectField_mhubzsar", kdYdTransfer.getKdgs());
                updateMap.put("selectField_mhubzsag", kdYdTransfer.getFkfs());

                log.debug("开始同步到宜搭: 单据编号={}, 表单UUID=FORM-F1B2BA2AF310476C88F4756F4DB50667VXDR", kdYdTransfer.getDjbh());

                ydClient.operateData(YDParam.builder()
                        .formUuid("FORM-F1B2BA2AF310476C88F4756F4DB50667VXDR")
                        .noExecuteExpression(false)
                        .searchCondition(JSONObject.toJSONString(UtilMap.map("textField_miptelgc", kdYdTransfer.getDjbh())))
                        .formDataJson(JSONObject.toJSONString(updateMap))
                        .build(), YDConf.FORM_OPERATION.upsert);

// 更新同步状态
                kdYdTransfer.setSyncStatus("1");
                kdYdTransferMapper.updateById(kdYdTransfer);
                successCount++;

                log.info("调拨单同步成功: 单据编号={}", kdYdTransfer.getDjbh());
            } catch (Exception e) {
                failCount++;
                log.error("同步单条调拨单数据异常: 单据编号={}, 错误信息={}",
                        kdYdTransfer.getDjbh(), e.getMessage(), e);
            }
        }

        log.info("【调拨单同步任务】完成: 成功={}, 失败={}, 总计={}",
                successCount, failCount, kdYdTRANSFERdels.size());
    }

    @Override
    public void synckdYdMaterialxsy() {
        MDC.put("MDC_KEY_PID", "1003");
        //当前时间戳
        long time = System.currentTimeMillis();
        List<Map> list=ydService.queryFormData_all(YDParam.builder().formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90").searchFieldJson(
                JSONObject.toJSONString(Arrays.asList(
                        new YDSearch("dateField_ml4ikfa1",
                                time,
                                "DateField",
                                YDSearch.Type.DATE_FIELD,
                                YDSearch.Operator.LT)
//                        new YDSearch("textField_misfb2ft",
//                                "137804",
//                                "TextField",
//                                YDSearch.Type.TEXT_FIELD,
//                                YDSearch.Operator.EQ)
                ))
        ).build());

        if (list == null || list.isEmpty()) {
            log.info("没有找到需要处理的单据");
        }
        for (Map item : list) {
            String formInstanceId = String.valueOf(item.get("formInstanceId"));
            Map formData =new HashMap<>();
            formData.put("textField_mfxbtce5", "无");
            formData.put("dateField_ml4ikfa1", "4073040000000");
            retryOperateData(YDParam.builder()
                    .formInstId(formInstanceId)
                    .updateFormDataJson(JSON.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.update);
        }
        log.info("【物料同步任务】完成: 总计={}", list.size());
    }

    @Override
    public void synckdyqsq() {
        MDC.put("MDC_KEY_PID", "1003");
        //当前时间戳
        long time = System.currentTimeMillis();
        List<Map> list=ydService.queryFormData_all(YDParam.builder().formUuid("FORM-29C510B098584EDAA303D7252082D447YGUS").searchFieldJson(
                JSONObject.toJSONString(Arrays.asList(
                        new YDSearch("dateField_meqpbxsj",
                                time,
                                "DateField",
                                YDSearch.Type.DATE_FIELD,
                                YDSearch.Operator.LT),
                        new YDSearch("radioField_meqpbxsi",
                                "否",
                                "RadioField",
                                YDSearch.Type.RADIO_FIELD,
                                YDSearch.Operator.EQ),
                        new YDSearch("selectField_mewmhnwj",
                                "已逾期",
                                "SelectField",
                                YDSearch.Type.RADIO_FIELD,
                                YDSearch.Operator.EQ)
                ))
        ).build());

        if (list == null || list.isEmpty()) {
            log.info("没有找到需要处理的单据");
        }
        log.info("共查询到 {} 条待处理单据", list.size());
        for (Map item : list) {

            String glbdjson = String.valueOf(item.get("associationFormField_me2kiw8j_id"));
            String sqr = String.valueOf(item.get("employeeField_mdya1lol_id"));
            String formInstanceId = String.valueOf(item.get("formInstanceId"));
//            String xsy = String.valueOf(item.get("employeeField_mejnamf3_id"));
            String xszg = String.valueOf(item.get("employeeField_mmsna3tn_id"));
            String zssj = String.valueOf(item.get("employeeField_mmsna3tm_id"));
            String yjlcbh = String.valueOf(item.get("serialNumberField_mdya1lon"));
//            String fhtzd = String.valueOf(item.get("serialNumberField_mheazm7w"));

            // 解析关联字段 JSON
            List<Map> sealjsonlist = parseJsonList(glbdjson);
            HashMap<String, Object> updateMap = new HashMap<>();
            for (Object obj : item.entrySet()) {
                Map.Entry<String, Object> formEntry = (Map.Entry<String, Object>) obj;
                String key = formEntry.getKey();
                Object value = formEntry.getValue();

                // 跳过需要特殊处理的主表关联字段
                if (key.equals("associationFormField_me2kiw8j_id") ||
                        key.equals("employeeField_mdya1lol_id") ||
                        key.equals("employeeField_mmsna3tn_id") ||
                        key.equals("employeeField_mmsna3tm_id") ) {
                    continue;
                }

                // 复制其他字段
                updateMap.put(key, value);
            }

            // 2. 添加需要特殊处理的主表字段
            updateMap.put("associationFormField_me2kiw8j", sealjsonlist);
            updateMap.put("employeeField_mdya1lol", sqr);
            updateMap.put("employeeField_mmsna3tn", xszg);
            updateMap.put("employeeField_mmsna3tm", zssj);
            updateMap.put("textField_mr1e0bpc", yjlcbh);
            // 3. 添加处理后的子表数据
            String sqrid = sqr.substring(2, sqr.length() - 2);
            String xszgid = xszg.substring(2, xszg.length() - 2);
            String finalId = (sqrid == null || sqrid.trim().isEmpty()) ? xszgid : sqrid;
            retryOperateData(
                    YDParam.builder()
                            .formUuid("FORM-54F26858BF574AF0838AEF4086C35FD5VDXJ")
                            .processCode("TPROC--1VF66Z61YYX6RD04NCTOPAF5EFMD2DKJV8UQM2")
                            .formDataJson(JSON.toJSONString(updateMap))
                            .userId(finalId)
                            .build(),
                    YDConf.FORM_OPERATION.start
            );
            Map formData =new HashMap<>();
            formData.put("selectField_mewmhnwj", "已申请逾期扣款");
            retryOperateData(YDParam.builder()
                    .formInstId(formInstanceId)
                    .updateFormDataJson(JSON.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.update);
        }
    }

    @Override
    public McR synckdlrgh() {
        MDC.put("MDC_KEY_PID", "1003");

        String formUuid = "FORM-F79B680547674A6BBD11C0D511E3C14B28FY";
        long now = System.currentTimeMillis();
        long dayMillis = 24L * 60 * 60 * 1000;

        ZoneId zoneId = ZoneId.of("Asia/Shanghai");

        long startTime = LocalDate.now(zoneId).atStartOfDay(zoneId).toInstant().toEpochMilli();
        long endTime = LocalDate.now(zoneId).plusDays(15).atStartOfDay(zoneId).toInstant().toEpochMilli() - 1;

        List<Map> list = null;

        // 查询重试（您已有的逻辑保留）
        for (int attempt = 1; attempt <= 3; attempt++) {
            try {
                list = ydService.queryFormData_all(
                        YDParam.builder()
                                .formUuid(formUuid)
                                .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
                                        new YDSearch("dateField_mjm9k35l", Arrays.asList(startTime, endTime),
                                                "DateField", YDSearch.Type.DATE_FIELD, YDSearch.Operator.BETWEEN),
//                                        // 如果需要过滤 textField_mjm9k35n = "666"，保留；否则删除
//                                        new YDSearch("textField_mjm9k35n", "666",
//                                                "TextField", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ),
                                        new YDSearch("radioField_mru0o7u6", "是",
                                                "RadioField", YDSearch.Type.RADIO_FIELD, YDSearch.Operator.EQ)
                                )))
                                .build()
                );
                break;
            } catch (Exception e) {
                log.warn("查询宜搭数据第 {} 次失败：{}", attempt, e.getMessage(), e);
                if (attempt == 3) return McR.errorParam("查询宜搭数据失败：" + e.getMessage());
                try { Thread.sleep(2000L); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return McR.errorParam("查询被中断"); }
            }
        }

        if (list == null || list.isEmpty()) {
            log.info("没有找到需要处理的单据");
            return McR.success("无待处理数据");
        }

        String accessToken;
        try {
            accessToken = ddClient.getAccessToken();
        } catch (Exception e) {
            log.warn("获取钉钉 accessToken 失败：{}", e.getMessage(), e);
            return McR.errorParam("获取钉钉 accessToken 失败：" + e.getMessage());
        }

        Number agentId = ddConf.getAgentId();
        List<String> releaseIds = new ArrayList<>();

        log.info("共查询到 {} 条待处理单据", list.size());

        for (Map item : list) {
            long releaseTime = UtilMap.getLong(item, "dateField_mjm9k35l");
            if (releaseTime <= 0) {
                log.warn("释放日期为空，跳过：{}", item);
                continue;
            }

            Object idObj = item.get("textField_ms2nby3g");
            if (idObj == null) idObj = item.get("formInstId");
            String formInstanceId = idObj == null ? null : String.valueOf(idObj);
            if (StringUtils.isBlank(formInstanceId) || "null".equals(formInstanceId)) {
                log.warn("formInstanceId 为空，跳过：{}", item);
                continue;
            }

            // 到期释放
            if (releaseTime <= now) {
                releaseIds.add(formInstanceId);
                continue;
            }

            // 提取申请人
            String sqr = null;
            Object sqrObj = item.get("employeeField_mjm9k35m_id");
            if (sqrObj instanceof List) {
                List sqrList = (List) sqrObj;
                if (!sqrList.isEmpty()) sqr = String.valueOf(sqrList.get(0));
            } else if (sqrObj != null) {
                String sqrText = String.valueOf(sqrObj);
                try {
                    JSONArray sqrArray = JSON.parseArray(sqrText);
                    if (sqrArray != null && !sqrArray.isEmpty()) sqr = sqrArray.getString(0);
                } catch (Exception e) {
                    sqr = sqrText;
                }
            }
            if (StringUtils.isBlank(sqr) || "null".equals(sqr)) {
                log.warn("申请人为空，跳过提醒：{}", formInstanceId);
                continue;
            }

            String type = String.valueOf(item.get("selectField_l3nrjuq0"));
            String khmc = String.valueOf(item.get("textField_mjm9k35o"));
            long days = (releaseTime - now + dayMillis - 1) / dayMillis;

            String msg = null;
            if ("未成交".equals(type)) {
                msg = khmc + " 客户近三个月内未成交，还剩 " + days + " 天即将释放到公海";
            } else if ("半年金额不足".equals(type)) {
                msg = khmc + " 客户近半年内成交未达到7.5w，还剩 " + days + " 天即将释放到公海";
            } else if ("一年金额不足".equals(type)) {
                msg = khmc + " 客户近一年内成交未达到15w，还剩 " + days + " 天即将释放到公海";
            }

            if (msg != null) {
                try {
                    sendDdMsg(accessToken, agentId, sqr, msg);
                } catch (Exception e) {
                    log.warn("发送钉钉提醒失败，formInstanceId={}，原因：{}", formInstanceId, e.getMessage());
                }
            }
        }

        // ========== 批量释放（微调：增加批次间隔） ==========
        int totalSuccess = 0;
        if (!releaseIds.isEmpty()) {
            Map<String, Object> formData = new HashMap<>();
            formData.put("employeeField_lqanqe6n", Arrays.asList());
            formData.put("employeeField_lqanqe6o", Arrays.asList());
            formData.put("selectField_megi74y7", "公司分配");
            formData.put("employeeField_megi74yl", Arrays.asList());

            int batchSize = 50;
            int maxRetry = 5;  // 如果3次不够，改成10或20
            int totalBatch = (releaseIds.size() + batchSize - 1) / batchSize;

            for (int i = 0; i < releaseIds.size(); i += batchSize) {
                int end = Math.min(i + batchSize, releaseIds.size());
                List<String> batch = releaseIds.subList(i, end);
                int batchNo = (i / batchSize) + 1;

                for (int attempt = 1; attempt <= maxRetry; attempt++) {
                    try {
                        ydClient.operateData(
                                YDParam.builder()
                                        .formUuid("FORM-68154CC0A7054BF0B1C933752CD3881FB0SR")
                                        .formInstanceIdList(batch)
                                        .useLatestVersion(true)
                                        .updateFormDataJson(JSON.toJSONString(formData))
                                        .build(),
                                YDConf.FORM_OPERATION.multi_update
                        );
                        totalSuccess += batch.size();
                        log.info("释放批次 {}/{} 成功，数量 {}", batchNo, totalBatch, batch.size());
                        break;
                    } catch (Exception e) {
                        log.warn("释放批次 {}/{} 第 {} 次失败：{}", batchNo, totalBatch, attempt, e.getMessage(), e);
                        if (attempt < maxRetry) {
                            try { Thread.sleep(2000L); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return McR.errorParam("批量释放被中断"); }
                        } else {
                            log.error("释放批次 {}/{} 最终失败", batchNo, totalBatch);
                        }
                    }
                }

                // ========== 新增：批次间隔1秒 ==========
                if (i + batchSize < releaseIds.size()) {
                    try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
                }
            }
        }

        log.info("处理完成，查询 {} 条，到期释放 {} 条", list.size(), totalSuccess);
        return McR.success("处理完成，查询 " + list.size() + " 条，到期释放 " + totalSuccess + " 条");
    }

    @Override
    public McR synckdndrq() {
        MDC.put("MDC_KEY_PID", "1003");
        //当前时间戳
        long endTime = System.currentTimeMillis();
        long ndTime = endTime + 365L * 24 * 60 * 60 * 1000;
        long lcTime = endTime + 90L * 24 * 60 * 60 * 1000;
//        long startTime = endTime - 14L * 24 * 60 * 60 * 1000;
        List<Map> list = ydService.queryFormData_all(
                YDParam.builder()
                        .formUuid("FORM-F79B680547674A6BBD11C0D511E3C14B28FY")
                        .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
                                new YDSearch(
                                        "dateField_mjz31qkm",
                                        endTime,
                                        "DateField",
                                        YDSearch.Type.DATE_FIELD,
                                        YDSearch.Operator.LE
                                )
//                                new YDSearch(
//                                        "radioField_mru0o7u6",
//                                        "是",
//                                        "RadioField",
//                                        YDSearch.Type.RADIO_FIELD,
//                                        YDSearch.Operator.EQ
//                                )
                        )))
                        .build()
        );
        log.info("查询结果:{}", list);

        List<String> allIds = list.stream()
                .map(item -> String.valueOf(item.get("formInstanceId")))
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());

        Map<String, Object> upData = new HashMap<>();
        upData.put("dateField_mjm9k35j", endTime);
        upData.put("dateField_mjqkkcsg", endTime);
        upData.put("numberField_mjm9k35k", 0);
        upData.put("selectField_l3nrjuq0", "未成交");
        upData.put("dateField_mjz31qkm", ndTime);
        upData.put("dateField_mjm9k35l", lcTime);

        int batchSize = 50;
        int totalSuccess = 0;

        for (int i = 0; i < allIds.size(); i += batchSize) {
            int end = Math.min(i + batchSize, allIds.size());
            List<String> batch = allIds.subList(i, end);

            for (int attempt = 1; attempt <= 30; attempt++) {
                try {
                    ydClient.operateData(YDParam.builder()
                            .formInstanceIdList(batch)
                            .formUuid("FORM-F79B680547674A6BBD11C0D511E3C14B28FY")
                            .useLatestVersion(true)
                            .updateFormDataJson(JSON.toJSONString(upData))
                            .build(), YDConf.FORM_OPERATION.multi_update);

                    totalSuccess += batch.size();
                    log.info("批次 {}/{} 成功", (i / batchSize) + 1, (allIds.size() + batchSize - 1) / batchSize);
                    break;

                } catch (Exception e) {
                    log.warn("批次 {}/{} 第 {} 次失败", (i / batchSize) + 1, attempt, e.getMessage());
                    if (attempt < 2000) {
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException ie) {
                            Thread.currentThread().interrupt();
                        }
                    }
                }
            }
        }

        return McR.success("处理完成，成功 " + totalSuccess + "/" + allIds.size() + " 条");
    }

    private Object retryOperateData(YDParam param, YDConf.FORM_OPERATION formOperation) {
        int maxAttempts = 3; // 尝试的最大次数
        int attempt = 0;
        long baseWaitTime = 3000; // 基础等待时间3秒

        while (attempt < maxAttempts) {
            try {
                Object result = ydClient.operateData(param, formOperation);
                // 成功调用后，如果有之前失败的重试日志，记录成功
                if (attempt > 0) {
                    log.info("第{}次重试成功", attempt + 1);
                }
                return result;
            } catch (McException e) {
                String errorMsg = e.getMessage();
                log.warn("第{}次调用失败，错误信息：{}", attempt + 1, errorMsg);

                // 判断是否是可重试的异常
                if (isRetryableError(errorMsg)) {
                    attempt++;
                    // 如果已达到最大尝试次数，不再重试，直接抛出异常
                    if (attempt >= maxAttempts) {
                        log.error("已达最大重试次数{}次，放弃重试", maxAttempts);
                        throw new RuntimeException("超出最大重试次数, param:" + JSONObject.toJSONString(param) + ", FORM_OPERATION:" + formOperation, e);
                    }

                    // 线程睡眠，使用指数退避策略
                    try {
                        long waitTime = baseWaitTime * (long) Math.pow(2, attempt - 1);
                        log.info("等待{}ms后重试第{}次, param:{}, FORM_OPERATION:{}",
                                waitTime, attempt + 1, JSONObject.toJSONString(param), formOperation);
                        Thread.sleep(waitTime);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt(); // 重新设置中断状态
                        log.error("重试睡眠被中断", ie);
                        throw new RuntimeException("重试过程被中断", ie);
                    }
                } else {
                    // 不可重试的异常，直接抛出
                    log.error("发生不可重试的异常，直接失败: {}", errorMsg);
                    throw new RuntimeException("宜搭操作失败: " + errorMsg, e);
                }
            } catch (Exception e) {
                // 非McException异常，直接抛出，不重试
                log.error("操作失败,param:{},FORM_OPERATION:{},异常信息:{}",
                        JSONObject.toJSONString(param), formOperation, e.getMessage());
                throw new RuntimeException(e);
            }
        }

        // 理论上不会执行到这里，但为了安全保留
        throw new RuntimeException("超出最大重试次数, param:" + JSONObject.toJSONString(param) + ", FORM_OPERATION:" + formOperation);
    }

    //自带重试的queryData方法
    private DDR_New retryQueryData(YDParam param, YDConf.FORM_QUERY formQuery) {
        int maxAttempts = 3; // 尝试的最大次数
        int attempt = 0;
        long baseWaitTime = 3000; // 基础等待时间3秒

        while (attempt < maxAttempts) {
            try {
                DDR_New result = ydClient.queryData(param, formQuery);
                // 成功调用后，如果有之前失败的重试日志，记录成功
                if (attempt > 0) {
                    log.info("第{}次重试查询成功", attempt + 1);
                }
                return result;
            } catch (McException e) {
                String errorMsg = e.getMessage();
                log.warn("第{}次查询失败，错误信息：{}", attempt + 1, errorMsg);

                // 判断是否是可重试的异常
                if (isRetryableError(errorMsg)) {
                    attempt++;
                    // 如果已达到最大尝试次数，不再重试，直接抛出异常
                    if (attempt >= maxAttempts) {
                        log.error("已达最大重试次数{}次，放弃重试查询", maxAttempts);
                        throw new RuntimeException("超出最大重试次数, param:" + JSONObject.toJSONString(param) + ", FORM_QUERY:" + formQuery, e);
                    }

                    // 线程睡眠，使用指数退避策略
                    try {
                        long waitTime = baseWaitTime * (long) Math.pow(2, attempt - 1);
                        log.info("等待{}ms后重试第{}次查询, param:{}, FORM_QUERY:{}",
                                waitTime, attempt + 1, JSONObject.toJSONString(param), formQuery);
                        Thread.sleep(waitTime);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt(); // 重新设置中断状态
                        log.error("重试查询睡眠被中断", ie);
                        throw new RuntimeException("重试查询过程被中断", ie);
                    }
                } else {
                    // 不可重试的异常，直接抛出
                    log.error("发生不可重试的异常，查询直接失败: {}", errorMsg);
                    throw new RuntimeException("宜搭查询失败: " + errorMsg, e);
                }
            } catch (Exception e) {
                // 非McException异常，直接抛出，不重试
                log.error("查询操作失败,param:{},FORM_QUERY:{},异常信息:{}",
                        JSONObject.toJSONString(param), formQuery, e.getMessage());
                throw new RuntimeException(e);
            }
        }

        // 理论上不会执行到这里，但为了安全保留
        throw new RuntimeException("超出最大重试次数, param:" + JSONObject.toJSONString(param) + ", FORM_QUERY:" + formQuery);
    }
    /**
     * 判断是否是可重试的错误
     */
    private boolean isRetryableError(String errorMsg) {
        if (errorMsg == null) return false;

        // 可重试的错误关键字列表（扩展了匹配范围）
        String[] retryableKeywords = {
                "temporary failure",
                "未知异常",
                "timeout",
                "Timeout",
                "Connection refused",
                "Internal Server",
                "服务不可用",
                "Service Unavailable",
                "Gateway Timeout",
                "Bad Gateway"
        };

        for (String keyword : retryableKeywords) {
            if (errorMsg.contains(keyword)) {
                return true;
            }
        }
        return false;
    }
    private List<Map> parseJsonList(String jsonStr) {
        if (jsonStr == null || "null".equals(jsonStr) || jsonStr.isEmpty()) {
            return Collections.emptyList();
        }
        try {
            // 宜搭有时返回的是 "\"[{...}]\""，需先 unescape
            String clean = StringEscapeUtils.unescapeJava(jsonStr);
            // 如果首尾是双引号，去掉
            if (clean.startsWith("\"") && clean.endsWith("\"")) {
                clean = clean.substring(1, clean.length() - 1);
            }
            return (List<Map>) JSONArray.parse(clean);
        } catch (Exception e) {

            return Collections.emptyList();
        }
    }
    private static String safeToString(Object obj) {
        return obj == null ? null : obj.toString();
    }

    private Object getddAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-B62CAE3075CE4098B17BB86C90FFA21C9B7C", "receipt", id, title, "");
    }

    private Object getfhdAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-A7F03ACEE01D4F609550C86BF7FE87D35M6I", "receipt", id, title, "");
    }

    private Object getysdAss(String title, String id) {
        return UtilMap.map("appType, formUuid, formType, instanceId, title, subTitle", "APP_VQDMMWS6OR1VHL8VMFD3", "FORM-AADBCDA8126F41A0ADDEE3353828583192M8", "receipt", id, title, "");
    }
    public void sendDdMsg(String access_token, Number agent_id, String userid_list, String content) {
        if (Objects.nonNull(userid_list)) {
            Map param2 = new HashMap();
            param2.put("access_token", access_token);
            Map body3 = new HashMap();
            body3.put("agent_id", agent_id);
            body3.put("userid_list", userid_list);
            Map msg = new HashMap();
            msg.put("msgtype", "text");
            //获取当前时间 精确到秒
            String time = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            msg.put("text", UtilMap.map("content, aa", content, ""));
            body3.put("msg", msg);
            UtilHttp.doPost("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2", null, param2, body3);
        }
    }
}