package com.gxwebsoft.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.config.CertificateProperties;
import com.gxwebsoft.common.core.utils.*;
import com.gxwebsoft.common.core.service.PaymentCacheService;
import com.gxwebsoft.common.core.service.EnvironmentAwarePaymentService;
import com.gxwebsoft.common.core.config.SpringContextUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.system.entity.Payment;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.service.*;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;
import com.gxwebsoft.common.system.service.PaymentService;
import com.gxwebsoft.common.system.service.SettingService;
import com.gxwebsoft.payment.constants.WechatPayType;
import com.gxwebsoft.shop.mapper.ShopOrderMapper;
import com.gxwebsoft.shop.param.ShopOrderParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAConfig;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
// Native支付的类将使用完全限定名避免冲突
import com.wechat.pay.java.service.payments.model.Transaction;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Date;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.gxwebsoft.common.core.utils.DateTimeUtil.formatDateTime;

/**
 * 订单Service实现
 *
 * @author 科技小王子
 * @since 2025-01-11 10:45:12
 */
@Slf4j
@Service
public class ShopOrderServiceImpl extends ServiceImpl<ShopOrderMapper, ShopOrder> implements ShopOrderService {
    @Value("${spring.profiles.active}")
    String active;
    @Resource
    private ConfigProperties config;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ShopOrderGoodsService shopOrderGoodsService;
    @Resource
    private ShopGoodsService shopGoodsService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private SettingService settingService;
    @Resource
    private CertificateProperties certConfig;
    @Resource
    private CertificateLoader certificateLoader;
    @Resource
    private PaymentCacheService paymentCacheService;
    @Resource
    private WechatCertAutoConfig wechatCertAutoConfig;
    @Resource
    private WechatPayDiagnostic wechatPayDiagnostic;
    @Resource
    private WechatPayCertificateDiagnostic certificateDiagnostic;
    @Resource
    private ShopOrderUpdate10550Service shopOrderUpdate10550Service;
    @Resource
    private ShopUserCouponService shopUserCouponService;


