package com.malk.huagao.service.impl;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
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.KdYdOrderDetailMapper;
import com.malk.huagao.mapper.KdYdOrderMapper;
import com.malk.huagao.mapper.KdYdOrderPaymentMapper;
import com.malk.huagao.service.IKdYdOrderService;
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.common.McR;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.aliwork.YDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LQY
 * @since 2025-10-15
 */
@Service
@Slf4j
public class KdYdOrderServiceImpl extends ServiceImpl<KdYdOrderMapper, KdYdOrder> implements IKdYdOrderService {
    @Autowired
    private YDClient ydClient;
    @Autowired
    private KdYdOrderMapper kdYdOrderMapper;
    @Autowired
    private KdYdOrderDetailMapper kdYdOrderDetailMapper;
    @Autowired
    private KdYdOrderPaymentMapper kdYdOrderPaymentMapper;
    @Value(value = "${kd.host}")
    private String kdHost;

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

        try {
            MDC.put("MDC_KEY_PID", "1003");
            String formInstId = UtilMap.getString(map, "formInstId");
            String type = UtilMap.getString(map, "type");

            // 处理特殊操作类型
            if ("del".equals(type)) {
                String bm = UtilMap.getString(map, "bm");
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                Map<String, Object> formParams = new HashMap<>();
                Map<String, Object> djbh = new HashMap<>();
                djbh.put("djbh", bm);
                result.put("data", djbh);
                String jsonStr = JSON.toJSONString(result);

                formParams.put("jsons", jsonStr);

                System.out.println("====" + formParams);
                HttpResponse response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/hgdjydtbdeletexsdd")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();

                String responseBody = response.body();
                // 返回删除操作的格式
                result.put("table", "KD_YD_ORDER");
                result.put("action", "del");
                result.put("data", new HashMap<String, Object>() {{
                    put("bm", bm);  // 删除的主键或标识
                    put("msg", "删除成功");
                }});
                return result;
            }

            if ("cancel".equals(type)) {
                String bm = UtilMap.getString(map, "bm");
                Map<String, String> headers = new HashMap<>();
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                Map<String, Object> formParams = new HashMap<>();
                Map<String, Object> djbh = new HashMap<>();
                djbh.put("djbh", bm);
                result.put("data", djbh);
                String jsonStr = JSON.toJSONString(result);
                System.out.println("==" + jsonStr);
                formParams.put("jsons", jsonStr);
                HttpResponse response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/hgdjydtbExcuteOperationxsdd")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();

                String responseBody = response.body();
                String msg = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getString("msg");
                String code = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getString("code");
                ydClient.operateData(
                        YDParam.builder()
                                .formInstanceId(formInstId)
                                .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_ml08nk3y, textareaField_mkxqgrvq", code, msg)))
                                .useLatestVersion(true).build(),
                        YDConf.FORM_OPERATION.update);
                // 返回作废操作的格式
                result.put("table", "KD_YD_ORDER");
                result.put("action", "cancel"); // 作废通常是修改状态
                result.put("data", new HashMap<String, Object>() {{
                    put("bm", bm); // 作废状态
                    put("msg", "作废成功");
                    // 其他作废需要的数据
                }});
                return result;
            }

            // 查询表单数据
            DDR_New ddrNew = retryQueryData(YDParam.builder()
                    .formInstId(formInstId)
                    .build(), YDConf.FORM_QUERY.retrieve_id);
            Map formData = ddrNew.getFormData();

            // 提取主表字段
            String djlx = UtilMap.getString(formData, "selectField_mejowmna");
            String khmc = UtilMap.getString(formData, "textField_mejnamf2");
//            String khmc = "五岳";
//            String djbh = UtilMap.getString(formData, "textField_mjs6fuwo");

            // 判断操作类型对应的action
            String actionType;
            String djbh = null;
            if ("edit".equals(type)) {
//                djbh = UtilMap.getString(formData, "textField_mjs6fuwo");
//                djbh = UtilMap.getString(formData, "textField_miwvnkep");
                 djbh = StringUtils.isNotBlank(UtilMap.getString(formData, "textField_mjs6fuwo"))
                        ? UtilMap.getString(formData, "textField_mjs6fuwo")
                        : UtilMap.getString(formData, "textField_miwvnkep");
                actionType = "edit";
            } else {
                actionType = "add";
                djbh = "";
            }

            // 提取其他字段...
            LocalDateTime rq = parseTimestamp(UtilMap.getString(formData, "dateField_mejowmnb"));
            String khxypj = UtilMap.getString(formData, "selectField_mewirdx4");
            String ywlx = UtilMap.getString(formData, "textField_mfxv2vfz");
            String xsy = UtilMap.getString(formData, "employeeField_mejowmng").replace("[\"", "").replace("\"]", "").trim();
            String xslx = UtilMap.getString(formData, "selectField_mejowmnc");
            String bzq = UtilMap.getString(formData, "selectField_mf6gyfkq");
            String xsbm = UtilMap.getString(formData, "departmentSelectField_mfxv2vfu").replace("[\"", "").replace("\"]", "").trim();
            String bz = UtilMap.getString(formData, "textareaField_mejnamfb");
            String jsbb = UtilMap.getString(formData, "selectField_mejowmnk");
            String sktj = UtilMap.getString(formData, "selectField_mgisux07");
            String zdzkestr = UtilMap.getString(formData, "numberField_mejowmni");
            BigDecimal zdzke = toBigDecimal(zdzkestr);
            String sestr = UtilMap.getString(formData, "numberField_mfxv2vgh");
            BigDecimal se = toBigDecimal(sestr);
            String jestr = UtilMap.getString(formData, "numberField_mfxv2vgj");
            BigDecimal je = toBigDecimal(jestr);
            String jshjstr = UtilMap.getString(formData, "numberField_mewfgzkv");
            BigDecimal jshj = toBigDecimal(jshjstr);
            String sfhs = UtilMap.getString(formData, "radioField_mfxv2vg4");
            String ckddh = UtilMap.getString(formData, "textField_mqg2b2g5");
            String jws = UtilMap.getString(formData, "radioField_mfxv2vgm");
            List<Map> tableField = (List<Map>) formData.get("tableField_mfbx1pqi");
            List<Map> tableFieldPayment = (List<Map>) formData.get("tableField_mhiui6v5");

            // 处理订单明细
            List<Map<String, Object>> orderList = new ArrayList<>();
            if (tableField != null) {
                for (int i = 0; i < tableField.size(); i++) {
                    Map item = tableField.get(i);
                    Map<String, Object> table1Map = new HashMap<>();

                    int detailId = parseInt(safeGetString(item, "numberField_mjzfodew"), 1);
                    String wlbm = safeGetString(item, "textField_mfbx1pqt");
//                    String wlbm = "010101010003";
                    String wlmc = safeGetString(item, "textField_mfbx1pqs");
//                    String kzfh = safeGetString1(item, "radioField_mqyje8pg");
                    String sku = safeGetString(item, "textField_mqg2b2g6");
                    String tcfpfs = safeGetString(item, "textField_mpqmsz2q");
                    String yjfpfs = safeGetString(item, "textField_mpqmsz2r");
                    String fpxsy = safeGetString(item, "textField_mpqmsz2s");
                    String ggxh = safeGetString(item, "textField_mfbx1pqr");
                    String xsdw = safeGetString(item, "textField_mfbx1pqq");
                    int xssl = parseInt(safeGetString(item, "numberField_mfbx1pr4"), 0);
                    String ssxl = safeGetString(item, "selectField_mfbx1pr1");
                    BigDecimal dj = toBigDecimal(safeGetString(item, "numberField_mfbx1prf"));
                    BigDecimal cxzkje = toBigDecimal(safeGetString(item, "numberField_mk56soin"));
                    BigDecimal hsdj = toBigDecimal(safeGetString(item, "numberField_mfbx1prg"));
                    String sfzp = safeGetString(item, "radioField_mfbx1prc");
                    String bz1 = safeGetString(item, "textareaField_mjryuaok");
                    int sl = parseInt(safeGetString(item, "numberField_mfbx1prb"), 0);
                    BigDecimal zse = toBigDecimal(safeGetString(item, "numberField_mfbx1prh"));
                    BigDecimal bbh = toBigDecimal1(safeGetString(item, "numberField_mowq936x"));
                    BigDecimal zje = toBigDecimal(safeGetString(item, "numberField_mfbx1pri"));
                    BigDecimal zjshj = toBigDecimal(safeGetString(item, "numberField_mfbx1prj"));
                    BigDecimal jj = toBigDecimal(safeGetString(item, "numberField_mfbx1prk"));
                    BigDecimal zkl = toBigDecimal(safeGetString(item, "numberField_mfbx1pru"));
                    BigDecimal zke = toBigDecimal(safeGetString(item, "numberField_mfbx1prt"));
                    LocalDateTime yhrq = parseTimestamp(UtilMap.getString(item, "dateField_mfbx1prs"));
                    BigDecimal xsjzj = toBigDecimal(safeGetString(item, "numberField_mfbx1pr0"));
                    String zmzs = safeGetString(item, "textField_mfxv2vgv");

                    // 设置明细字段
                    table1Map.put("detailId", detailId);
                    table1Map.put("wlbm", wlbm);
                    table1Map.put("sku", sku);
//                    table1Map.put("kzfh", kzfh);
                    table1Map.put("wlmc", wlmc);
                    table1Map.put("ggxh", ggxh);
                    table1Map.put("xsdw", xsdw);
                    table1Map.put("xssl", xssl);
                    table1Map.put("ssxl", ssxl);
                    table1Map.put("dj", dj);
                    table1Map.put("cxzkje", cxzkje);
                    table1Map.put("hsdj", hsdj);
                    table1Map.put("sfzp", sfzp);
                    table1Map.put("bz", bz1);
                    table1Map.put("sl", sl);
                    table1Map.put("tcfpfs", tcfpfs);
                    table1Map.put("yjfpfs", yjfpfs);
                    table1Map.put("fpxsy", fpxsy);
                    table1Map.put("se1", zse);
                    table1Map.put("bbh", bbh);
                    table1Map.put("je1", zje);
                    table1Map.put("jshj1", zjshj);
                    table1Map.put("jj", jj);
                    table1Map.put("zkl", zkl);
                    table1Map.put("zke", zke);
                    table1Map.put("xsjzj", xsjzj);
                    table1Map.put("zmzs", zmzs);
                    table1Map.put("yhrq", yhrq);

                    orderList.add(table1Map);
                }
            }

            // 处理付款明细
            List<Map<String, Object>> OrderPayList = new ArrayList<>();
            if (tableFieldPayment != null) {
                for (int i = 0; i < tableFieldPayment.size(); i++) {
                    Map row = tableFieldPayment.get(i);
                    Map<String, Object> table2Map = new HashMap<>();
                    int detailId = i + 1;

                    String sfys = safeGetString(row, "radioField_mhiui6v7");
//                    String sjyskzfh = safeGetString(row, "radioField_ml7hg2oi");
                    String gldh = safeGetString(row, "textField_mhiui6va");
                    BigDecimal ysbl = toBigDecimal(UtilMap.getString(row, "numberField_mhiui6v6"));
                    BigDecimal ysje = toBigDecimal(UtilMap.getString(row, "numberField_mhiui6v8"));
                    BigDecimal ssje = toBigDecimal(UtilMap.getString(row, "numberField_mhiui6vb"));
                    LocalDateTime endTime = parseTimestamp(UtilMap.getString(row, "dateField_mhiui6v9"));

                    table2Map.put("detailId", detailId);
                    table2Map.put("sfys", sfys);
//                    table2Map.put("sjyskzfh", sjyskzfh);
                    table2Map.put("gldh", gldh);
                    table2Map.put("ysbl", ysbl);
                    table2Map.put("ysje", ysje);
                    table2Map.put("ssje", ssje);
                    table2Map.put("endTime", endTime);

                    OrderPayList.add(table2Map);
                }
            }

            // 构建主表数据，映射到数据库表字段
            Map<String, Object> orderData = new HashMap<>();

            // 注意：这里需要将字段名映射到数据库表字段名
            // 示例映射，实际需要根据数据库表结构调整
            orderData.put("djlx", djlx);                    // 单据类型
            orderData.put("djbh", djbh);                    // 单据编号
            orderData.put("ckddh", ckddh);                    // 单据编号
            orderData.put("khmc", khmc);                    // 客户名称
            orderData.put("rq", rq);                        // 日期
            orderData.put("khxypj", khxypj);                // 客户信用评级
            orderData.put("ywlx", ywlx);                    // 业务类型
            orderData.put("xslx", xslx);                    // 销售类型
            orderData.put("bzq", bzq);                      // 保质期
            orderData.put("xsy", xsy);                      // 销售员
            orderData.put("xsbm", xsbm);                    // 销售部门
            orderData.put("bz", bz);                        // 备注
            orderData.put("jsbb", jsbb);                    // 结算币别
            orderData.put("sktj", sktj);                    // 收款条件
            orderData.put("zdzke", zdzke);                  // 整单折扣额
            orderData.put("se", se);                        // 税额
            orderData.put("je", je);                        // 金额
            orderData.put("jshj", jshj);                    // 价税合计
            orderData.put("sfhs", sfhs);                    // 是否含税
            orderData.put("jws", jws);                      // 价位税

            // 明细数据（需要根据实际数据库设计确定存储方式）
            // 如果明细是单独的表，可能需要单独处理
            orderData.put("OrderDetailList", orderList);         // 订单明细列表
            orderData.put("PaymentDetailList", OrderPayList);    // 付款明细列表

            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");

            result.put("data", orderData);
// 将result转换为JSON字符串
            String jsonStr = JSON.toJSONString(result);
// 构建form参数
            Map<String, Object> formParams = new HashMap<>();
            formParams.put("jsons", jsonStr);
            log.info("订单请求参数：" + formParams);
// 发送请求
            HttpResponse response = null;
            if ("add".equals(actionType)) {
                response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/hgdjydtbxsdd")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();
            } else {
                response = HttpRequest.post(kdHost+"/xk/dyzn/WsBasedyzn.asmx/hgdjydtbupdatexsdd")
                        .headerMap(headers, true)
                        .form(formParams)
                        .timeout(90000)  // 30秒超时
                        .execute();
            }

            String responseBody = response.body();
            log.info("返回结果responseBody: " + responseBody);
            try {
                // 一行代码提取
                String jdbh = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getJSONObject("data")
                        .getString("djbh");
                String msg = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getString("msg");
                String code = JSON.parseArray(responseBody)
                        .getJSONObject(0)
                        .getString("code");
                retryOperateData(
                        YDParam.builder()
                                .formInstanceId(formInstId)
                                .updateFormDataJson(JSONObject.toJSONString(UtilMap.map("textField_ml08nk3y, textareaField_mkxqgrvq, textField_mjs6fuwo", code, msg, jdbh)))
                                .useLatestVersion(true).build(),
                        YDConf.FORM_OPERATION.update);

            } catch (Exception e) {
                System.out.println("解析JSON失败: " + e.getMessage());
            }
        } catch (Exception e) {
            // 异常处理
            result.put("table", "KD_YD_SALE_ORDER");
            result.put("action", "error");
            result.put("data", new HashMap<String, Object>() {{
                put("errorMsg", "操作失败：" + e.getMessage());
            }});
            // 可以添加日志记录
            // log.error("insertkdYdOrder error", e);
        }

