package com.ruoyi.database.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.config.AlipayRYConfig;
import com.ruoyi.database.domain.ParkingBillInfo;
import com.ruoyi.database.domain.ParkingBillPaymentInfo;
import com.ruoyi.database.service.ParkingBillInfoService;
import com.ruoyi.database.service.ParkingBillPaymentInfoService;
import com.ruoyi.database.util.HaiKangApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
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;


    @Autowired
    private ParkingBillPaymentInfoService parkingBillPaymentInfoService;

    @Autowired
    private ParkingBillInfoService parkingBillInfoService;

    @Autowired
    private HaiKangApiUtils haiKangApiUtils;



    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"); // 支付宝交易号
            String gmtPayment = params.get("gmt_payment"); // 支付宝交易号

            // 4. 判断交易状态
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISH".equals(tradeStatus)) {
                // 支付成功
                ParkingBillPaymentInfo one = parkingBillPaymentInfoService.lambdaQuery()
                        .eq(ParkingBillPaymentInfo::getOrderId, outTradeNo)
                        .last("limit 1")
                        .one();
                if (one == null) {
                    return "failure";
                }
                one.setPayStatus(1);
                one.setPayTime(gmtPayment);
                one.setTransactionId(tradeNo);
                boolean b = parkingBillPaymentInfoService.updateById(one);
                if (!b){
                    return "failure";
                }
                ParkingBillInfo parkingBillInfo = parkingBillInfoService.lambdaQuery()
                        .eq(ParkingBillInfo::getBillCode, one.getBillCode())
                        .last("limit 1")
                        .one();
                if (parkingBillInfo == null) {
                    return "failure";
                }
                String notice = haiKangApiUtils.notice(one, parkingBillInfo, 2);
                JSONObject jsonObject = new JSONObject(notice);
                String msg = jsonObject.getStr("msg");
                if ("SUCCESS".equals(msg)) {
                    parkingBillInfo.setIsNotify(1);
                }
                parkingBillInfo.setIsPay(1);
                boolean b1 = parkingBillInfoService.updateById(parkingBillInfo);
                if (!b1) {
                    return "failure";
                }
                System.out.println("订单支付成功: " + outTradeNo + ", 支付宝交易号: " + tradeNo);
            }
            // 5. 处理成功，返回 'success' 字符串给支付宝，支付宝将停止重复通知[citation:5]
            return "success";
        } catch (Exception e) {
            System.err.println("处理支付宝异步通知异常: " + e.getMessage());
            return "failure";
        }
    }
}