package com.kexue.skills.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.kexue.skills.common.util.HttpUtil;
import com.kexue.skills.config.PaymentConfig;
import com.kexue.skills.entity.PaymentOrder;
import com.kexue.skills.service.PayService;
import com.kexue.skills.service.PaymentOrderService;
import com.kexue.skills.service.AccountService;
import com.kexue.skills.service.PackageConfigService;
import com.kexue.skills.entity.PackageConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.http.HttpClient;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.*;
import java.math.BigDecimal;

/**
 * 支付服务实现类
 */
@Service("payService")
public class PayServiceImpl implements PayService {

    private static final Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
    
    // 单例 HTTP 客户端，提升性能
    private static final HttpClient HTTP_CLIENT = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .build();
    
    // 微信支付下单 URL
    private static final String WECHAT_PAY_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    
    // 最大金额限制（元）
    private static final BigDecimal MAX_AMOUNT = new BigDecimal("100000");
    
    // 最小金额限制（元）
    private static final BigDecimal MIN_AMOUNT = new BigDecimal("0.01");
    
    // 商品描述最大长度（字节）
    private static final int MAX_BODY_LENGTH = 128;

    @Resource
    private PaymentConfig paymentConfig;

    @Resource
    private PaymentOrderService paymentOrderService;

    @Resource
    private AccountService accountService;

    @Resource
    private PackageConfigService packageConfigService;

