package com.kexue.skills.controller;

import com.kexue.skills.common.CommonResult;
import com.kexue.skills.entity.PaymentOrder;
import com.kexue.skills.service.PayService;
import com.kexue.skills.service.PaymentOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import com.kexue.skills.entity.dto.OrderStatusDto;
import com.kexue.skills.entity.dto.OrderStatusQueryDto;

import java.util.Map;
import java.util.Objects;

/**
 * 支付控制器
 */
@Tag(name = "支付管理 Api")
@RestController
@RequestMapping("/api/pay")
public class PayController {

    private static final Logger logger = LoggerFactory.getLogger(PayController.class);

    @Resource
    private PayService payService;

    @Resource
    private PaymentOrderService paymentOrderService;

    /**
     * 创建微信支付订单
     * @param order 支付订单信息
     * @param request HTTP 请求（用于获取用户 IP）
     * @return 微信支付参数
     */
    @Operation(summary = "创建微信支付订单", description = "创建微信支付订单")
    @PostMapping("/wx/create")
    public CommonResult<Map<String, String>> createWechatPay(@RequestBody PaymentOrder order, HttpServletRequest request) {
        try {
            // 设置支付类型为微信支付（1）
            order.setPayType(1);
            // 创建支付订单
            PaymentOrder createdOrder = paymentOrderService.createPaymentOrder(order);
            // 获取用户真实 IP
            String ipAddress = getUserIpAddress(request);
            // 生成微信支付参数
            Map<String, String> payParams = payService.createWechatPay(createdOrder, ipAddress);
            return CommonResult.success(payParams);
        } catch (IllegalArgumentException e) {
            logger.error("参数错误：{}", e.getMessage());
            return CommonResult.failed(e.getMessage());
        } catch (Exception e) {
            logger.error("创建微信支付订单失败", e);
            return CommonResult.failed("系统繁忙，请稍后重试");
        }
    }
        
    /**
     * 获取用户真实 IP 地址
     */
    private String getUserIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 如果是多代理，取第一个 IP
        if (ip != null && !ip.isEmpty() && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 处理微信支付回调
     * @param request HTTP请求
     * @return 回调响应
     */
    @Operation(summary = "处理微信支付回调", description = "处理微信支付回调")
    @PostMapping("/wx/notify")
    public String handleWechatPayNotify(HttpServletRequest request) {
        return payService.handleWechatPayNotify(request);
    }

    /**
     * 创建支付宝支付订单
     * @param order 支付订单信息
     * @return 支付宝支付表单
     */
    @Operation(summary = "创建支付宝支付订单", description = "创建支付宝支付订单")
    @PostMapping("/alipay/create")
    public CommonResult<String> createAlipay(@RequestBody PaymentOrder order) {
        try {
            // 设置支付类型为支付宝（2）
            order.setPayType(2);
            // 创建支付订单
            PaymentOrder createdOrder = paymentOrderService.createPaymentOrder(order);
            // 生成支付宝支付表单
            String form = payService.createAlipay(createdOrder);

            // 更新订单信息
            createdOrder.setQrCode( form);
            paymentOrderService.update(createdOrder);

            return CommonResult.success(form);
        } catch (Exception e) {
            logger.error("创建支付宝支付订单失败", e);
            return CommonResult.failed("创建支付宝支付订单失败: " + e.getMessage());
        }
    }

    /**
     * 处理支付宝支付回调
     * @param request HTTP请求
     * @return 回调响应
     */
    @Operation(summary = "处理支付宝支付回调", description = "处理支付宝支付回调")
    @PostMapping("/alipay/trade/notify")
    public String handleAlipayNotify(HttpServletRequest request) {
        return payService.handleAlipayNotify(request);
    }

    /**
     * 处理支付宝支付同步回调
     * @param request HTTP请求
     * @return 同步回调响应
     */
    @Operation(summary = "处理支付宝支付同步回调", description = "处理支付宝支付同步回调")
    @GetMapping("/alipay/trade/return")
    public CommonResult<Map<String, Object>> handleAlipayReturn(HttpServletRequest request) {
        Map<String, Object> result = payService.handleAlipayReturn(request);
        if (result.get("success").equals(true)) {
            return CommonResult.success(result);
        } else {
            return CommonResult.failed(result.get("message").toString());
        }
    }

    /**
     * 查询订单状态
     * @param queryDto 查询参数，包含 orderId 或 orderNo
     * @return 订单状态信息
     */
    @Operation(summary = "查询订单状态", description = "根据订单 id 或 orderNo 查询订单状态")
    @PostMapping("/queryOrderStatus")
    public CommonResult<OrderStatusDto> queryOrderStatus(@RequestBody OrderStatusQueryDto queryDto) {
        try {
            // 检查参数是否有效
            if (Objects.isNull(queryDto.getOrderId()) && Objects.isNull(queryDto.getOrderNo())) {
                return CommonResult.failed("请提供 orderId 或 orderNo 参数");
            }
            
            PaymentOrder order = null;
            
            // 根据订单 id 查询
            if (queryDto.getOrderId() != null) {
                order = paymentOrderService.queryById(queryDto.getOrderId());
            }
            // 根据订单号查询
            else if (queryDto.getOrderNo() != null && !queryDto.getOrderNo().trim().isEmpty()) {
                order = paymentOrderService.queryByOrderNo(queryDto.getOrderNo());
            }
            
            if (order == null) {
                return CommonResult.failed("订单不存在");
            }
            
            // 构建响应数据
            OrderStatusDto result = OrderStatusDto.fromPaymentOrder(order);
            
            return CommonResult.success(result);
        } catch (Exception e) {
            logger.error("查询订单状态失败", e);
            return CommonResult.failed("系统繁忙，请稍后重试");
        }
    }
}