        return result;
    }

    @Override
    public void SckdYdOrder(Map map) {
        MDC.put("MDC_KEY_PID", "1003");

        try {
            String formInstId = UtilMap.getString(map, "formInstId");
            String khbm = UtilMap.getString(map, "khbm");

            // 参数校验
            if (StringUtils.isBlank(formInstId)) {
                throw new RuntimeException("订单ID不能为空");
            }
            if (StringUtils.isBlank(khbm)) {
                throw new RuntimeException("客户编号不能为空");
            }

            // 1. 查询订单详情
            DDR_New ddrNew = retryQueryData(YDParam.builder()
                    .formInstId(formInstId)
                    .build(), YDConf.FORM_QUERY.retrieve_id);

            if (ddrNew == null || ddrNew.getFormData() == null) {
                throw new RuntimeException("未找到订单信息，订单ID：" + formInstId);
            }

            Map formData1 = ddrNew.getFormData();
            String ddje = UtilMap.getString(formData1, "numberField_mfxv2vgj");
            Long zhcjrq = UtilMap.getLong(formData1, "dateField_mejowmnb");

            // 订单金额校验
            if (ddje == null || ddje.trim().isEmpty()) {
                throw new RuntimeException("订单金额不能为空，订单ID：" + formInstId);
            }

            // 2. 计算订单金额
            Double orderAmount = null;
            try {
                orderAmount = Double.parseDouble(ddje);
                orderAmount = Math.round(orderAmount * 100.0) / 100.0;

                // 订单金额合理性校验
                if (orderAmount < 0) {
                    throw new RuntimeException("订单金额不能为负数: " + orderAmount);
                }
            } catch (NumberFormatException e) {
                throw new RuntimeException("订单金额格式错误: " + ddje, e);
            }

            System.out.println("订单信息：订单ID=" + formInstId +
                    ", 订单金额=" + orderAmount +
                    ", 客户编号=" + khbm);

            // 3. 查询客户历史信息
            Object result = retryQueryData(YDParam.builder()
                    .formUuid("FORM-F79B680547674A6BBD11C0D511E3C14B28FY")
                    .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
                            new YDSearch("textField_mjm9k35n",
                                    khbm,
                                    "客户编号",
                                    YDSearch.Type.TEXT_FIELD,
                                    YDSearch.Operator.EQ)
                    )))
                    .build(), YDConf.FORM_QUERY.retrieve_list_all).getData();

            List<Map> list = (List<Map>) result;

            if (list == null || list.isEmpty()) {
                throw new RuntimeException("未找到客户信息，客户编号：" + khbm);
            }

            // 4. 获取客户现有信息并进行数据完整性校验
            Map customerData = (Map) list.get(0).get("formData");
            Double historicalAmount = UtilMap.getDouble(customerData, "numberField_mjm9k35k");
            Long dddateTimestampStr = UtilMap.getLong(customerData, "dateField_mjqkkcsg");
            Long sfdateTimestampStr = UtilMap.getLong(customerData, "dateField_mjm9k35l");
            String originalSelectFieldValue = UtilMap.getString(customerData, "selectField_l3nrjuq0");
            String originalKhsx = UtilMap.getString(customerData, "selectField_mjsco9d4");

            // 关键字段完整性校验
            if (dddateTimestampStr == null) {
                throw new RuntimeException("最后成交日期不能为空，客户编号：" + khbm);
            }

            if (historicalAmount == null) {
                // 历史金额为null时，记录错误日志并抛出异常，避免错误清零
                System.err.println("严重错误：未能获取到客户历史金额，客户编号：" + khbm +
                        "，返回数据：" + JSONObject.toJSONString(customerData));
                throw new RuntimeException("无法获取客户历史金额，客户编号：" + khbm + "，请检查数据完整性");
            }

            // 记录更新前的数据快照，便于问题追踪
            System.out.println("更新前数据快照：客户编号=" + khbm +
                    ", 历史金额=" + historicalAmount +
                    ", 最后成交日期=" + timestampToDateString(dddateTimestampStr) +
                    ", 公海池日期=" + (sfdateTimestampStr != null ? timestampToDateString(sfdateTimestampStr) : "空") +
                    ", 销售属性=" + originalKhsx +
                    ", 选择字段=" + originalSelectFieldValue);

            // 5. 金额计算和校验
            historicalAmount = Math.round(historicalAmount * 100.0) / 100.0;
            Double totalAmount = orderAmount + historicalAmount;
            totalAmount = Math.round(totalAmount * 100.0) / 100.0;

            // 金额变化监控：检测异常的大幅减少
            if (totalAmount < historicalAmount && totalAmount < historicalAmount * 0.5) {
                String errorMsg = String.format(
                        "警告：金额异常减少！客户编号=%s, 订单金额=%.2f, 原历史金额=%.2f, 新总金额=%.2f, 减少比例=%.2f%%",
                        khbm, orderAmount, historicalAmount, totalAmount,
                        (historicalAmount - totalAmount) / historicalAmount * 100
                );
                System.err.println(errorMsg);
                // 根据业务需求决定是否抛出异常
                // throw new RuntimeException(errorMsg);
            }

            // 订单金额为0时的特殊处理：保持原金额不变
            if (orderAmount == 0 && historicalAmount > 0) {
                System.out.println("订单金额为0，保持原累计金额不变：" + historicalAmount);
                totalAmount = historicalAmount;
            }

            System.out.println("金额计算：订单金额=" + orderAmount +
                    ", 历史金额=" + historicalAmount +
                    ", 总金额=" + totalAmount);

            // 6. 时间计算
            long currentTimestamp = System.currentTimeMillis();
            long currentToDdDays = (currentTimestamp - dddateTimestampStr) / (1000 * 60 * 60 * 24);
            long sfToDdDays = (sfdateTimestampStr != null && sfdateTimestampStr > 0) ?
                    (sfdateTimestampStr - dddateTimestampStr) / (1000 * 60 * 60 * 24) : 0;

            System.out.println("时间计算：当前时间=" + timestampToDateString(String.valueOf(currentTimestamp)) +
                    ", 成交日期=" + timestampToDateString(String.valueOf(dddateTimestampStr)) +
                    ", 当前-成交相差=" + currentToDdDays + "天" +
                    ", 公海-成交相差=" + sfToDdDays + "天");

            // 7. 业务规则计算
            String ghcDateTimestamp = null;
            String selectFieldValue = originalSelectFieldValue;
            String khsx = originalKhsx;

            // 设置客户属性
            if (totalAmount >= 75000 && sfToDdDays <= 180) {
                khsx = "自行开发";
            }

            // 业务规则判断
            if (currentToDdDays < 90 && totalAmount > 0 && Math.abs(sfToDdDays - 180) <= 1) {
                // 条件1：在成交日期上加90天
                ghcDateTimestamp = String.valueOf(calculateTimestamp(sfdateTimestampStr, 90));
                selectFieldValue = "半年金额不足";
                System.out.println("条件1触发：公海池时间设为成交日期+90天=" +
                        timestampToDateString(ghcDateTimestamp));
            } else if (totalAmount >= 75000 && sfToDdDays <= 180) {
                // 条件2：在成交日期上加180天
                ghcDateTimestamp = String.valueOf(calculateTimestamp(sfdateTimestampStr, 180));
                selectFieldValue = "半年金额不足";
                System.out.println("条件2触发：公海池时间设为成交日期+180天=" +
                        timestampToDateString(ghcDateTimestamp));
            } else if (totalAmount < 150000 && sfToDdDays > 180) {
                // 条件3：设置一年金额不足，但不设置公海池日期
                selectFieldValue = "一年金额不足";
                System.out.println("条件3触发：金额<15万且公海日期>180天，设置一年金额不足");
            } else if (totalAmount > 150000) {
                // 【新增】总金额大于15万：释放公海池日期设为成交日期的下一年第一天
                ghcDateTimestamp = getNextYearFirstDay(dddateTimestampStr);
                selectFieldValue = "金额充足";
                System.out.println("条件4触发：总金额>15万，公海池时间设为成交日期下一年第一天=" +
                        timestampToDateString(ghcDateTimestamp));
            } else {
                // 其他情况
                if (totalAmount > 0) {
                    ghcDateTimestamp = String.valueOf(calculateTimestamp(sfdateTimestampStr, 90));
                    selectFieldValue = "半年金额不足";
                    System.out.println("基础情况：金额大于0，公海池时间+90天=" +
                            timestampToDateString(ghcDateTimestamp));
                } else if (totalAmount < 75000) {
                    selectFieldValue = "半年金额不足";
                    System.out.println("金额<7.5万，但未设置公海池时间");
                } else if (totalAmount < 150000) {
                    selectFieldValue = "一年金额不足";
                    System.out.println("金额7.5-15万，但未设置公海池时间");
                }
            }

            // 8. 构建更新数据（只更新需要变更的字段）
            Map<String, Object> formData = new HashMap<>();

            // 必须更新的字段
            formData.put("dateField_mjm9k35j", zhcjrq);  // 最后成交日期
            formData.put("numberField_mjm9k35k", totalAmount);       // 累计金额
            formData.put("selectField_mjsco9d4", khsx);              // 销售属性

            // 条件更新：只在有值时才更新 selectField
            if (selectFieldValue != null && !selectFieldValue.isEmpty()) {
                if (!selectFieldValue.equals(originalSelectFieldValue)) {
                    formData.put("selectField_l3nrjuq0", selectFieldValue);
                    System.out.println("更新选择字段：" + originalSelectFieldValue + " -> " + selectFieldValue);
                }
            }

            // 条件更新：只在明确需要变更公海池日期时才更新
            if (ghcDateTimestamp != null) {
                // 只有当新值与旧值不同时才更新
                String newDateStr = timestampToDateString(ghcDateTimestamp);
                String oldDateStr = sfdateTimestampStr != null ? timestampToDateString(String.valueOf(sfdateTimestampStr)) : "空";
                if (!newDateStr.equals(oldDateStr)) {
                    formData.put("dateField_mjm9k35l", ghcDateTimestamp);
                    System.out.println("更新公海池日期：" + oldDateStr + " -> " + newDateStr);
                } else {
                    System.out.println("公海池日期未变化，跳过更新：" + newDateStr);
                }
            } else {
                // 不设置该字段，upsert操作会保持原值不变
                System.out.println("公海池日期无需变更，保持原值：" +
                        (sfdateTimestampStr != null ? timestampToDateString(String.valueOf(sfdateTimestampStr)) : "空"));
            }

            // 9. 数据变更前最终校验
            if (totalAmount == 0 && historicalAmount > 0) {
                System.err.println("警告：即将把客户金额从 " + historicalAmount + " 更新为 0，请确认业务逻辑！");
                // 可选：根据业务需求决定是否继续执行
                // throw new RuntimeException("金额异常清零，操作已阻止");
            }

            System.out.println("最终更新数据：" + JSONObject.toJSONString(formData));

            // 10. 执行更新操作（retryOperateData已内置重试功能）
            retryOperateData(YDParam.builder()
                    .formUuid("FORM-F79B680547674A6BBD11C0D511E3C14B28FY")
                    .appType("APP_VQDMMWS6OR1VHL8VMFD3")
                    .systemToken("XE766X81JHKXK4Z27SYOI86CPCLQ3J1LV7ODMH2")
                    .noExecuteExpression(false)
                    .searchFieldJson(JSONObject.toJSONString(Arrays.asList(
                            new YDSearch("textField_mjm9k35n",
                                    khbm,
                                    "客户编号",
                                    YDSearch.Type.TEXT_FIELD,
                                    YDSearch.Operator.EQ)
                    )))
                    .formDataJson(JSONObject.toJSONString(formData))
                    .build(), YDConf.FORM_OPERATION.upsert);

            System.out.println("客户信息更新成功，客户编号：" + khbm);

        } catch (Exception e) {
            System.err.println("处理订单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("处理订单失败: " + e.getMessage(), e);
        } finally {
            MDC.remove("MDC_KEY_PID");
        }
    }

    /**
     * 获取指定时间戳的下一年第一天零点的时间戳
     * @param timestamp 时间戳（毫秒）
     * @return 下一年第一天零点的时间戳
     */
    private String getNextYearFirstDay(Long timestamp) {
        if (timestamp == null || timestamp <= 0) {
            // 如果时间戳无效，返回当前时间下一年第一天
            timestamp = System.currentTimeMillis();
        }

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp);

        // 设置为下一年第一天
        calendar.add(Calendar.YEAR, 1);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return String.valueOf(calendar.getTimeInMillis());
    }

    /**
     * 计算指定日期加上天数后的时间戳
     */
    private long calculateTimestamp(Long baseTimestamp, int daysToAdd) {
        if (baseTimestamp == null || baseTimestamp <= 0) {
            baseTimestamp = System.currentTimeMillis();
        }
        return baseTimestamp + (daysToAdd * 24L * 60 * 60 * 1000);
    }

    /**
     * 时间戳转日期字符串（用于日志）
     */
    private String timestampToDateString(Object timestamp) {
        if (timestamp == null) {
            return "空";
        }
        try {
            long ts;
            if (timestamp instanceof String) {
                ts = Long.parseLong((String) timestamp);
            } else if (timestamp instanceof Long) {
                ts = (Long) timestamp;
            } else {
                return timestamp.toString();
            }
            if (ts <= 0) {
                return "无效时间戳";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(new Date(ts));
        } catch (Exception e) {
            return timestamp.toString();
        }
    }

    /**
     * 计算时间戳：在基础时间戳上添加天数
     *
     * @param baseTimestamp 基础时间戳（毫秒）
     * @param days          要添加的天数
     * @return 计算后的时间戳（毫秒）
     */
    private long calculateTimestamp(long baseTimestamp, int days) {
        try {
            long oneDayMillis = 24L * 60L * 60L * 1000L;
            long daysMillis = (long) days * oneDayMillis;
            return baseTimestamp + daysMillis;
        } catch (Exception e) {
            System.err.println("时间戳计算失败：" + baseTimestamp + ", 天数：" + days);
            return baseTimestamp + (days * 24L * 60L * 60L * 1000L);
        }
    }

    /**
     * 辅助方法：将时间戳转换为可读日期（仅用于调试）
     */
    private String timestampToDateString(String timestamp) {
        try {
            long ts = Long.parseLong(timestamp.trim());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(new Date(ts));
        } catch (Exception e) {
            return "无效时间戳：" + timestamp;
        }
    }

    /**
     * 重载方法：直接接收long类型时间戳
     */
    private String timestampToDateString(long timestamp) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(new Date(timestamp));
        } catch (Exception e) {
            return "无效时间戳：" + timestamp;
        }
    }

    private static LocalDateTime parseTimestamp(String timestampStr) {
        if (timestampStr == null || timestampStr.trim().isEmpty()) return null;
        try {
            long timestamp = Long.parseLong(timestampStr.trim());
            return LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timestamp),
                    ZoneId.systemDefault()
            );
        } catch (NumberFormatException e) {
            return null;
        }
    }

    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);
    }
    private String safeGetString1(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(6, RoundingMode.HALF_UP);
        }
        try {
            return new BigDecimal(str.trim())
                    .setScale(6, RoundingMode.HALF_UP);
        } catch (NumberFormatException e) {
            // 返回默认值而不是抛出异常，避免程序中断
            return BigDecimal.ZERO.setScale(6, RoundingMode.HALF_UP);
        }
    }
    public static BigDecimal toBigDecimal1(String str) {
        if (str == null || str.trim().isEmpty()) {
            return BigDecimal.ZERO.setScale(6, RoundingMode.HALF_UP);
        }
        try {
            return new BigDecimal(str.trim())
                    .setScale(6, RoundingMode.HALF_UP);
        } catch (NumberFormatException e) {
            // 返回默认值而不是抛出异常，避免程序中断
            return BigDecimal.ZERO.setScale(6, 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);
//    }

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