package com.ruoyi.api;

import com.ruoyi.ai.domain.*;
import com.ruoyi.ai.service.IAiRechargeService;
import com.ruoyi.ai.service.IJinShaService;
import com.ruoyi.ai.service.IKaDaService;
import com.ruoyi.ai.service.IYuZhouService;
import com.ruoyi.ai.service.IVmService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ip.IpUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/pay")
@Api(tags = "支付接口")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class PayController {
    private final IJinShaService jinShaService;
    private final IKaDaService kaDaService;
    private final IAiRechargeService aiRechargeService;
    private final IYuZhouService yuZhouService;
    private final IVmService vmService;

    /**
     * jinsha请求支付
     */
    @GetMapping("/jinsha-pay")
    @ApiOperation("jinsha请求支付")
    public AjaxResult jinShaPay(Long gearId) throws Exception {
        PayResVO payResVO = jinShaService.jinShaPay(gearId);
        return AjaxResult.success(payResVO);
    }

    @PostMapping("/jinsha-callBack")
    @ApiOperation("jinsha支付回调")
    @Anonymous
    public AjaxResult jinShaCallBack(@RequestBody JinShaBodyCall request) {
        AjaxResult ajaxResult = jinShaService.jinShaCall(request);
        return ajaxResult;
    }

    /**
     * kada请求支付
     */
    @GetMapping("/kada-pay")
    @ApiOperation("kada请求支付")
    public AjaxResult kaDaPay(Long gearId) throws Exception {
        PayResVO pay = kaDaService.pay(gearId);
        return AjaxResult.success(pay);
    }

    @PostMapping("/kada-callBack")
    @ApiOperation("kada支付回调")
    @Anonymous
    public AjaxResult kaDaCallBack(@RequestBody KaDaBodyCall req, HttpServletRequest request) throws Exception {
        AjaxResult ajaxResult = kaDaService.callBack(request, req);
        return ajaxResult;
    }

    @GetMapping("/kada-callBack/test")
    @ApiOperation("测试支付回调")
    @Anonymous
    public AjaxResult kaDaCallBackTest(String orderNo) {
        aiRechargeService.addRecharge(orderNo);
        return AjaxResult.success();
    }

    @GetMapping("/yuzhou-pay")
    @ApiOperation("yuzhou请求支付")
    public AjaxResult yuZhouPay(Long gearId) throws Exception {
        PayResVO pay = yuZhouService.pay(gearId);
        return AjaxResult.success(pay);
    }

    @PostMapping("/yuzhou-callBack")
    @ApiOperation("yuzhou支付回调")
    @Anonymous
    public String yuZhouCallBack(@RequestBody Map<String, Object> map) throws Exception {
        String s = yuZhouService.callBack(map);
        return s;
    }

    /**
     * VM请求支付
     */
    @PostMapping("/vm-pay")
    @ApiOperation("VM请求支付")
    public AjaxResult vmPay(@RequestBody VmPayReq req, HttpServletRequest request) throws Exception {
        // 获取用户真实IP地址
        String clientIp = IpUtils.getIpAddr(request);
        PayResVO payResVO = vmService.vmPay(req.getGearId(), req.getVmCardInfo(), clientIp);
        return AjaxResult.success(payResVO);
    }

    @PostMapping("/vm-callBack")
    @ApiOperation("VM支付回调")
    @Anonymous
    public String vmCallBack(HttpServletRequest request) {
        // 记录请求的Content-Type
        String contentType = request.getContentType();

        // 从请求中解析表单参数
        VmCallBackReq req = new VmCallBackReq();

        // 记录所有请求参数用于调试
        java.util.Enumeration<String> paramNames = request.getParameterNames();
        java.util.Map<String, String> allParams = new java.util.HashMap<>();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String paramValue = request.getParameter(paramName);
            allParams.put(paramName, paramValue);
        }
        org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(PayController.class);
        log.info("VM支付回调请求参数: {}, Content-Type: {}", allParams, contentType);

        req.setMchNo(request.getParameter("mchNo"));
        req.setAppId(request.getParameter("appId"));
        req.setMchOrderNo(request.getParameter("mchOrderNo"));
        req.setPayOrderId(request.getParameter("payOrderId"));
        req.setWayCode(request.getParameter("wayCode"));

        // 解析整数类型字段
        String amountStr = request.getParameter("amount");
        if (amountStr != null && !amountStr.isEmpty()) {
            try {
                req.setAmount(Integer.parseInt(amountStr));
            } catch (NumberFormatException e) {
                log.warn("VM支付回调amount解析失败: {}", amountStr);
            }
        }

        req.setCurrency(request.getParameter("currency"));
        req.setIfCode(request.getParameter("ifCode"));
        req.setSubject(request.getParameter("subject"));
        req.setBody(request.getParameter("body"));
        req.setClientIp(request.getParameter("clientIp"));

        // 解析订单状态（文档字段名：state）
        String stateStr = request.getParameter("state");
        if (stateStr != null && !stateStr.isEmpty()) {
            try {
                req.setState(Integer.parseInt(stateStr));
            } catch (NumberFormatException e) {
                log.warn("VM支付回调state解析失败: {}", stateStr);
            }
        }

        req.setChannelOrderNo(request.getParameter("channelOrderNo"));
        req.setErrCode(request.getParameter("errCode"));
        req.setErrMsg(request.getParameter("errMsg"));
        req.setExtParam(request.getParameter("extParam"));

        // 解析时间戳：createdAt、successTime、reqTime（文档字段名）
        String createdAtStr = request.getParameter("createdAt");
        if (createdAtStr != null && !createdAtStr.isEmpty()) {
            try {
                req.setCreatedAt(Long.parseLong(createdAtStr));
            } catch (NumberFormatException e) {
                log.warn("VM支付回调createdAt解析失败: {}", createdAtStr);
            }
        }
        String successTimeStr = request.getParameter("successTime");
        if (successTimeStr != null && !successTimeStr.isEmpty()) {
            try {
                req.setSuccessTime(Long.parseLong(successTimeStr));
            } catch (NumberFormatException e) {
                log.warn("VM支付回调successTime解析失败: {}", successTimeStr);
            }
        }
        String reqTimeStr = request.getParameter("reqTime");
        if (reqTimeStr != null && !reqTimeStr.isEmpty()) {
            try {
                req.setReqTime(Long.parseLong(reqTimeStr));
            } catch (NumberFormatException e) {
                log.warn("VM支付回调reqTime解析失败: {}", reqTimeStr);
            }
        }

        req.setSign(request.getParameter("sign"));
        req.setSignType(request.getParameter("signType"));

        log.info("VM支付回调解析后的对象: mchOrderNo={}, state={}, sign={}",
                req.getMchOrderNo(), req.getState(), req.getSign());

        return vmService.vmCallBack(req);
    }

}