    /**
     * 生成随机字符串
     * @return 随机字符串
     */
    private String generateNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成MD5签名
     * @param params 参数
     * @param key 密钥
     * @return 签名
     */
    private String generateSignature(Map<String, String> params, String key) {
        // 排序参数
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        // 构建签名字符串
        StringBuilder sb = new StringBuilder();
        for (String k : keys) {
            String v = params.get(k);
            if (v != null && !v.isEmpty()) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        sb.append("key=").append(key);
        
        // 打印签名字符串（注意：生产环境应移除）
        logger.info("生成签名的字符串: {}", sb.toString());
        logger.info("使用的密钥: {}", key);

        // 生成MD5
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(sb.toString().getBytes("UTF-8"));
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String hex = Integer.toHexString(b & 0xFF);
                if (hex.length() == 1) {
                    result.append("0");
                }
                result.append(hex);
            }
            String signature = result.toString().toUpperCase();
            logger.info("生成的签名: {}", signature);
            return signature;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            logger.error("生成签名失败", e);
            throw new RuntimeException("生成签名失败", e);
        }
    }

    /**
     * 将Map转换为XML
     * @param params 参数
     * @return XML字符串
     */
    private String mapToXml(Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append("<").append(entry.getKey()).append("><![CDATA[")
              .append(entry.getValue())
              .append("]]></").append(entry.getKey()).append(">");
        }
        sb.append("</xml>");
        String xml = sb.toString();
        logger.info("生成的XML: {}", xml);
        return xml;
    }

    /**
     * 将XML转换为Map
     * @param xml XML字符串
     * @return Map
     */
    private Map<String, String> xmlToMap(String xml) {
        Map<String, String> map = new HashMap<>();
        try {
            // 使用更健壮的XML解析方法
            xml = xml.trim();
            if (!xml.startsWith("<xml>") || !xml.endsWith("</xml>")) {
                throw new RuntimeException("无效的XML格式");
            }
            
            // 移除xml标签
            String content = xml.substring(5, xml.length() - 6).trim();
            
            // 按标签分割
            int pos = 0;
            while (pos < content.length()) {
                // 找到开始标签
                int startTagStart = content.indexOf('<', pos);
                if (startTagStart == -1) break;
                int startTagEnd = content.indexOf('>', startTagStart);
                if (startTagEnd == -1) break;
                
                String tagName = content.substring(startTagStart + 1, startTagEnd).trim();
                
                // 找到结束标签
                int endTagStart = content.indexOf("</" + tagName + ">", startTagEnd);
                if (endTagStart == -1) break;
                
                String value = content.substring(startTagEnd + 1, endTagStart).trim();
                
                // 处理CDATA标签
                if (value.startsWith("<![CDATA[") && value.endsWith("]]>") ) {
                    value = value.substring(9, value.length() - 3).trim();
                }
                
                map.put(tagName, value);
                pos = endTagStart + tagName.length() + 3;
            }
            
            logger.info("XML解析结果: {}", map);
        } catch (Exception e) {
            logger.error("XML解析失败: {}", xml, e);
            throw new RuntimeException("XML解析失败", e);
        }
        return map;
    }

    /**
     * 创建微信支付订单
     * @param order 支付订单信息
     * @param ipAddress 用户真实 IP 地址（从 Controller 传入）
     * @return 微信支付参数
     * @throws IllegalArgumentException 参数错误时抛出
     * @throws RuntimeException 网络异常或微信侧错误时抛出
     */
    @Override
    public Map<String, String> createWechatPay(PaymentOrder order, String ipAddress) {
        // 1. 参数校验
        validatePaymentOrder(order);
        
        try {
            // 2. 构建微信支付参数
            Map<String, String> params = buildWechatPayParams(order, ipAddress);
            
            // 3. 生成签名并构建 XML
            String sign = generateSignature(params, paymentConfig.getWechat().getMchKey());
            params.put("sign", sign);
            
            String xml = mapToXml(params);
            logRequest(xml);
            
            // 4. 发送请求到微信支付接口
            String xmlResult = sendWechatRequest(xml);
            
            // 5. 解析并处理响应
            return processWechatResponse(xmlResult, order);
            
        } catch (IllegalArgumentException e) {
            logger.error("参数校验失败：{}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("创建微信支付订单失败", e);
            throw new RuntimeException("系统繁忙，请稍后重试", e);
        }
    }
    
    /**
     * 校验支付订单参数
     */
    private void validatePaymentOrder(PaymentOrder order) {
        if (order == null) {
            throw new IllegalArgumentException("支付订单不能为空");
        }
        
        // 校验金额
        if (order.getAmount() == null) {
            throw new IllegalArgumentException("支付金额不能为空");
        }
        if (order.getAmount().compareTo(MIN_AMOUNT) < 0) {
            throw new IllegalArgumentException("支付金额不能小于 0.01 元");
        }
        if (order.getAmount().compareTo(MAX_AMOUNT) > 0) {
            throw new IllegalArgumentException("单笔支付金额不能超过 10 万元");
        }
        
        // 校验订单号
        if (order.getOrderNo() == null || order.getOrderNo().trim().isEmpty()) {
            throw new IllegalArgumentException("订单号不能为空");
        }
        if (order.getOrderNo().length() > 32) {
            throw new IllegalArgumentException("订单号长度不能超过 32 位");
        }
        if (!order.getOrderNo().matches("^[a-zA-Z0-9_]+$")) {
            throw new IllegalArgumentException("订单号只能包含字母、数字和下划线");
        }
        
        // 校验商品名称
        if (order.getProductName() == null || order.getProductName().trim().isEmpty()) {
            throw new IllegalArgumentException("商品名称不能为空");
        }
    }
    
    /**
     * 构建微信支付请求参数
     */
    private Map<String, String> buildWechatPayParams(PaymentOrder order, String ipAddress) {
        Map<String, String> params = new HashMap<>();
        
        // 应用ID
        String appId = paymentConfig.getWechat().getAppId();
        logger.info("使用的appId: {}", appId);
        params.put("appid", appId);
        
        // 商户号
        String mchId = paymentConfig.getWechat().getMchId();
        logger.info("使用的mchId: {}", mchId);
        params.put("mch_id", mchId);
        
        // 随机字符串
        String nonceStr = generateNonceStr();
        logger.info("生成的nonce_str: {}", nonceStr);
        params.put("nonce_str", nonceStr);

        params.put("sign_type", "MD5");
        
        // 商品描述
        String body = limitBodyLength(order.getProductName());
        logger.info("商品描述: {}", body);
        params.put("body", body);
        
        // 商户订单号
        String outTradeNo = order.getOrderNo();
        logger.info("商户订单号: {}", outTradeNo);
        params.put("out_trade_no", outTradeNo);
        
        // 金额转换：元转分
        BigDecimal totalFee = order.getAmount()
                .multiply(BigDecimal.valueOf(100))
                .setScale(0, BigDecimal.ROUND_HALF_UP);
        String totalFeeStr = String.valueOf(totalFee.intValue());
        logger.info("计算的 total_fee: {} 分", totalFeeStr);
        params.put("total_fee", totalFeeStr);
        
        // 使用传入的 IP 地址，如果为空则使用默认值
        String ip = ipAddress != null ? ipAddress : "127.0.0.1";
        // 转换IPv6地址为IPv4
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }
        // 确保IP地址格式正确
        ip = ip.trim();
        logger.info("使用的IP地址: {}", ip);
        params.put("spbill_create_ip", ip);
        
        // 使用配置的回调地址
        String notifyUrl = paymentConfig.getWechat().getNotifyUrl();
        // 确保回调地址格式正确
        notifyUrl = notifyUrl.trim();
        logger.info("使用的回调地址: {}", notifyUrl);
        params.put("notify_url", notifyUrl);
        
        // 交易类型
        params.put("trade_type", "NATIVE");
        
        // 商品ID（NATIVE支付必传）
        params.put("product_id", order.getOrderNo());
        
        // 打印构建的参数
        logger.info("构建的微信支付参数: {}", params);
        
        return params;
    }
    
    /**
     * 限制商品描述长度（最多 128 字节）
     */
    private String limitBodyLength(String body) {
        if (body == null) {
            return "";
        }
        try {
            // 移除特殊字符，只保留中文、英文、数字和常见标点
            body = body.replaceAll("[^\u4e00-\u9fa5a-zA-Z0-9\\s,.!？！，。]", "");
            
            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
            if (bytes.length <= MAX_BODY_LENGTH) {
                return body;
            }
            // 截断并添加省略号
            String truncated = new String(bytes, 0, Math.min(MAX_BODY_LENGTH - 3, bytes.length), StandardCharsets.UTF_8);
            return truncated + "...";
        } catch (Exception e) {
            logger.warn("商品描述编码失败，使用默认值", e);
            return body.length() > 60 ? body.substring(0, 60) + "..." : body;
        }
    }
    
    /**
     * 记录请求日志（敏感信息脱敏）
     */
    private void logRequest(String xml) {
        if (logger.isDebugEnabled()) {
            logger.debug("微信支付请求 XML: {}", maskSensitiveInfo(xml));
        }
        logger.info("开始发送微信支付请求到：{}", WECHAT_PAY_URL);
    }
    
    /**
     * 脱敏敏感信息
     */
    private String maskSensitiveInfo(String xml) {
        return xml.replaceAll("(<mch_key><!\\[CDATA\\[)(.*?)(]]></mch_key>)", "$1***$3")
                  .replaceAll("(<sign><!\\[CDATA\\[)(.*?)(]]></sign>)", "$1***$3");
    }
    
    /**
     * 发送微信支付请求
     */
    private String sendWechatRequest(String xml) throws Exception {
        logger.info("请求参数：appId={}, mchId={}", 
                paymentConfig.getWechat().getAppId(), 
                paymentConfig.getWechat().getMchId());
        
        String xmlResult = HttpUtil.postWithClient(WECHAT_PAY_URL, xml, HTTP_CLIENT);
        
        if (xmlResult == null || xmlResult.trim().isEmpty()) {
            logger.error("微信支付接口返回空响应");
            throw new RuntimeException("微信支付接口返回空响应");
        }
        
        logger.info("微信支付接口返回 XML: {}", xmlResult);
        return xmlResult;
    }
    
    /**
     * 处理微信支付响应
     */
    private Map<String, String> processWechatResponse(String xmlResult, PaymentOrder order) {
        try {
            Map<String, String> result = xmlToMap(xmlResult);
            logger.info("解析后的微信支付响应：{}", result);
            
            String returnCode = result.get("return_code");
            String resultCode = result.get("result_code");
            String returnMsg = result.get("return_msg");
            String errCode = result.get("err_code");
            String errCodeDes = result.get("err_code_des");
            
            logger.info("微信支付返回码：return_code={}, result_code={}, return_msg={}, err_code={}, err_code_des={}", 
                    returnCode, resultCode, returnMsg, errCode, errCodeDes);
            
            // 检查通信标识
            if (!"SUCCESS".equals(returnCode)) {
                String errorMsg = "通信失败：" + (returnMsg != null ? returnMsg : "未知错误");
                logger.error(errorMsg);
                throw new RuntimeException(errorMsg);
            }
            
            // 检查业务结果
            if (!"SUCCESS".equals(resultCode)) {
                String errorMsg = returnMsg != null ? returnMsg : "未知错误";
                if (errCodeDes != null) {
                    errorMsg += " (" + errCodeDes + ")";
                }
                logger.error("微信支付下单失败：err_code={}, error_msg={}", errCode, errorMsg);
                throw new RuntimeException("支付下单失败：" + errorMsg);
            }
            
            // 保存微信支付二维码URL到订单
            String codeUrl = result.get("code_url");
            order.setCodeUrl(codeUrl);
            order.setChannelOrderNo(result.get("order_no"));
            paymentOrderService.update(order);

            // 返回成功结果
            Map<String, String> payParams = new HashMap<>();
            payParams.put("code_url", codeUrl);
            payParams.put("order_no", order.getOrderNo());
            return payParams;
            
        } catch (IllegalArgumentException e) {
            throw e;
        } catch (Exception e) {
            logger.error("解析微信支付响应失败", e);
            throw new RuntimeException("解析响应失败：" + e.getMessage(), e);
        }
    }

    /**
     * 处理微信支付回调
     * @param request HTTP请求
     * @return 回调响应
     */
    @Override
    public String handleWechatPayNotify(HttpServletRequest request) {
        BufferedReader reader = null;
        try {
            // 读取回调数据
            InputStream inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String xmlData = sb.toString();

            // 解析XML
            Map<String, String> params = xmlToMap(xmlData);

            logger.info("微信支付回调数据：{}", params);

            // 验证签名
            String sign = params.get("sign");
            if (sign == null) {
                logger.error("微信支付回调签名为空");
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名为空]]></return_msg></xml>";
            }
            params.remove("sign");
            String expectedSign = generateSignature(params, paymentConfig.getWechat().getMchKey());

            if (!sign.equals(expectedSign)) {
                logger.error("微信支付回调签名验证失败");
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名验证失败]]></return_msg></xml>";
            }

            // 处理支付结果
            if ("SUCCESS".equals(params.get("return_code")) && "SUCCESS".equals(params.get("result_code"))) {
                String orderNo = params.get("out_trade_no");
                String transactionId = params.get("transaction_id");

                // 更新支付订单状态
                if (orderNo != null) {
                    PaymentOrder order = paymentOrderService.queryByOrderNo(orderNo);
                    if (order != null) {
                        paymentOrderService.updateStatus(order.getOrderId(), 2, transactionId);
                        
                        // 更新账户余额并添加交易记录
                        try {
                            // 增加账户余额（充值）
                            accountService.addBalance(
                                    order.getUserId(),
                                    order.getAmount(),
                                    true, // 可提现
                                    transactionId,
                                    order.getBusinessId(),
                                    "recharge",
                                    "微信支付充值"
                            );
                            logger.info("微信支付回调：更新账户余额成功，userId={}, amount={}, actualAmount={}", order.getUserId(), order.getAmount(), order.getAmount());
                        } catch (Exception e) {
                            logger.error("微信支付回调：更新账户余额失败", e);
                            // 继续处理，不影响回调响应
                        }
                    }
                }

                return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            } else {
                logger.error("微信支付回调失败: {}", params.get("return_msg"));
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>";
            }
        } catch (Exception e) {
            logger.error("处理微信支付回调失败", e);
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>";
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("关闭流失败", e);
                }
            }
        }
    }

    /**
     * 创建支付宝支付订单
     * @param order 支付订单信息
     * @return 支付宝支付表单
     */
    @Override
    public String createAlipay(PaymentOrder order) {
        try {
            // 初始化支付宝客户端
            AlipayClient alipayClient = new DefaultAlipayClient(
                    paymentConfig.getAlipay().getGatewayUrl(),
                    paymentConfig.getAlipay().getAppId(),
                    paymentConfig.getAlipay().getPrivateKey(),
                    "JSON",
                    paymentConfig.getAlipay().getCharset(),
                    paymentConfig.getAlipay().getPublicKey(),
                    paymentConfig.getAlipay().getSignType());

            // 创建支付请求
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setNotifyUrl(paymentConfig.getAlipay().getNotifyUrl());
            request.setReturnUrl(paymentConfig.getAlipay().getReturnUrl());

            // 构建请求参数
            Map<String, Object> bizContent = new HashMap<>();
            bizContent.put("out_trade_no", order.getOrderNo());
            bizContent.put("total_amount", order.getAmount().toString());
            bizContent.put("subject", order.getProductName());
            bizContent.put("businessId", order.getBusinessId());
            bizContent.put("body", order.getProductDesc());
            bizContent.put("timeout_express", "30m");
            bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

            request.setBizContent(com.alibaba.fastjson.JSON.toJSONString(bizContent));

            // 生成支付表单
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                String htmlForm = response.getBody();
                // 保存支付宝支付HTML内容到订单
                order.setQrCode(htmlForm);
                paymentOrderService.update(order);
                return htmlForm;
            } else {
                logger.error("支付宝支付下单失败: {}", response.getMsg());
                throw new RuntimeException("支付宝支付下单失败: " + response.getMsg());
            }
        } catch (AlipayApiException e) {
            logger.error("创建支付宝支付订单失败", e);
            throw new RuntimeException("创建支付宝支付订单失败", e);
        }
    }

    /**
     * 处理支付宝支付回调
     * @param request HTTP请求
     * @return 回调响应
     */
    @Override
    public String handleAlipayNotify(HttpServletRequest request) {
        try {
            // 获取回调参数
            Map<String, String> params = new HashMap<>();
            request.getParameterMap().forEach((key, values) -> {
                if (values != null && values.length > 0) {
                    params.put(key, values[0]);
                }
            });

            logger.info("支付宝支付回调参数: {}", params);

            // 初始化支付宝客户端
            AlipayClient alipayClient = new DefaultAlipayClient(
                    paymentConfig.getAlipay().getGatewayUrl(),
                    paymentConfig.getAlipay().getAppId(),
                    paymentConfig.getAlipay().getPrivateKey(),
                    "JSON",
                    paymentConfig.getAlipay().getCharset(),
                    paymentConfig.getAlipay().getPublicKey(),
                    paymentConfig.getAlipay().getSignType());

            // 验证签名
            boolean signVerified = com.alipay.api.internal.util.AlipaySignature.rsaCheckV1(
                    params, paymentConfig.getAlipay().getPublicKey(),
                    paymentConfig.getAlipay().getCharset(),
                    paymentConfig.getAlipay().getSignType());

            if (!signVerified) {
                logger.error("支付宝支付回调签名验证失败");
                return "failure";
            }

            // 处理支付结果
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                String orderNo = params.get("out_trade_no");
                String transactionId = params.get("trade_no");

                // 更新支付订单状态
                if (orderNo != null) {
                    PaymentOrder order = paymentOrderService.queryByOrderNo(orderNo);
                    if (order != null) {
                        paymentOrderService.updateStatus(order.getOrderId(), 2, transactionId);
                        
                        // 更新账户余额并添加交易记录
                        try {
                            // 增加账户余额（充值）
                            accountService.addBalance(
                                    order.getUserId(),
                                    order.getAmount(),
                                    true, // 可提现
                                    transactionId,
                                    order.getBusinessId(),
                                    "recharge",
                                    "支付宝支付充值"
                            );
                            logger.info("支付宝支付回调：更新账户余额成功，userId={}, amount={}, actualAmount={}", order.getUserId(), order.getAmount(), order.getAmount());
                        } catch (Exception e) {
                            logger.error("支付宝支付回调：更新账户余额失败", e);
                            // 继续处理，不影响回调响应
                        }
                    }
                }

                return "success";
            } else {
                logger.error("支付宝支付回调失败: {}", tradeStatus);
                return "failure";
            }
        } catch (Exception e) {
            logger.error("处理支付宝支付回调失败", e);
            return "failure";
        }
    }

    /**
     * 处理支付宝支付同步回调
     * @param request HTTP请求
     * @return 同步回调响应
     */
    @Override
    public Map<String, Object> handleAlipayReturn(HttpServletRequest request) {
        try {
            // 获取回调参数
            Map<String, String> params = new HashMap<>();
            request.getParameterMap().forEach((key, values) -> {
                params.put(key, values[0]);
            });

            // 初始化支付宝客户端
            AlipayClient alipayClient = new DefaultAlipayClient(
                    paymentConfig.getAlipay().getGatewayUrl(),
                    paymentConfig.getAlipay().getAppId(),
                    paymentConfig.getAlipay().getPrivateKey(),
                    "JSON",
                    paymentConfig.getAlipay().getCharset(),
                    paymentConfig.getAlipay().getPublicKey(),
                    paymentConfig.getAlipay().getSignType());

            // 验证签名
            boolean signVerified = com.alipay.api.internal.util.AlipaySignature.rsaCheckV1(
                    params, paymentConfig.getAlipay().getPublicKey(),
                    paymentConfig.getAlipay().getCharset(),
                    paymentConfig.getAlipay().getSignType());

            Map<String, Object> result = new HashMap<>();
            if (signVerified) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    result.put("success", true);
                    result.put("orderNo", params.get("out_trade_no"));
                    result.put("message", "支付成功");
                } else {
                    result.put("success", false);
                    result.put("message", "支付失败");
                }
            } else {
                result.put("success", false);
                result.put("message", "签名验证失败");
            }
            return result;
        } catch (Exception e) {
            logger.error("处理支付宝支付同步回调失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "处理失败");
            return result;
        }
    }


}
