package com.example.demo.controller;

import com.example.demo.model.Payment;
import com.example.demo.model.PaymentStatus;
import com.example.demo.service.PayPalService;
import com.example.demo.service.PaymentService;
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.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * PayPal支付控制器
 * 处理PayPal支付相关的HTTP请求
 */
@RestController
@RequestMapping("/api/payment/paypal")
@Tag(name = "PayPal支付", description = "PayPal支付相关接口")
@CrossOrigin(origins = "*")
public class PayPalController {
    
    private static final Logger logger = LoggerFactory.getLogger(PayPalController.class);
    
    @Autowired(required = false)
    private PayPalService payPalService;
    
    @Autowired
    private PaymentService paymentService;
    
    @Value("${app.frontend-url:https://www.vionow.com}")
    private String frontendUrl;
    
    /**
     * 创建PayPal支付
     * 支持两种模式：
     * 1. 传入 paymentId：使用已有的支付记录
     * 2. 不传入 paymentId：创建新的支付记录
     */
    @PostMapping("/create")
    @Operation(summary = "创建PayPal支付", description = "创建PayPal支付订单并返回支付URL")
    public ResponseEntity<Map<String, Object>> createPayment(@RequestBody Map<String, Object> request) {
        try {
            logger.info("=== 创建PayPal支付请求 ===");
            logger.info("请求参数: {}", request);
            
            if (payPalService == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "PayPal服务未配置");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            Payment payment;
            
            // 检查是否传入了已有的 paymentId
            Object paymentIdObj = request.get("paymentId");
            if (paymentIdObj != null) {
                Long paymentId = Long.valueOf(paymentIdObj.toString());
                logger.info("使用已有的支付记录，paymentId: {}", paymentId);
                
                Optional<Payment> existingPayment = paymentService.findById(paymentId);
                if (existingPayment.isEmpty()) {
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("success", false);
                    errorResponse.put("message", "支付记录不存在");
                    return ResponseEntity.badRequest().body(errorResponse);
                }
                payment = existingPayment.get();
                
                // 检查支付状态，如果已成功则不允许重复创建
                if (payment.getStatus() == PaymentStatus.SUCCESS) {
                    Map<String, Object> errorResponse = new HashMap<>();
                    errorResponse.put("success", false);
                    errorResponse.put("message", "该支付已完成，请勿重复支付");
                    return ResponseEntity.badRequest().body(errorResponse);
                }
            } else {
                // 旧模式：创建新的支付记录
                String username = (String) request.get("username");
                String orderId = (String) request.get("orderId");
                String amount = request.get("amount") != null ? request.get("amount").toString() : null;
                String method = (String) request.get("method");
                String description = (String) request.get("description");
                
                payment = paymentService.createPayment(username, orderId, amount, method, description);
            }
            
            // 调用 PayPal API 创建支付
            String paypalUrl = null;
            String paypalPaymentId = null;
            
            if (payPalService != null) {
                try {
                    Map<String, Object> paypalResult = payPalService.createPayment(payment);
                    if (paypalResult.containsKey("paymentUrl")) {
                        paypalUrl = paypalResult.get("paymentUrl").toString();
                    }
                    if (paypalResult.containsKey("paypalPaymentId")) {
                        paypalPaymentId = paypalResult.get("paypalPaymentId").toString();
                    }
                    logger.info("PayPal API 返回: url={}, paypalId={}", paypalUrl, paypalPaymentId);
                } catch (Exception e) {
                    logger.error("调用 PayPal API 失败: {}", e.getMessage());
                }
            }
            
            // 如果 PayPal API 未配置或调用失败，返回错误
            if (paypalUrl == null || paypalUrl.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "PayPal服务暂不可用，请使用支付宝支付");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 保存 PayPal 的 paymentId 到数据库
            if (paypalPaymentId != null) {
                payment.setExternalTransactionId(paypalPaymentId);
                payment.setPaymentUrl(paypalUrl);
                paymentService.save(payment);
                logger.info("已保存 PayPal paymentId: {} 到支付记录: {}", paypalPaymentId, payment.getId());
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("paymentId", payment.getId());
            response.put("paymentUrl", paypalUrl);
            response.put("externalTransactionId", paypalPaymentId);
            
            logger.info("✅ PayPal支付创建成功: {}", response);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("❌ 创建PayPal支付失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    /**
     * PayPal支付成功回调（用户同意支付后）
     */
    @GetMapping("/success")
    @Operation(summary = "PayPal支付成功回调", description = "用户在PayPal完成支付后的回调")
    public RedirectView paymentSuccess(
            @RequestParam("paymentId") Long paymentId,
            @RequestParam("PayerID") String payerId,
            @RequestParam("token") String token) {
        
        try {
            logger.info("=== PayPal支付成功回调 ===");
            logger.info("Payment ID: {}", paymentId);
            logger.info("Payer ID: {}", payerId);
            logger.info("Token: {}", token);
            
            // 检查PayPal服务是否可用
            if (payPalService == null) {
                logger.error("PayPal服务未配置");
                return new RedirectView(frontendUrl + "/subscription?paymentStatus=error&message=PayPal service not configured");
            }
            
            // 获取支付记录
            Optional<Payment> paymentOpt = paymentService.findById(paymentId);
            if (!paymentOpt.isPresent()) {
                logger.error("支付记录不存在: {}", paymentId);
                return new RedirectView(frontendUrl + "/subscription?paymentStatus=error&message=Payment not found");
            }
            
            Payment payment = paymentOpt.get();
            String paypalPaymentId = payment.getExternalTransactionId();
            
            // 执行PayPal支付
            Map<String, Object> result = payPalService.executePayment(paypalPaymentId, payerId);
            
            if (Boolean.TRUE.equals(result.get("success"))) {
                // 更新支付状态为成功
                String transactionId = (String) result.get("transactionId");
                paymentService.confirmPaymentSuccess(paymentId, transactionId);
                
                logger.info("✅ PayPal支付确认成功");
                
                // 重定向到前端会员订阅页面（支付成功）
                return new RedirectView(frontendUrl + "/subscription?paymentStatus=success&paymentId=" + paymentId);
            } else {
                logger.error("PayPal支付执行失败");
                return new RedirectView(frontendUrl + "/subscription?paymentStatus=error&message=Payment execution failed");
            }
            
        } catch (Exception e) {
            logger.error("❌ PayPal支付成功回调处理失败", e);
            return new RedirectView(frontendUrl + "/subscription?paymentStatus=error&message=" + e.getMessage());
        }
    }
    
    /**
     * PayPal支付取消回调（用户取消支付）
     */
    @GetMapping("/cancel")
    @Operation(summary = "PayPal支付取消回调", description = "用户取消PayPal支付后的回调")
    public RedirectView paymentCancel(@RequestParam("paymentId") Long paymentId) {
        try {
            logger.info("=== PayPal支付取消回调 ===");
            logger.info("Payment ID: {}", paymentId);
            
            // 更新支付状态为取消
            paymentService.updatePaymentStatus(paymentId, PaymentStatus.CANCELLED);
            
            logger.info("✅ PayPal支付已取消");
            
            // 重定向到前端会员订阅页面（支付已取消）
            return new RedirectView(frontendUrl + "/subscription?paymentStatus=cancelled&paymentId=" + paymentId);
            
        } catch (Exception e) {
            logger.error("❌ PayPal支付取消回调处理失败", e);
            return new RedirectView(frontendUrl + "/subscription?paymentStatus=error&message=" + e.getMessage());
        }
    }
    
    /**
     * 查询PayPal支付状态
     */
    @GetMapping("/status/{paymentId}")
    @Operation(summary = "查询PayPal支付状态", description = "查询指定支付的当前状态")
    public ResponseEntity<Map<String, Object>> getPaymentStatus(@PathVariable Long paymentId) {
        try {
            logger.info("=== 查询PayPal支付状态 ===");
            logger.info("Payment ID: {}", paymentId);
            
            Optional<Payment> paymentOpt = paymentService.findById(paymentId);
            if (!paymentOpt.isPresent()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "支付记录不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            Payment payment = paymentOpt.get();
            String paypalPaymentId = payment.getExternalTransactionId();
            
            if (paypalPaymentId == null || paypalPaymentId.isEmpty()) {
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("status", payment.getStatus().name());
                response.put("localStatus", true);
                return ResponseEntity.ok(response);
            }
            
            // 从PayPal查询状态
            Map<String, Object> paypalStatus = payPalService.getPaymentStatus(paypalPaymentId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("localStatus", payment.getStatus().name());
            response.put("paypalStatus", paypalStatus.get("state"));
            response.put("paypalDetails", paypalStatus);
            
            logger.info("✅ 查询成功: {}", response);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("❌ 查询PayPal支付状态失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    /**
     * PayPal退款
     */
    @PostMapping("/refund")
    @Operation(summary = "PayPal退款", description = "对指定支付进行退款")
    public ResponseEntity<Map<String, Object>> refundPayment(@RequestBody Map<String, String> request) {
        try {
            logger.info("=== PayPal退款请求 ===");
            logger.info("请求参数: {}", request);
            
            if (payPalService == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "PayPal服务未配置");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            Long paymentId = Long.parseLong(request.get("paymentId"));
            
            // 获取支付记录
            Optional<Payment> paymentOpt = paymentService.findById(paymentId);
            if (!paymentOpt.isPresent()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "支付记录不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            Payment payment = paymentOpt.get();
            String saleId = payment.getExternalTransactionId();
            
            if (saleId == null || saleId.isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "无法获取交易ID");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
            // 执行退款
            Map<String, Object> result = payPalService.refundPayment(saleId);
            
            if (Boolean.TRUE.equals(result.get("success"))) {
                // 更新支付状态
                paymentService.updatePaymentStatus(paymentId, PaymentStatus.REFUNDED);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("refundId", result.get("refundId"));
                response.put("message", "退款成功");
                
                logger.info("✅ PayPal退款成功");
                
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "退款失败");
                return ResponseEntity.badRequest().body(errorResponse);
            }
            
        } catch (Exception e) {
            logger.error("❌ PayPal退款失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
}
