package com.malk.huagao.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.malk.huagao.entity.KdYdCustomer;
import com.malk.huagao.entity.KdYdMaterial;
import com.malk.huagao.mapper.KdYdMaterialMapper;
import com.malk.huagao.service.IKdYdMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-10-16
 */
@Service
@Slf4j
public class KdYdMaterialServiceImpl extends ServiceImpl<KdYdMaterialMapper, KdYdMaterial> implements IKdYdMaterialService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdMaterialMapper kdYdMaterialMapper;
    @Value(value = "${kd.host}")
    private String kdHost;
    @Override
    public void insertkdYdMaterial(Map map) {
        MDC.put("MDC_KEY_PID", "1003");
        String formInstId = UtilMap.getString(map, "formInstId");
        DDR_New ddrNew = retryQueryData(YDParam.builder()
                .formInstId(formInstId)
                .build(), YDConf.FORM_QUERY.retrieve_id);
        Map formData = ddrNew.getFormData();
        System.out.println(formData);
        String wlmc = UtilMap.getString(formData, "textField_l43jpnsf");
        String xh = UtilMap.getString(formData, "textField_l43jpnsg");
        String gg = UtilMap.getString(formData, "textField_lqbxkzbq");
        String wlfz = UtilMap.getString(formData, "selectField_mguazu3k");
        String wlsx = UtilMap.getString(formData, "textField_l43jpnsh");
        String xsy = UtilMap.getString(formData, "employeeField_mgu5vocz").replace("[\"", "").replace("\"]", "").trim();
        String ssxl = UtilMap.getString(formData, "textField_mfxbtcdp");
        String jx = UtilMap.getString(formData, "textField_mejl9nrs");
        int sd = parseInt(safeGetString(formData, "numberField_mfxbtceb"), 0);
        String mrsl = UtilMap.getString(formData, "textField_mfxbtcdq");
        String chlb = UtilMap.getString(formData, "textField_mfxbtcdr");
        String jbdw = UtilMap.getString(formData, "textField_mfxbtcdo");
        BigDecimal xsjzj = toBigDecimal(safeGetString(formData, "numberField_mejl9nsc"));
        String smzs = UtilMap.getString(formData, "textField_mfxbtce4");
        String sjzt = UtilMap.getString(formData, "textField_mfxbtce6");
        String jyzt = UtilMap.getString(formData, "textField_mfxbtcea");
        String dzl = UtilMap.getString(formData, "textField_mfxbtcea");
        String pzzt = UtilMap.getString(formData, "selectField_mejl9nrq");
        String wlbt = wlmc+"-"+xh;
//        String sdmc = ssxl+"-"+pzzt+"-"+safeGetString(formData, "numberField_mfxbtceb");

        KdYdMaterial kdYdMaterial = new KdYdMaterial();
        kdYdMaterial.setWlmc(wlmc);
        kdYdMaterial.setXh(xh);
        kdYdMaterial.setGg(gg);
        kdYdMaterial.setWlfz(wlfz);
        kdYdMaterial.setWlsx(wlsx);
        kdYdMaterial.setJbdw(jbdw);
        kdYdMaterial.setSsxl(ssxl);
        kdYdMaterial.setJx(jx);
        kdYdMaterial.setSd(sd);
        kdYdMaterial.setMrsl(mrsl);
        kdYdMaterial.setChlb(chlb);
        kdYdMaterial.setXsy(xsy);
        kdYdMaterial.setXsjzj(xsjzj);
        kdYdMaterial.setSmzs(smzs);
        kdYdMaterial.setSjzt(sjzt);
        kdYdMaterial.setJyzt(jyzt);
        kdYdMaterial.setDzl(dzl);
        kdYdMaterial.setPzzt(pzzt);
        kdYdMaterial.setMaterialtitle(wlbt);
//        kdYdMaterial.setSpeedname(sdmc);
        kdYdMaterial.setForminstid(formInstId);
        kdYdMaterialMapper.insert(kdYdMaterial);

       
    }

    @Override
    public Map<String, Object> addkdYdMaterial(Map json) {
        Map<String, Object> result = new HashMap<>();

        try {
            MDC.put("MDC_KEY_PID", "1003");

            // 查询需要删除的数据
            List<Map<String, Object>> kdYdMaterialdels = UtilMap.getList(json ,"data");
            String action = json.get("action").toString();
            String table = json.get("table").toString();

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

                for (Map item : kdYdMaterialdels) {
                    try {
                        // 修复：使用安全的方式转换FMATERIALID
                        Object fmaterialidObj = item.get("FMATERIALID");
                        String fmaterialidStr = String.valueOf(fmaterialidObj);

                        List<Map> list1 = (List<Map>) retryQueryData(YDParam.builder()
                                .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                                .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                                .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                                .searchFieldJson(JSONObject.toJSONString(UtilMap.map("textField_misfb2ft", fmaterialidStr)))
                                .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.info("找到待删除的表单实例: formInstanceId={}", formInstanceId);
                                }
                            }
                        } else {
                            log.info("未找到对应的物料数据: fmaterialid={}", fmaterialidStr);
                        }

                    } catch (Exception e) {
                        log.info("删除物料数据查询异常: FMATERIALID={}", item.get("FMATERIALID"), e);
                    }
                }

                // 执行批量删除
                if (!list.isEmpty()) {
                    try {
                        Object deleteResult = retryOperateData(YDParam.builder()
                                .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                                .formInstanceIdList(list)
                                .build(), YDConf.FORM_OPERATION.delete_batch);
                        // 返回删除结果
                        result.put("code", "200");
                        result.put("msg", "删除成功，共删除" + list.size() + "条数据");
                        result.put("data", new HashMap<String, Object>() {{
                            put("deleteResult", "删除成功");
                            put("deletedCount", list.size());
                            put("deletedIds", list);
                        }});
                        return result;

                    } catch (Exception e) {
                        log.error("批量删除操作异常", e);
                        result.put("code", "500");
                        result.put("msg", "批量删除操作异常：" + e.getMessage());
                        result.put("data", new HashMap<>());
                        return result;
                    }
                } else {
                    result.put("code", "200");
                    result.put("msg", "未找到需要删除的数据");
                    result.put("data", new HashMap<>());
                    return result;
                }
            }

            List<Map<String, Object>> kdYdMaterials = UtilMap.getList(json ,"data");
            // 同步新增/更新数据
            if (kdYdMaterials.isEmpty()) {
                log.info("【物料单同步任务】无需要同步的数据，结束");
                result.put("code", "200");
                result.put("msg", "无需要同步的数据");
                result.put("data", new HashMap<>());
                return result;
            }

            // 存储所有操作的结果
            List<Map<String, Object>> operationResults = new ArrayList<>();
            int successCount = 0;
            int failCount = 0;

            for (Map kdYdMaterial : kdYdMaterials) {
                Map<String, Object> singleResult = new HashMap<>();

                try {
                    // 修复：安全地获取所有字段值
                    String wlbm = safeGetStringValue(kdYdMaterial, "wlbm");
                    String wlmc = safeGetStringValue(kdYdMaterial, "wlmc");
                    String xh = safeGetStringValue(kdYdMaterial, "xh");
                    String gg = safeGetStringValue(kdYdMaterial, "gg");
                    String kssj = safeGetStringValue(kdYdMaterial, "kssj");
                    String jzsj = safeGetStringValue(kdYdMaterial, "jzsj");

                    // 修复：安全处理FMATERIALID，可能为字符串或数字
                    Object fmaterialidObj = kdYdMaterial.get("FMATERIALID");
                    String fmaterialidStr = String.valueOf(fmaterialidObj);

                    String wlfz = safeGetStringValue(kdYdMaterial, "wlfz");
                    String wlsx = safeGetStringValue(kdYdMaterial, "wlsx");
                    String jbdw = safeGetStringValue(kdYdMaterial, "jbdw");
                    String ssxl = safeGetStringValue(kdYdMaterial, "ssxl");
                    String jx = safeGetStringValue(kdYdMaterial, "jx");
                    String sku = safeGetStringValue(kdYdMaterial, "sku");

                    // 修复：安全处理sd字段
                    Object sdObj = kdYdMaterial.get("sd");
                    Integer sd = null;
                    if (sdObj != null) {
                        try {
                            if (sdObj instanceof Integer) {
                                sd = (Integer) sdObj;
                            } else if (sdObj instanceof String) {
                                sd = Integer.parseInt((String) sdObj);
                            } else if (sdObj instanceof Number) {
                                sd = ((Number) sdObj).intValue();
                            }
                        } catch (Exception e) {
                            log.warn("无法解析sd字段: {}", sdObj);
                        }
                    }

                    String mrsl = safeGetStringValue(kdYdMaterial, "mrsl");
                    String chlb = safeGetStringValue(kdYdMaterial, "chlb");
                    String xsy = safeGetStringValue(kdYdMaterial, "xsy");

                    // 修复：安全处理xsjzj字段
                    Object xsjzjObj = kdYdMaterial.get("xsjzj");
                    BigDecimal xsjzj = null;
                    if (xsjzjObj != null) {
                        try {
                            if (xsjzjObj instanceof BigDecimal) {
                                xsjzj = (BigDecimal) xsjzjObj;
                            } else if (xsjzjObj instanceof String) {
                                xsjzj = new BigDecimal((String) xsjzjObj);
                            } else if (xsjzjObj instanceof Number) {
                                xsjzj = new BigDecimal(xsjzjObj.toString());
                            }
                        } catch (Exception e) {
                            log.warn("无法解析xsjzj字段: {}", xsjzjObj);
                        }
                    }

                    String smzs = safeGetStringValue(kdYdMaterial, "smzs");
                    String sjzt = safeGetStringValue(kdYdMaterial, "sjzt");
                    String jyzt = safeGetStringValue(kdYdMaterial, "jyzt");
                    String dzl = safeGetStringValue(kdYdMaterial, "dzl");
                    String wlzl = safeGetStringValue(kdYdMaterial, "wlzl");
                    String pzzt = safeGetStringValue(kdYdMaterial, "pzzt");
                    String sdbb = safeGetStringValue(kdYdMaterial, "sdbb");
                    String wlbt = wlmc + wlbm;

                    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", fmaterialidStr); // 使用字符串类型
                    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("dateField_ml4ikfa0", kssj);
                    updateFormData.put("dateField_ml4ikfa1", jzsj);
                    updateFormData.put("textField_mfxbtce6", sjzt);
                    updateFormData.put("textField_mqg2328v", sku);

                    if (sd != null) {
                        updateFormData.put("numberField_mfxbtceb", sd);
                    } else {
                        updateFormData.put("numberField_mfxbtceb", 0);
                    }

                    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);

                    // 确保金额字段保留两位小数
                    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);

                    // 执行操作并获取结果
                    Object operationResult = retryOperateData(YDParam.builder()
                            .formUuid("FORM-E64114E9F2C9426E91F92886EDFFA2C08Q90")
                            .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                            .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                            .searchCondition(JSONObject.toJSONString(Arrays.asList(new YDSearch(
                                    "textField_misfb2ft", fmaterialidStr, "金蝶内码", YDSearch.Type.TEXT_FIELD, YDSearch.Operator.EQ))))
                            .formDataJson(JSONObject.toJSONString(updateFormData))
                            .build(), YDConf.FORM_OPERATION.upsert);

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

                    // 记录单个操作结果
                    singleResult.put("FMATERIALID", fmaterialidStr);
                    singleResult.put("operationResult", operationResult);
                    singleResult.put("status", "success");
                    successCount++;

                } catch (Exception e) {
                    log.error("物料单同步失败", e);

                    // 修复：安全获取FMATERIALID
                    Object fmaterialidObj = kdYdMaterial.get("FMATERIALID");
                    String fmaterialidStr = fmaterialidObj != null ? String.valueOf(fmaterialidObj) : "unknown";

                    singleResult.put("FMATERIALID", fmaterialidStr);
                    singleResult.put("errorMsg", e.getMessage());
                    singleResult.put("status", "fail");
                    failCount++;
                }

                operationResults.add(singleResult);
            }

            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("operationResults", operationResults);
            data.put("totalCount", kdYdMaterials.size());
            data.put("successCount", successCount);
            data.put("failCount", failCount);

            result.put("code", failCount == 0 ? "200" : "300");
            result.put("msg", "操作完成，成功" + successCount + "条，失败" + failCount + "条");
            result.put("data", data);

            return result;

        } catch (Exception e) {
            log.error("物料单同步任务执行异常", e);
            result.put("code", "500");
            result.put("msg", "系统异常：" + e.getMessage());
            result.put("data", new HashMap<>());
            return result;
        }
    }

    @Override
    public Map<String, Object> updatekdYdMaterial(Map map) {
        MDC.put("MDC_KEY_PID", "1003");
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 参数提取
            String jdnm = UtilMap.getString(map, "jdnm");
            String xsy = UtilMap.getString(map, "xsy");
            String kssj = UtilMap.getString(map, "kssj");
            String jssj = UtilMap.getString(map, "jssj");

            // 2. 时间戳转年月日格式
            String kssjFormatted = formatTimestamp(kssj);
            String jssjFormatted = formatTimestamp(jssj);

            // 3. 参数非空校验
            if (isAnyBlank(jdnm, xsy, kssj, jssj)) {
                result.put("code", 400);
                result.put("message", "参数不能为空：jdnm、xsy、kssj、jssj 均为必填");
                return result;
            }

            // 4. 参数 URL 编码（防止中文/特殊字符乱码）
            String encodedJdnm = URLEncoder.encode(jdnm, "UTF-8");
            String encodedXsy = URLEncoder.encode(xsy, "UTF-8");
            String encodedKssj = URLEncoder.encode(kssjFormatted, "UTF-8");
            String encodedJssj = URLEncoder.encode(jssjFormatted, "UTF-8");
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            // 5. 构建完整 URL（参数用 & 连接）
            String url = kdHost + "/xk/dyzn/WsBasedyzn.asmx/Hggxwlxx?" +
                    "FMATERIALID=" + encodedJdnm +
                    "&F_HGSALE=" + encodedXsy +
                    "&FSSXSYKSRQ=" + encodedKssj +
                    "&F_HGSALEENDDATE=" + encodedJssj;
            log.info("物料请求URL: {}", url);
            // 6. 发送 GET 请求
            HttpResponse response = HttpRequest.get(url)
                    .timeout(30000)
                    .execute();
            System.out.println("response"+response);
            // 7. 处理响应
            String responseBody = response.body();
            System.out.println("responseBody"+responseBody);
            int statusCode = response.getStatus();

            log.info("更新扣点物料响应状态: {}, 响应内容: {}", statusCode, responseBody);


            return result;

        } catch (UnsupportedEncodingException e) {
            result.put("code", 500);
            result.put("message", "参数编码异常：" + e.getMessage());
            return result;
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "系统异常：" + e.getMessage());
            return result;
        } finally {
            MDC.remove("MDC_KEY_PID");
        }
    }
    // 格式化方法
    private String formatTimestamp(String timestamp) {
        if (timestamp == null || timestamp.isEmpty()) {
            return "";
        }
        try {
            long time = Long.parseLong(timestamp);
            // 判断是秒级（10位）还是毫秒级（13位）
            if (timestamp.length() == 10) {
                time = time * 1000; // 秒级转毫秒级
            }
            Date date = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(date);
        } catch (NumberFormatException e) {
            log.error("时间戳格式错误: {}", timestamp, e);
            return timestamp; // 转换失败返回原值
        }
    }
    /**
     * 判断是否有任意参数为空
     */
    private boolean isAnyBlank(String... strs) {
        for (String str : strs) {
            if (str == null || str.trim().isEmpty()) {
                return true;
            }
        }
        return false;
    }
    // 辅助方法：安全获取字符串值
    private String safeGetStringValue(Map map, String key) {
        if (map == null) return "";
        Object value = map.get(key);
        if (value == null) return "";
        return String.valueOf(value);
    }

    private static int parseInt(String str, int defaultValue) {
        if (str == null || str.trim().isEmpty()) {
            return defaultValue;
        }
        try {
            return Integer.parseInt(str.trim());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }
    private String safeGetString(Map formData, String key) {
        Object val = formData.get(key);
        return val == null ? "" : String.valueOf(val);
    }
    public static BigDecimal toBigDecimal(String str) {
        if (str == null || str.trim().isEmpty()) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        try {
            return new BigDecimal(str.trim())
                    .setScale(2, RoundingMode.HALF_UP);
        } catch (NumberFormatException e) {
            // 返回默认值而不是抛出异常，避免程序中断
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
    }

    /**
     * 重载方法，支持Number类型输入
     */
    public static BigDecimal toBigDecimal(Number number) {
        if (number == null) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        return new BigDecimal(number.toString())
                .setScale(2, RoundingMode.HALF_UP);
    }
    //自带重试的operateData方法
    //自带重试的operateData方法
    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;
    }
}