    @Override
    public PageResult<ShopOrder> pageRel(ShopOrderParam param) {
        PageParam<ShopOrder, ShopOrderParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<ShopOrder> list = baseMapper.selectPageRel(page, param);

        // 整理订单数据
        if (!CollectionUtils.isEmpty(list)) {
            final Set<Integer> orderIds = list.stream().map(ShopOrder::getOrderId).collect(Collectors.toSet());
            final List<ShopOrderGoods> goodsList = shopOrderGoodsService.list(new LambdaQueryWrapper<ShopOrderGoods>().in(ShopOrderGoods::getOrderId, orderIds));
            final Map<Integer, List<ShopOrderGoods>> collect = goodsList.stream().collect(Collectors.groupingBy(ShopOrderGoods::getOrderId));
            list.forEach(d -> {
                d.setOrderGoods(collect.get(d.getOrderId()));

                // 确保 realName 字段有值，优先使用关联查询的结果，如果为空则使用订单表中的 realName
                if (StrUtil.isBlank(d.getRealName())) {
                    log.debug("订单 {} 的 realName 为空，尝试从其他字段获取", d.getOrderId());
                    // 可以根据业务需求添加其他逻辑，比如从 nickname 或其他字段获取
                }
            });
        }
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<ShopOrder> listRel(ShopOrderParam param) {
        List<ShopOrder> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<ShopOrder, ShopOrderParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public ShopOrder getByIdRel(Integer orderId) {
        ShopOrderParam param = new ShopOrderParam();
        param.setOrderId(orderId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public HashMap<String, String> createWxOrder(ShopOrder order) {
        Payment payment = null;  // 声明在try块外面，这样catch块也能访问
        try {
            System.out.println("=== 开始创建微信支付订单 ===");
            System.out.println("订单号: " + order.getOrderNo());
            System.out.println("租户ID: " + order.getTenantId());
            System.out.println("支付类型: " + order.getPayType());
            System.out.println("订单金额: " + order.getTotalPrice());
            System.out.println("用户OpenID: " + order.getOpenid());

            // 检查订单基本信息
            if (order.getTenantId() == null) {
                throw new RuntimeException("订单租户ID为null");
            }
            if (order.getOrderNo() == null || order.getOrderNo().trim().isEmpty()) {
                throw new RuntimeException("订单号为空");
            }
            if (order.getTotalPrice() == null) {
                throw new RuntimeException("订单金额为null");
            }

            // 根据支付类型检查OpenID
            if (order.getPayType().equals(1)) {
                // JSAPI支付需要OpenID
                if (order.getOpenid() == null || order.getOpenid().trim().isEmpty()) {
                    throw new RuntimeException("JSAPI支付必须传openid");
                }
            }

            // 后台微信支付配置信息
            payment = getPayment(order);
            System.out.println("支付配置: " + (payment != null ? "已获取" : "未获取"));

            if (payment == null) {
                throw new RuntimeException("支付配置为null，租户ID: " + order.getTenantId());
            }

            // 检查支付配置的关键字段
            if (payment.getAppId() == null || payment.getAppId().trim().isEmpty()) {
                throw new RuntimeException("支付配置中应用ID为null或空");
            }
            if (payment.getMchId() == null || payment.getMchId().trim().isEmpty()) {
                throw new RuntimeException("支付配置中商户号为null或空");
            }

            // 返回的订单数据
            final HashMap<String, String> orderInfo = new HashMap<>();

            // 根据支付类型选择不同的处理逻辑
            if (order.getPayType().equals(102)) {
                // Native支付处理（兼容旧的102类型）
                System.out.println("⚠️ 检测到使用废弃的微信Native支付类型(102)，建议升级到微信支付(1)");
                order.setWechatPayType(WechatPayType.NATIVE);
                return createNativePayOrder(order, payment);
            } else if (order.getPayType().equals(1)) {
                // 微信支付处理 - 根据是否有openid判断使用JSAPI还是Native
                String wechatType = WechatPayType.getAutoType(order.getOpenid());
                order.setWechatPayType(wechatType);

                if (WechatPayType.JSAPI.equals(wechatType)) {
                    // 有openid，使用JSAPI支付
                    return createJsapiPayOrder(order, payment);
                } else {
                    // 无openid，使用Native支付
                    return createNativePayOrder(order, payment);
                }
            } else {
                // 其他支付方式暂时使用JSAPI处理
                return createJsapiPayOrder(order, payment);
            }

        } catch (Exception e) {
            System.err.println("=== 创建微信支付订单失败 ===");
            System.err.println("错误信息: " + e.getMessage());
            System.err.println("错误类型: " + e.getClass().getName());

            // 特殊处理签名验证失败的情况
            if (e.getMessage() != null && e.getMessage().contains("signature is incorrect")) {
                System.err.println("🔍 签名验证失败诊断:");
                System.err.println("1. 检查商户证书序列号是否正确");
                System.err.println("2. 检查APIv3密钥是否正确");
                System.err.println("3. 检查私钥文件是否正确");
                System.err.println("4. 检查微信支付平台证书是否过期");
                System.err.println("5. 建议使用自动证书配置避免证书管理问题");
                System.err.println("当前支付配置:");
                System.err.println("租户ID: " + order.getTenantId());
                System.err.println("商户号: " + (payment != null ? payment.getMchId() : "null"));
                System.err.println("应用ID: " + (payment != null ? payment.getAppId() : "null"));
            }

            throw new RuntimeException("创建微信支付订单失败：" + e.getMessage(), e);
        }
    }

    /**
     * 创建Native支付订单
     */
    private HashMap<String, String> createNativePayOrder(ShopOrder order, Payment payment) throws Exception {
        System.out.println("=== 使用Native支付模式 ===");

        // 构建Native支付服务
        Config wxPayConfig = getWxPayConfig(order);
        NativePayService nativeService = new NativePayService.Builder().config(wxPayConfig).build();

        // 订单金额（转换为分）
        BigDecimal decimal = order.getTotalPrice();
        final BigDecimal multiply = decimal.multiply(new BigDecimal(100));
        Integer money = multiply.intValue();

        // 测试环境使用1分钱
        if (active.equals("dev")) {
            money = 1;
        }

        // 构建Native支付请求
        com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest request =
            new com.wechat.pay.java.service.payments.nativepay.model.PrepayRequest();
        com.wechat.pay.java.service.payments.nativepay.model.Amount amount =
            new com.wechat.pay.java.service.payments.nativepay.model.Amount();
        amount.setTotal(money);
        amount.setCurrency("CNY");
        request.setAmount(amount);

        request.setAppid(payment.getAppId());
        request.setMchid(payment.getMchId());

        // 微信支付description字段限制127字节，需要截断处理
        String description = com.gxwebsoft.common.core.utils.WechatPayUtils.processDescription(order.getComments());
        request.setDescription(description);
        request.setOutTradeNo(order.getOrderNo());
        request.setAttach(order.getTenantId().toString());

        System.out.println("=== 关键信息确认 ===");
        System.out.println("发送给微信的订单号(OutTradeNo): " + order.getOrderNo());
        System.out.println("商户号(MchId): " + payment.getMchId());
        System.out.println("应用ID(AppId): " + payment.getAppId());

        // 设置回调地址
        String notifyUrl = config.getServerUrl() + "/system/wx-pay/notify/" + order.getTenantId();
        if (active.equals("dev")) {
            notifyUrl = "http://jimei-api.natapp1.cc/api/shop/wx-pay/notify/" + order.getTenantId();
        }
        if (StrUtil.isNotBlank(payment.getNotifyUrl())) {
            notifyUrl = payment.getNotifyUrl().concat("/").concat(order.getTenantId().toString());
        }
        request.setNotifyUrl(notifyUrl);

        System.out.println("=== 发起Native支付请求 ===");
        System.out.println("请求参数: " + request);

        // 调用Native支付API
        com.wechat.pay.java.service.payments.nativepay.model.PrepayResponse response = nativeService.prepay(request);

        System.out.println("=== Native支付响应成功 ===");
        System.out.println("二维码URL: " + response.getCodeUrl());

        // 构建返回数据
        final HashMap<String, String> orderInfo = new HashMap<>();
        orderInfo.put("provider", "wxpay");
        orderInfo.put("codeUrl", response.getCodeUrl());  // Native支付返回二维码URL
        orderInfo.put("orderNo", order.getOrderNo());
        orderInfo.put("payType", WechatPayType.NATIVE);
        orderInfo.put("wechatPayType", WechatPayType.NATIVE);

        return orderInfo;
    }

    /**
     * 创建JSAPI支付订单（原有逻辑）
     */
    private HashMap<String, String> createJsapiPayOrder(ShopOrder order, Payment payment) throws Exception {
        System.out.println("=== 使用JSAPI支付模式 ===");

        // JSAPI支付必须有OpenID
        if (order.getOpenid() == null || order.getOpenid().trim().isEmpty()) {
            throw new RuntimeException("JSAPI支付必须传openid");
        }

        // 构建JSAPI支付服务
        JsapiServiceExtension service = getWxService(order);
        System.out.println("微信支付服务构建完成");

        // 订单金额
        BigDecimal decimal = order.getTotalPrice();
        final BigDecimal multiply = decimal.multiply(new BigDecimal(100));
        Integer money = multiply.intValue();

        System.out.println("=== 构建支付请求参数 ===");

        PrepayRequest request = new PrepayRequest();
        Amount amount = new Amount();
        amount.setTotal(money);
        amount.setCurrency("CNY");
        request.setAmount(amount);

        System.out.println("设置应用ID: " + payment.getAppId());
        request.setAppid(payment.getAppId());

        System.out.println("设置商户号: " + payment.getMchId());
        request.setMchid(payment.getMchId());

        // 微信支付description字段限制127字节，需要截断处理
        String description = com.gxwebsoft.common.core.utils.WechatPayUtils.processDescription(order.getComments());
        System.out.println("设置描述: " + description);
        request.setDescription(description);

        System.out.println("设置订单号: " + order.getOrderNo());
        request.setOutTradeNo(order.getOrderNo());

        System.out.println("设置附加数据: " + order.getTenantId().toString());
        request.setAttach(order.getTenantId().toString());

        final Payer payer = new Payer();
        System.out.println("设置用户OpenID: " + order.getOpenid());
        payer.setOpenid(order.getOpenid());
        request.setPayer(payer);
        request.setNotifyUrl(config.getServerUrl() + "/system/wx-pay/notify/" + order.getTenantId()); // 默认回调地址
        // 测试环境
        if (active.equals("dev")) {
            amount.setTotal(1);
            request.setAmount(amount);
            request.setNotifyUrl("http://jimei-api.natapp1.cc/api/shop/wx-pay/notify/" + order.getTenantId()); // 默认回调地址
        }
        // 后台配置的回调地址
        if (StrUtil.isNotBlank(payment.getNotifyUrl())) {
            request.setNotifyUrl(payment.getNotifyUrl().concat("/").concat(order.getTenantId().toString()));
            System.out.println("后台配置的回调地址 = " + request.getNotifyUrl());
        }
        System.out.println("=== 发起微信支付请求 ===");
        System.out.println("请求参数: " + request);

        PrepayWithRequestPaymentResponse response = service.prepayWithRequestPayment(request);

        System.out.println("=== 微信支付响应成功 ===");
        System.out.println("预支付ID: " + response.getPackageVal());

        final HashMap<String, String> orderInfo = new HashMap<>();
        orderInfo.put("provider", "wxpay");
        orderInfo.put("timeStamp", response.getTimeStamp());
        orderInfo.put("nonceStr", response.getNonceStr());
        orderInfo.put("package", response.getPackageVal());
        orderInfo.put("signType", "RSA");
        orderInfo.put("paySign", response.getPaySign());
        orderInfo.put("orderNo", order.getOrderNo());
        orderInfo.put("payType", WechatPayType.JSAPI);
        orderInfo.put("wechatPayType", WechatPayType.JSAPI);
        return orderInfo;
    }

    @Override
    public ShopOrder getByOutTradeNo(String outTradeNo) {
        return baseMapper.getByOutTradeNo(outTradeNo);
    }

    /**
     * 修复订单支付状态
     *
     * @param shopOrder
     */
    @Override
    public Boolean queryOrderByOutTradeNo(ShopOrder shopOrder) {
        // 后台微信支付配置信息
        final Payment payment = getPayment(shopOrder);
        QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();
        queryRequest.setMchid(payment.getMchId());
        queryRequest.setOutTradeNo(shopOrder.getOrderNo());
        // 构建service
        JsapiServiceExtension service = getWxService(shopOrder);
        try {
            Transaction result = service.queryOrderByOutTradeNo(queryRequest);
            if (result.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
                shopOrder.setPayStatus(true);
                shopOrder.setPayTime(LocalDateTime.now());
                shopOrder.setTransactionId(result.getTransactionId());
                updateById(shopOrder);
                return true;
            }
        } catch (ServiceException e) {
            // API返回失败, 例如ORDER_NOT_EXISTS
            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            System.out.printf("reponse body=[%s]\n", e.getResponseBody());
        }
        return false;
    }

    @Override
    public void updateByOutTradeNo(ShopOrder order) {
        order.setExpirationTime(null);
        baseMapper.updateByOutTradeNo(order);

        // 处理支付成功后的业务逻辑
        handlePaymentSuccess(order);

        if (order.getTenantId().equals(10550)) {
            shopOrderUpdate10550Service.update(order);
        }
    }

    /**
     * 处理支付成功后的业务逻辑
     */
    private void handlePaymentSuccess(ShopOrder order) {
        try {
            // 1. 使用优惠券
            if (order.getCouponId() != null && order.getCouponId() > 0) {
                markCouponAsUsed(order);
            }

            // 2. 累计商品销量
            updateGoodsSales(order);

            log.info("支付成功后业务逻辑处理完成 - 订单号：{}", order.getOrderNo());
        } catch (Exception e) {
            log.error("处理支付成功后业务逻辑失败 - 订单号：{}", order.getOrderNo(), e);
            // 不抛出异常，避免影响支付回调的成功响应
        }
    }

    /**
     * 标记优惠券为已使用
     */
    private void markCouponAsUsed(ShopOrder order) {
        try {
            // 注入 CouponStatusService 并使用其 useCoupon 方法
            // couponStatusService.useCoupon(order.getCouponId().longValue(), order.getOrderId(), order.getOrderNo());

            // 临时保持原有逻辑，建议后续重构
            ShopUserCoupon coupon = shopUserCouponService.getById(order.getCouponId());
            if (coupon != null) {
                coupon.markAsUsed(order.getOrderId(), order.getOrderNo());
                shopUserCouponService.updateById(coupon);
                log.info("优惠券标记为已使用 - 优惠券ID：{}，订单号：{}", order.getCouponId(), order.getOrderNo());
            }
        } catch (Exception e) {
            log.error("标记优惠券为已使用失败 - 优惠券ID：{}，订单号：{}", order.getCouponId(), order.getOrderNo(), e);
        }
    }

    /**
     * 累计商品销量
     */
    private void updateGoodsSales(ShopOrder order) {
        try {
            // 获取订单商品列表（忽略租户隔离）
            final List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.getListByOrderIdIgnoreTenant(order.getOrderId());

            if (orderGoodsList.isEmpty()) {
                log.warn("订单商品列表为空 - 订单号：{}", order.getOrderNo());
                return;
            }

            // 累计每个商品的销量
            for (ShopOrderGoods orderGoods : orderGoodsList) {
                updateSingleGoodsSales(orderGoods);
            }

            log.info("商品销量累计完成 - 订单号：{}，商品数量：{}", order.getOrderNo(), orderGoodsList.size());
        } catch (Exception e) {
            log.error("累计商品销量失败 - 订单号：{}", order.getOrderNo(), e);
        }
    }

    /**
     * 累计单个商品的销量
     * 使用新的addSaleCount方法，忽略租户隔离确保更新成功
     */
    private void updateSingleGoodsSales(ShopOrderGoods orderGoods) {
        try {
            if (orderGoods.getGoodsId() == null || orderGoods.getTotalNum() == null || orderGoods.getTotalNum() <= 0) {
                log.warn("商品销量累计参数无效 - 商品ID：{}，购买数量：{}",
                    orderGoods.getGoodsId(), orderGoods.getTotalNum());
                return;
            }

            // 使用新的addSaleCount方法，忽略租户隔离
            boolean updated = shopGoodsService.addSaleCount(orderGoods.getGoodsId(), orderGoods.getTotalNum());

            if (updated) {
                log.info("商品销量累计成功 - 商品ID：{}，商品名称：{}，购买数量：{}",
                    orderGoods.getGoodsId(), orderGoods.getGoodsName(), orderGoods.getTotalNum());
            } else {
                log.warn("商品销量累计失败 - 商品ID：{}，商品名称：{}，购买数量：{}",
                    orderGoods.getGoodsId(), orderGoods.getGoodsName(), orderGoods.getTotalNum());
            }
        } catch (Exception e) {
            log.error("累计单个商品销量异常 - 商品ID：{}，商品名称：{}，购买数量：{}",
                orderGoods.getGoodsId(), orderGoods.getGoodsName(), orderGoods.getTotalNum(), e);
        }
    }

    /**
     * 读取微信支付配置
     * 生产环境优先从缓存读取 Payment:1* 格式的商户信息
     * 开发环境自动使用本地回调地址
     *
     * @param order
     * @return
     */
    public Payment getPayment(ShopOrder order) {
        // 先清除可能的错误缓存
//      paymentCacheService.removePaymentConfig(order.getPayType().toString(), order.getTenantId());

        // 使用环境感知的支付配置服务
        Payment payment;
        try {
            // 尝试使用环境感知服务
            EnvironmentAwarePaymentService envPaymentService =
                SpringContextUtil.getBean(EnvironmentAwarePaymentService.class);
            payment = envPaymentService.getEnvironmentAwarePaymentConfig(order.getPayType(), order.getTenantId());
        } catch (Exception e) {
            // 如果环境感知服务不可用，回退到原有方式
            log.warn("环境感知支付服务不可用，使用原有配置方式: {}", e.getMessage());
            payment = paymentCacheService.getPaymentConfig(order.getPayType(), order.getTenantId());
        }

        // 添加详细的支付配置检查
        System.out.println("=== 支付配置检查 ===");
        System.out.println("订单支付类型: " + order.getPayType());
        System.out.println("租户ID: " + order.getTenantId());

        if (payment == null) {
            throw new RuntimeException("未找到支付配置，支付类型: " + order.getPayType() + ", 租户ID: " + order.getTenantId());
        }

        System.out.println("支付配置ID: " + payment.getId());
        System.out.println("支付方式名称: " + payment.getName());
        System.out.println("支付类型: " + payment.getType());
        System.out.println("支付代码: " + payment.getCode());
        System.out.println("应用ID: " + payment.getAppId());
        System.out.println("商户号: " + payment.getMchId());
        System.out.println("API密钥: " + (payment.getApiKey() != null ? "已配置(长度:" + payment.getApiKey().length() + ")" : "未配置"));
        System.out.println("商户证书序列号: " + payment.getMerchantSerialNumber());
        System.out.println("状态: " + payment.getStatus());

        return payment;
    }

    /**
     * 构建微信支付
     *
     * @param order
     * @return
     */
    public JsapiServiceExtension getWxService(ShopOrder order) {
        try {
            final Payment payment = getPayment(order);

            // 提前声明所有需要的变量，避免重复定义
            String privateKey;
            String apiclientCert = null;
            String pubKey = null;
            String tenantCertPath = null;
            String privateKeyPath = null;
            String pubKeyPath = null;
            String apiclientCertPath = null;
            String apiclientCertFile = null;
            String pubKeyFile = null;

            // 运行配置诊断
            System.out.println("=== 运行微信支付配置诊断 ===");
            wechatPayDiagnostic.diagnosePaymentConfig(payment, null, active);

            // 运行证书诊断
            System.out.println("=== 运行证书诊断 ===");
            WechatPayCertificateDiagnostic.DiagnosticResult diagnosticResult =
                    certificateDiagnostic.diagnoseCertificateConfig(payment, order.getTenantId(), active);
            System.out.println(diagnosticResult.getFullReport());



            // 构建微信支付配置
            Config config = null;
            if (active.equals("dev")) {
                // 开发环境使用自动证书配置
                // 首先初始化私钥路径
                tenantCertPath = "dev/wechat/" + order.getTenantId();
                privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
                privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
                System.out.println("开发环境私钥路径: " + privateKeyPath);
                System.out.println("开发环境私钥加载成功: " + privateKey);

                // 检查数据库配置是否完整
                if (payment.getMchId() == null || payment.getMchId().trim().isEmpty()) {
                    throw new RuntimeException("数据库中商户号(mchId)未配置");
                }
                if (payment.getMerchantSerialNumber() == null || payment.getMerchantSerialNumber().trim().isEmpty()) {
                    throw new RuntimeException("数据库中商户证书序列号(merchantSerialNumber)未配置");
                }
                if (payment.getApiKey() == null || payment.getApiKey().trim().isEmpty()) {
                    throw new RuntimeException("数据库中API密钥(apiKey)未配置");
                }

                System.out.println("=== 使用数据库支付配置 ===");
                System.out.println("商户号: " + payment.getMchId());
                System.out.println("序列号: " + payment.getMerchantSerialNumber());
                System.out.println("API密钥: 已配置(长度:" + payment.getApiKey().length() + ")");

                // 临时使用RSA配置替代自动证书配置，避免404错误
                System.out.println("=== 注意：使用RSA配置替代自动证书配置 ===");
                System.out.println("原因：商户平台可能未开启API安全功能或未申请微信支付公钥");

                // 首先检查是否配置了公钥，如果有则优先使用公钥模式
                if (payment.getPubKey() != null && !payment.getPubKey().isEmpty() &&
                        payment.getPubKeyId() != null && !payment.getPubKeyId().isEmpty()) {

                    try {
                        // 开发环境固定使用 wechatpay_public_key.pem
                        pubKeyPath = tenantCertPath + "/wechatpay_public_key.pem";

                        System.out.println("开发环境公钥文件路径: " + pubKeyPath);

                        // 检查公钥文件是否存在
                        if (certificateLoader.certificateExists(pubKeyPath)) {
                            System.out.println("=== 检测到公钥配置，使用RSA公钥模式 ===");
                            System.out.println("公钥文件: " + payment.getPubKey());
                            System.out.println("公钥ID: " + payment.getPubKeyId());

                            pubKeyFile = certificateLoader.loadCertificatePath(pubKeyPath);
                            System.out.println("✅ 开发环境公钥文件加载成功: " + pubKeyFile);

                            config = new RSAPublicKeyConfig.Builder()
                                    .merchantId(payment.getMchId())
                                    .privateKeyFromPath(privateKey)
                                    .publicKeyFromPath(pubKeyFile)
                                    .publicKeyId(payment.getPubKeyId())
                                    .merchantSerialNumber(payment.getMerchantSerialNumber())
                                    .apiV3Key(payment.getApiKey())
                                    .build();
                            System.out.println("✅ 开发环境RSA公钥配置成功");
                        } else {
                            System.out.println("⚠️ 开发环境公钥文件不存在，跳过公钥模式: " + pubKeyPath);
                            // 跳过公钥配置，继续后续的自动证书配置
                        }
                    } catch (Exception e) {
                        System.err.println("❌ 开发环境公钥配置检查失败: " + e.getMessage());
                        // 跳过公钥配置，继续后续的自动证书配置
                    }
                }

                // 如果没有公钥配置或公钥文件不存在，尝试自动证书配置
                if (config == null) {
                    // 没有公钥配置，尝试自动证书配置
                    try {
                        System.out.println("=== 尝试创建自动证书配置 ===");
                        System.out.println("商户号: " + payment.getMchId());
                        System.out.println("私钥路径: " + privateKey);
                        System.out.println("序列号: " + payment.getMerchantSerialNumber());
                        System.out.println("API密钥长度: " + (payment.getApiKey() != null ? payment.getApiKey().length() : 0));

                        config = wechatCertAutoConfig.createAutoConfig(
                                payment.getMchId(),
                                privateKey,
                                payment.getMerchantSerialNumber(),
                                payment.getApiKey()
                        );
                        System.out.println("✅ 开发环境自动证书配置成功");
                    } catch (Exception e) {
                        System.err.println("❌ 自动证书配置失败: " + e.getMessage());
                        System.err.println("错误类型: " + e.getClass().getName());
                        e.printStackTrace();

                        // 检查是否是证书相关的错误
                        if (e.getMessage() != null && (
                                e.getMessage().contains("certificate") ||
                                        e.getMessage().contains("X509Certificate") ||
                                        e.getMessage().contains("getSerialNumber") ||
                                        e.getMessage().contains("404") ||
                                        e.getMessage().contains("API安全"))) {

                            System.err.println("🔍 证书问题诊断:");
                            System.err.println("1. 检查商户平台是否已开启API安全功能");
                            System.err.println("2. 检查是否已申请使用微信支付公钥");
                            System.err.println("3. 检查网络连接是否正常");
                            System.err.println("4. 检查商户证书序列号是否正确");
                            System.err.println("5. 参考文档：https://pay.weixin.qq.com/doc/v3/merchant/4012153196");

                            // 开发环境回退到基础RSA配置
                            System.err.println("⚠️ 开发环境回退到基础RSA配置...");
                            try {
                                // 方案1：尝试使用RSA证书配置（需要商户证书文件）
                                apiclientCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();

                                if (certificateLoader.certificateExists(apiclientCertPath)) {
                                    apiclientCertFile = certificateLoader.loadCertificatePath(apiclientCertPath);
                                    System.out.println("方案1: 使用RSA证书配置作为回退方案");
                                    System.out.println("商户证书路径: " + apiclientCertFile);

                                    try {
                                        config = new RSAConfig.Builder()
                                                .merchantId(payment.getMchId())
                                                .privateKeyFromPath(privateKey)
                                                .merchantSerialNumber(payment.getMerchantSerialNumber())
                                                .wechatPayCertificatesFromPath(apiclientCertFile)
                                                .build();
                                        System.out.println("✅ 开发环境RSA证书配置成功");
                                    } catch (Exception rsaException) {
                                        System.err.println("RSA证书配置失败: " + rsaException.getMessage());
                                        throw rsaException;
                                    }
                                } else {
                                    System.err.println("❌ 商户证书文件不存在: " + apiclientCertPath);
                                    System.err.println("⚠️ 尝试方案2: 使用最小化配置...");

                                    // 方案2：使用最小化的RSA配置（仅私钥和序列号）
                                    try {
                                        // 创建一个最基础的配置，不依赖平台证书
                                        config = new com.wechat.pay.java.core.RSAConfig.Builder()
                                                .merchantId(payment.getMchId())
                                                .privateKeyFromPath(privateKey)
                                                .merchantSerialNumber(payment.getMerchantSerialNumber())
                                                .build();
                                        System.out.println("✅ 开发环境最小化RSA配置成功");
                                    } catch (Exception minimalException) {
                                        System.err.println("最小化配置也失败: " + minimalException.getMessage());
                                        throw new RuntimeException("所有配置方案都失败，请检查私钥文件和商户配置", e);
                                    }
                                }
                            } catch (Exception fallbackException) {
                                System.err.println("❌ 手动证书配置失败: " + fallbackException.getMessage());
                                fallbackException.printStackTrace();

                                // 最后的回退：抛出详细错误信息
                                System.err.println("=== 最终错误诊断 ===");
                                System.err.println("1. 自动证书配置失败原因: " + e.getMessage());
                                System.err.println("2. 手动证书配置失败原因: " + fallbackException.getMessage());
                                System.err.println("3. 建议解决方案:");
                                System.err.println("   - 检查微信商户平台是否开启API安全功能");
                                System.err.println("   - 确认已申请使用微信支付公钥");
                                System.err.println("   - 验证商户证书序列号是否正确");
                                System.err.println("   - 检查私钥文件是否完整且格式正确");

                                throw new RuntimeException("微信支付配置失败，请检查商户平台API安全设置和证书配置。原始错误: " + e.getMessage() + ", 回退错误: " + fallbackException.getMessage(), e);
                            }
                        } else {
                            throw new RuntimeException("微信支付配置失败：" + e.getMessage(), e);
                        }
                    }
                }
            } else {
                // 生产环境 - 首先初始化私钥
                final String certRootPath = certConfig.getCertRootPath();
                System.out.println("生产环境证书根路径: " + certRootPath);

                String privateKeyRelativePath = payment.getApiclientKey();
                System.out.println("数据库中的私钥相对路径: " + privateKeyRelativePath);

                // 修复路径拼接逻辑：数据库中存储的路径如果已经包含 /file，则直接拼接
                String privateKeyFullPath;
                if (privateKeyRelativePath.startsWith("/file/")) {
                    // 路径已经包含 /file/ 前缀，直接拼接到根路径
                    privateKeyFullPath = certRootPath + privateKeyRelativePath;
                } else if (privateKeyRelativePath.startsWith("file/")) {
                    // 路径包含 file/ 前缀，添加根路径和斜杠
                    privateKeyFullPath = certRootPath + "/" + privateKeyRelativePath;
                } else {
                    // 路径不包含 file 前缀，添加完整的 /file/ 前缀
                    privateKeyFullPath = certRootPath + "/file/" + privateKeyRelativePath;
                }

                System.out.println("生产环境私钥完整路径: " + privateKeyFullPath);
                privateKey = certificateLoader.loadCertificatePath(privateKeyFullPath);
                System.out.println("✅ 生产环境私钥加载完成: " + privateKey);

                // 生产环境也优先检查公钥配置
                if (payment.getPubKey() != null && !payment.getPubKey().isEmpty() &&
                        payment.getPubKeyId() != null && !payment.getPubKeyId().isEmpty()) {

                    System.out.println("=== 生产环境检测到公钥配置，使用RSA公钥模式 ===");
                    System.out.println("公钥文件路径: " + payment.getPubKey());
                    System.out.println("公钥ID: " + payment.getPubKeyId());

                    try {
                        // 生产环境处理公钥路径
                        String pubKeyRelativePath = payment.getPubKey();
                        System.out.println("数据库中的公钥相对路径: " + pubKeyRelativePath);

                        // 修复公钥路径拼接逻辑，与私钥路径处理保持一致
                        String pubKeyFullPath;
                        if (pubKeyRelativePath.startsWith("/file/")) {
                            // 路径已经包含 /file/ 前缀，直接拼接到根路径
                            pubKeyFullPath = certRootPath + pubKeyRelativePath;
                        } else if (pubKeyRelativePath.startsWith("file/")) {
                            // 路径包含 file/ 前缀，添加根路径和斜杠
                            pubKeyFullPath = certRootPath + "/" + pubKeyRelativePath;
                        } else {
                            // 路径不包含 file 前缀，添加完整的 /file/ 前缀
                            pubKeyFullPath = certRootPath + "/file/" + pubKeyRelativePath;
                        }

                        System.out.println("生产环境公钥完整路径: " + pubKeyFullPath);
                        pubKeyFile = certificateLoader.loadCertificatePath(pubKeyFullPath);
                        System.out.println("✅ 生产环境公钥文件加载成功: " + pubKeyFile);

                        config = new RSAPublicKeyConfig.Builder()
                                .merchantId(payment.getMchId())
                                .privateKeyFromPath(privateKey)
                                .publicKeyFromPath(pubKeyFile)
                                .publicKeyId(payment.getPubKeyId())
                                .merchantSerialNumber(payment.getMerchantSerialNumber())
                                .apiV3Key(payment.getApiKey())
                                .build();
                        System.out.println("✅ 生产环境RSA公钥配置成功");
                    } catch (Exception pubKeyException) {
                        System.err.println("❌ 生产环境RSA公钥配置失败: " + pubKeyException.getMessage());
                        pubKeyException.printStackTrace();
                        throw new RuntimeException("生产环境RSA公钥配置失败: " + pubKeyException.getMessage(), pubKeyException);
                    }
                } else {
                    // 没有公钥配置，使用自动证书配置
                    System.out.println("=== 生产环境使用自动证书配置 ===");
                    System.out.println("商户号: " + payment.getMchId());
                    System.out.println("序列号: " + payment.getMerchantSerialNumber());
                    System.out.println("API密钥: 已配置(长度:" + payment.getApiKey().length() + ")");

                    try {
                        // 优先使用自动证书配置，避免证书过期和序列号不匹配问题
                        config = wechatCertAutoConfig.createAutoConfig(
                                payment.getMchId(),
                                privateKey,
                                payment.getMerchantSerialNumber(),
                                payment.getApiKey()
                        );
                        System.out.println("✅ 生产环境自动证书配置成功");
                    } catch (Exception autoConfigException) {
                        System.err.println("⚠️ 自动证书配置失败，回退到手动证书配置");
                        System.err.println("自动配置错误: " + autoConfigException.getMessage());
                        System.err.println("错误类型: " + autoConfigException.getClass().getName());
                        autoConfigException.printStackTrace();

                        // 检查是否是证书相关的错误
                        if (autoConfigException.getMessage() != null && (
                                autoConfigException.getMessage().contains("certificate") ||
                                        autoConfigException.getMessage().contains("X509Certificate") ||
                                        autoConfigException.getMessage().contains("getSerialNumber") ||
                                        autoConfigException.getMessage().contains("404") ||
                                        autoConfigException.getMessage().contains("API安全"))) {

                            System.err.println("🔍 生产环境证书问题诊断:");
                            System.err.println("1. 检查商户平台是否已开启API安全功能");
                            System.err.println("2. 检查是否已申请使用微信支付公钥");
                            System.err.println("3. 检查网络连接是否正常");
                            System.err.println("4. 检查商户证书序列号是否正确");
                        }

                        try {
                            // 回退到手动证书配置
                            if (payment.getPubKey() != null && !payment.getPubKey().isEmpty()) {
                                System.out.println("使用RSA公钥配置作为回退方案");
                                config = new RSAPublicKeyConfig.Builder()
                                        .merchantId(payment.getMchId())
                                        .privateKeyFromPath(privateKey)
                                        .publicKeyFromPath(pubKey)
                                        .publicKeyId(payment.getPubKeyId())
                                        .merchantSerialNumber(payment.getMerchantSerialNumber())
                                        .apiV3Key(payment.getApiKey())
                                        .build();
                                System.out.println("✅ 生产环境RSA公钥配置成功");
                            } else if (apiclientCert != null && !apiclientCert.isEmpty()) {
                                System.out.println("使用RSA证书配置作为回退方案");
                                config = new RSAConfig.Builder()
                                        .merchantId(payment.getMchId())
                                        .privateKeyFromPath(privateKey)
                                        .merchantSerialNumber(payment.getMerchantSerialNumber())
                                        .wechatPayCertificatesFromPath(apiclientCert)
                                        .build();
                                System.out.println("✅ 生产环境RSA证书配置成功");
                            } else {
                                throw new RuntimeException("生产环境缺少必要的证书文件，无法创建手动证书配置", autoConfigException);
                            }
                        } catch (Exception fallbackException) {
                            System.err.println("❌ 生产环境手动证书配置也失败: " + fallbackException.getMessage());
                            throw new RuntimeException("生产环境微信支付配置失败，请检查商户平台API安全设置和证书配置", autoConfigException);
                        }
                    }
                }
            }

            // 构建service
            return new JsapiServiceExtension.Builder().config(config).build();
        } catch (Exception e) {
            System.err.println("=== 构建微信支付服务失败 ===");
            System.err.println("错误信息: " + e.getMessage());
            System.err.println("错误类型: " + e.getClass().getName());
            e.printStackTrace();
            throw new RuntimeException("构建微信支付服务失败：" + e.getMessage(), e);
        }
    }

    @Override
    public BigDecimal total() {
        try {
            // 使用数据库聚合查询统计订单总金额，性能更高
            BigDecimal total = baseMapper.selectTotalAmount();

            if (total == null) {
                total = BigDecimal.ZERO;
            }

            log.info("统计订单总金额完成，总金额：{}", total);
            return total;

        } catch (Exception e) {
            log.error("统计订单总金额失败", e);
            return BigDecimal.ZERO;
        }
    }

    /**
     * 获取Native支付的微信支付配置
     */
    private Config getWxPayConfig(ShopOrder order) throws Exception {
        try {
            final Payment payment = getPayment(order);
            String privateKey;
            String apiclientCert = null;
            String pubKey = null;

            // 初始化证书路径
            if (active.equals("dev")) {
                // 开发环境 - 构建包含租户号的证书路径
                String tenantCertPath = "dev/wechat/" + order.getTenantId();
                String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();

                System.out.println("开发环境证书路径 - 租户ID: " + order.getTenantId());
                System.out.println("开发环境证书路径 - 私钥: " + privateKeyPath);

                privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
                System.out.println("私钥完整路径: " + privateKey);

                // 尝试加载公钥（如果配置了）
                if (StrUtil.isNotBlank(payment.getPubKey()) && StrUtil.isNotBlank(payment.getPubKeyId())) {
                    try {
                        String pubKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getWechatpayCertFile();
                        pubKey = certificateLoader.loadCertificatePath(pubKeyPath);
                        System.out.println("✅ 开发环境公钥加载成功");
                    } catch (Exception e) {
                        System.out.println("⚠️ 开发环境公钥加载失败，将使用自动证书配置: " + e.getMessage());
                    }
                }
            } else {
                // 生产环境 - 从数据库配置的路径加载
                final String certRootPath = certConfig.getCertRootPath();

                System.out.println("生产环境证书路径 - 租户ID: " + order.getTenantId());
                System.out.println("生产环境证书根路径: " + certRootPath);
                System.out.println("私钥文件名: " + payment.getApiclientKey());

                String privateKeyRelativePath = payment.getApiclientKey();

                // 修复路径拼接逻辑：数据库中存储的路径如果已经包含 /file，则直接拼接
                String privateKeyFullPath;
                if (privateKeyRelativePath.startsWith("/file/")) {
                    // 路径已经包含 /file/ 前缀，直接拼接到根路径
                    privateKeyFullPath = certRootPath + privateKeyRelativePath;
                } else if (privateKeyRelativePath.startsWith("file/")) {
                    // 路径包含 file/ 前缀，添加根路径和斜杠
                    privateKeyFullPath = certRootPath + "/" + privateKeyRelativePath;
                } else {
                    // 路径不包含 file 前缀，添加完整的 /file/ 前缀
                    privateKeyFullPath = certRootPath + "/file/" + privateKeyRelativePath;
                }

                System.out.println("私钥完整路径: " + privateKeyFullPath);
                privateKey = certificateLoader.loadCertificatePath(privateKeyFullPath);
                System.out.println("✅ 生产环境私钥加载完成: " + privateKey);

                // 尝试加载公钥（如果配置了）
                if (StrUtil.isNotBlank(payment.getPubKey()) && StrUtil.isNotBlank(payment.getPubKeyId())) {
                    try {
                        String pubKeyRelativePath = payment.getPubKey();
                        System.out.println("数据库中的公钥相对路径: " + pubKeyRelativePath);

                        // 修复公钥路径拼接逻辑，与私钥路径处理保持一致
                        String pubKeyFullPath;
                        if (pubKeyRelativePath.startsWith("/file/")) {
                            // 路径已经包含 /file/ 前缀，直接拼接到根路径
                            pubKeyFullPath = certRootPath + pubKeyRelativePath;
                        } else if (pubKeyRelativePath.startsWith("file/")) {
                            // 路径包含 file/ 前缀，添加根路径和斜杠
                            pubKeyFullPath = certRootPath + "/" + pubKeyRelativePath;
                        } else {
                            // 路径不包含 file 前缀，添加完整的 /file/ 前缀
                            pubKeyFullPath = certRootPath + "/file/" + pubKeyRelativePath;
                        }

                        System.out.println("生产环境公钥完整路径: " + pubKeyFullPath);
                        pubKey = certificateLoader.loadCertificatePath(pubKeyFullPath);
                        System.out.println("✅ 生产环境公钥加载成功");
                    } catch (Exception e) {
                        System.out.println("⚠️ 生产环境公钥加载失败，将使用自动证书配置: " + e.getMessage());
                    }
                }
            }

            // 根据可用的证书类型选择配置方式
            Config config;
            if (pubKey != null && StrUtil.isNotBlank(payment.getPubKeyId())) {
                // 使用RSA公钥配置（推荐方式）
                System.out.println("🔧 使用RSA公钥配置");
                config = new RSAPublicKeyConfig.Builder()
                        .merchantId(payment.getMchId())
                        .privateKeyFromPath(privateKey)
                        .merchantSerialNumber(payment.getMerchantSerialNumber())
                        .publicKeyFromPath(pubKey)
                        .publicKeyId(payment.getPubKeyId())
                        .apiV3Key(payment.getApiKey())
                        .build();
            } else {
                // 使用自动证书配置
                System.out.println("🔧 使用RSA自动证书配置");
                config = new RSAAutoCertificateConfig.Builder()
                        .merchantId(payment.getMchId())
                        .privateKeyFromPath(privateKey)
                        .merchantSerialNumber(payment.getMerchantSerialNumber())
                        .apiV3Key(payment.getApiKey())
                        .build();
            }

            System.out.println("✅ 微信支付配置构建成功");
            return config;

        } catch (Exception e) {
            System.err.println("❌ 构建微信支付服务失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("构建微信支付服务失败：" + e.getMessage(), e);
        }
    }

    @Override
    public ShopOrder getByOrderNo(String orderNo, Integer tenantId) {
        return this.lambdaQuery()
                .eq(ShopOrder::getOrderNo, orderNo)
                .eq(ShopOrder::getTenantId, tenantId)
                .one();
    }

    @Override
    public boolean syncPaymentStatus(String orderNo, Integer paymentStatus, String transactionId, String payTime, Integer tenantId) {
        try {
            // 查询订单
            ShopOrder order = getByOrderNo(orderNo, tenantId);
            if (order == null) {
                log.warn("同步支付状态失败：订单不存在, orderNo={}, tenantId={}", orderNo, tenantId);
                return false;
            }

            // 如果订单已经是支付成功状态，不需要更新
            if (order.getPayStatus() && paymentStatus == 1) {
                log.info("订单已经是支付成功状态，无需更新: orderNo={}", orderNo);
                return true;
            }

            // 更新订单状态
            boolean updated = this.lambdaUpdate()
                    .eq(ShopOrder::getOrderNo, orderNo)
                    .eq(ShopOrder::getTenantId, tenantId)
                    .set(ShopOrder::getPayStatus, paymentStatus == 1)
                    .set(transactionId != null, ShopOrder::getTransactionId, transactionId)
                    .set(payTime != null, ShopOrder::getPayTime, payTime)
                    .set(ShopOrder::getUpdateTime, LocalDateTime.now())
                    .update();

            if (updated) {
                log.info("订单支付状态同步成功: orderNo={}, paymentStatus={}, transactionId={}",
                    orderNo, paymentStatus, transactionId);
            } else {
                log.warn("订单支付状态同步失败: orderNo={}, paymentStatus={}", orderNo, paymentStatus);
            }

            return updated;

        } catch (Exception e) {
            log.error("同步订单支付状态异常: orderNo={}, error={}", orderNo, e.getMessage(), e);
            return false;
        }
    }


}
