package com.ruoyi.database.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.config.AlipayRYConfig;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
public class AlipayNotifyController {

    private final AlipayRYConfig alipayConfig;
    // 假设你有一个处理订单业务的服务
    // private final OrderService orderService;

    public AlipayNotifyController(AlipayRYConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    @PostMapping("/notify")
    public String handleNotify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        // 1. 将异步通知的参数转换成一个Map
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        try {
            // 2. 验证签名（非常重要！确保请求来自支付宝）
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    alipayConfig.alipayPublicKey,
                    "UTF-8",
                    "RSA2"
            );

            if (!signVerified) {
                // 签名验证失败，记录日志并拒绝
                System.err.println("支付宝异步通知签名验证失败");
                return "failure";
            }

            // 3. 签名验证通过，处理业务逻辑
            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no"); // 你的商户订单号
            String tradeNo = params.get("trade_no"); // 支付宝交易号

            // 4. 判断交易状态
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISH".equals(tradeStatus)) {
                // 支付成功

                // 4.1 幂等性处理：查询本地订单是否已处理，避免重复通知导致业务重复执行[citation:5]
                // if (orderService.isOrderPaid(outTradeNo)) {
                //     return "success";
                // }

                // 4.2 校验金额（重要！防止金额被篡改）[citation:5]
                // String totalAmount = params.get("total_amount");
                // if (!orderService.verifyOrderAmount(outTradeNo, totalAmount)) {
                //     return "failure";
                // }

                // 4.3 更新本地订单状态为已支付
                // orderService.updateOrderToPaid(outTradeNo, tradeNo);
                System.out.println("订单支付成功: " + outTradeNo + ", 支付宝交易号: " + tradeNo);
            }

            // 5. 处理成功，返回 'success' 字符串给支付宝，支付宝将停止重复通知[citation:5]
            return "success";
        } catch (Exception e) {
            System.err.println("处理支付宝异步通知异常: " + e.getMessage());
            return "failure";
        }
    }
}