package com.example.demo.controller;

import com.example.demo.model.Payment;
import com.example.demo.model.PaymentStatus;
import com.example.demo.service.PaymentService;
import com.example.demo.service.AlipayService;
import com.example.demo.service.PayPalService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/payments")
public class PaymentApiController {
    
    private static final Logger logger = LoggerFactory.getLogger(PaymentApiController.class);
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private AlipayService alipayService;
    
    @Autowired
    private PayPalService payPalService;
    
    /**
     * 获取用户的支付记录
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserPayments(
            Authentication authentication,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String search) {
        try {
            List<Payment> payments;
            
            // 检查用户是否已登录
            if (authentication != null && authentication.isAuthenticated()) {
                String username = authentication.getName();
                payments = paymentService.findByUsername(username);
            } else {
                // 未登录用户返回空列表
                payments = new ArrayList<>();
            }
            
            // 简单的筛选逻辑
            if (status != null && !status.isEmpty()) {
                payments = payments.stream()
                    .filter(p -> p.getStatus().name().equals(status))
                    .toList();
            }
            
            if (search != null && !search.isEmpty()) {
                payments = payments.stream()
                    .filter(p -> p.getOrderId().contains(search))
                    .toList();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "获取支付记录成功");
            response.put("data", payments);
            response.put("total", payments.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取支付记录失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取支付记录失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据ID获取支付详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getPaymentById(
            @PathVariable Long id,
            Authentication authentication) {
        try {
            Payment payment = paymentService.findById(id)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(authentication.getName())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限访问此支付记录"));
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取支付详情失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取支付详情失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建支付
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createPayment(
            @RequestBody Map<String, Object> paymentData,
            Authentication authentication) {
        try {
            String username;
            if (authentication != null && authentication.isAuthenticated()) {
                username = authentication.getName();
            } else {
                // 未登录用户使用匿名用户名
                username = "anonymous_" + System.currentTimeMillis();
            }
            
            String orderId = (String) paymentData.get("orderId");
            String amountStr = (String) paymentData.get("amount");
            String method = (String) paymentData.get("method");
            
            if (orderId == null || amountStr == null || method == null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("订单号、金额和支付方式不能为空"));
            }
            
            Payment payment = paymentService.createPayment(username, orderId, amountStr, method);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付创建成功");
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建支付失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建支付失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新支付状态
     */
    @PutMapping("/{id}/status")
    public ResponseEntity<Map<String, Object>> updatePaymentStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusData,
            Authentication authentication) {
        try {
            String status = statusData.get("status");
            if (status == null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("状态不能为空"));
            }
            
            Payment payment = paymentService.findById(id)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(authentication.getName())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限修改此支付记录"));
            }
            
            payment.setStatus(PaymentStatus.valueOf(status));
            paymentService.save(payment);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "状态更新成功");
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新支付状态失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("更新支付状态失败: " + e.getMessage()));
        }
    }
    
    /**
     * 确认支付成功
     */
    @PostMapping("/{id}/success")
    public ResponseEntity<Map<String, Object>> confirmPaymentSuccess(
            @PathVariable Long id,
            @RequestBody Map<String, String> successData,
            Authentication authentication) {
        try {
            String externalTransactionId = successData.get("externalTransactionId");
            
            Payment payment = paymentService.findById(id)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(authentication.getName())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            paymentService.confirmPaymentSuccess(id, externalTransactionId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付确认成功");
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("确认支付成功失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("确认支付成功失败: " + e.getMessage()));
        }
    }
    
    /**
     * 确认支付失败
     */
    @PostMapping("/{id}/failure")
    public ResponseEntity<Map<String, Object>> confirmPaymentFailure(
            @PathVariable Long id,
            @RequestBody Map<String, String> failureData,
            Authentication authentication) {
        try {
            String failureReason = failureData.get("failureReason");
            
            Payment payment = paymentService.findById(id)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(authentication.getName())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            paymentService.confirmPaymentFailure(id, failureReason);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付失败确认成功");
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("确认支付失败失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("确认支付失败失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取支付统计
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getPaymentStats(Authentication authentication) {
        try {
            String username = authentication.getName();
            Map<String, Object> stats = paymentService.getUserPaymentStats(username);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", stats);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取支付统计失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("获取支付统计失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建测试支付记录
     */
    @PostMapping("/create-test")
    public ResponseEntity<Map<String, Object>> createTestPayment(
            @RequestBody Map<String, Object> paymentData,
            Authentication authentication) {
        try {
            String username;
            if (authentication != null && authentication.isAuthenticated()) {
                username = authentication.getName();
            } else {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("请先登录后再创建支付记录"));
            }
            
            String amountStr = (String) paymentData.get("amount");
            String method = (String) paymentData.get("method");
            
            if (amountStr == null || method == null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("金额和支付方式不能为空"));
            }
            
            // 生成测试订单号
            String testOrderId = "TEST_" + System.currentTimeMillis();
            Payment payment = paymentService.createPayment(username, testOrderId, amountStr, method);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "测试支付记录创建成功");
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建测试支付记录失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建测试支付记录失败: " + e.getMessage()));
        }
    }
    
    /**
     * 测试支付完成（用于测试自动创建订单功能）
     */
    @PostMapping("/{id}/test-complete")
    public ResponseEntity<Map<String, Object>> testPaymentComplete(
            @PathVariable Long id,
            Authentication authentication) {
        try {
            Payment payment = paymentService.findById(id)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(authentication.getName())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            // 模拟支付成功
            String mockTransactionId = "TEST_" + System.currentTimeMillis();
            paymentService.confirmPaymentSuccess(id, mockTransactionId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付完成测试成功，订单已自动创建");
            response.put("data", payment);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("测试支付完成失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("测试支付完成失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建支付宝支付
     */
    @PostMapping("/alipay/create")
    public ResponseEntity<Map<String, Object>> createAlipayPayment(
            @RequestBody Map<String, Object> paymentData,
            Authentication authentication) {
        try {
            String username;
            if (authentication != null && authentication.isAuthenticated()) {
                username = authentication.getName();
            } else {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("请先登录后再创建支付"));
            }
            
            Long paymentId = Long.valueOf(paymentData.get("paymentId").toString());
            Payment payment = paymentService.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(username)) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            // 调用支付宝接口创建支付
            String paymentUrl = alipayService.createPayment(payment);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付宝支付创建成功");
            response.put("data", Map.of("paymentUrl", paymentUrl));
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建支付宝支付失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建支付宝支付失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建PayPal支付
     */
    @PostMapping("/paypal/create")
    public ResponseEntity<Map<String, Object>> createPayPalPayment(
            @RequestBody Map<String, Object> paymentData,
            Authentication authentication) {
        try {
            String username;
            if (authentication != null && authentication.isAuthenticated()) {
                username = authentication.getName();
            } else {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("请先登录后再创建支付"));
            }
            
            Long paymentId = Long.valueOf(paymentData.get("paymentId").toString());
            Payment payment = paymentService.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(username)) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            // 调用PayPal接口创建支付
            String paymentUrl = payPalService.createPayment(payment);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "PayPal支付创建成功");
            response.put("data", Map.of("paymentUrl", paymentUrl));
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建PayPal支付失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建PayPal支付失败: " + e.getMessage()));
        }
    }
    
    /**
     * 支付宝异步通知
     */
    @PostMapping("/alipay/notify")
    public ResponseEntity<String> handleAlipayNotify(@RequestParam Map<String, String> params) {
        try {
            logger.info("收到支付宝异步通知：{}", params);
            
            boolean success = alipayService.handleNotify(params);
            
            if (success) {
                return ResponseEntity.ok("success");
            } else {
                return ResponseEntity.ok("fail");
            }
        } catch (Exception e) {
            logger.error("处理支付宝异步通知失败：", e);
            return ResponseEntity.ok("fail");
        }
    }
    
    /**
     * 支付宝同步返回
     */
    @GetMapping("/alipay/return")
    public ResponseEntity<String> handleAlipayReturn(@RequestParam Map<String, String> params) {
        try {
            logger.info("收到支付宝同步返回：{}", params);
            
            boolean success = alipayService.handleReturn(params);
            
            if (success) {
                return ResponseEntity.ok("支付成功，正在跳转...");
            } else {
                return ResponseEntity.ok("支付验证失败");
            }
        } catch (Exception e) {
            logger.error("处理支付宝同步返回失败：", e);
            return ResponseEntity.ok("支付处理异常");
        }
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}
