package com.ruoyi.database.controller;

import cn.hutool.json.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
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.service.WechatMiniProgramPayService;
import com.ruoyi.database.util.HaiKangApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wxpay")
public class WxPayNotifyController {

    @Autowired
    private WechatMiniProgramPayService wechatPayService;

    @Autowired
    private ParkingBillPaymentInfoService parkingBillPaymentInfoService;

    @Autowired
    private ParkingBillInfoService parkingBillInfoService;

    @Autowired
    private HaiKangApiUtils haiKangApiUtils;


    /**
     * 微信支付结果通知回调
     * 这个接口URL就是在创建订单时设置的 notifyUrl
     */
    @PostMapping("/notify")
    public String handleNotify(@RequestBody String xmlData) {
        try {
            System.out.println("========== 收到支付通知 ==========");
            System.out.println("通知数据: " + xmlData);

            // 1. 获取 wxPayService
            WxPayService wxPayService = wechatPayService.getWxPayService();

            // 2. 使用SDK解析并验证通知数据（SDK会自动验证签名）
            WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);

            // 3. 获取关键业务参数
            String orderId = notifyResult.getOutTradeNo();
            String transactionId = notifyResult.getTransactionId();
            Integer totalFee = notifyResult.getTotalFee();
            String timeEnd = notifyResult.getTimeEnd();

            System.out.println("解析通知数据: orderId=" + orderId +
                    ", transactionId=" + transactionId + ", totalFee=" + totalFee);
            ParkingBillPaymentInfo one = parkingBillPaymentInfoService.lambdaQuery()
                    .eq(ParkingBillPaymentInfo::getOrderId, orderId)
                    .last("limit 1")
                    .one();
            if (one == null) {
                return WxPayNotifyResponse.fail("处理失败");
            }
            one.setPayStatus(1);
            one.setPayTime(timeEnd);
            one.setTransactionId(transactionId);
            boolean b = parkingBillPaymentInfoService.updateById(one);
            if (!b){
                return WxPayNotifyResponse.fail("处理失败");
            }

            ParkingBillInfo parkingBillInfo = parkingBillInfoService.lambdaQuery()
                    .eq(ParkingBillInfo::getBillCode, one.getBillCode())
                    .last("limit 1")
                    .one();
            if (parkingBillInfo == null) {
                return WxPayNotifyResponse.fail("处理失败");
            }
            String notice = haiKangApiUtils.notice(one, parkingBillInfo, 3);
            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 WxPayNotifyResponse.fail("处理失败");
            }
            System.out.println("支付通知处理成功");
            System.out.println("========== 支付通知处理完成 ==========");
            // 7. 返回成功响应（必须返回success）
            return WxPayNotifyResponse.success("OK");

        } catch (Exception e) {
            System.err.println("支付通知处理失败: " + e.getMessage());
            e.printStackTrace();
            return WxPayNotifyResponse.fail("处理失败");
        }
    }
}
