package com.example.demo.controller;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;

import com.example.demo.model.Payment;
import com.example.demo.model.PaymentMethod;
import com.example.demo.model.PaymentStatus;
import com.example.demo.model.User;
import com.example.demo.model.UserMembership;
import com.example.demo.model.MembershipLevel;
import com.example.demo.repository.PaymentRepository;
import com.example.demo.repository.UserMembershipRepository;
import com.example.demo.repository.MembershipLevelRepository;
import com.example.demo.service.AlipayService;
import com.example.demo.service.LuluPayService;
import com.example.demo.service.OrderService;
import com.example.demo.service.PaymentService;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtils;

@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 LuluPayService luluPayService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private OrderService orderService;
    
    @Autowired
    private PaymentRepository paymentRepository;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private UserMembershipRepository userMembershipRepository;
    
    @Autowired
    private MembershipLevelRepository membershipLevelRepository;

    
    /**
     * 获取用户的支付记录
     */
    @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 = paymentData.get("amount") != null ? paymentData.get("amount").toString() : null;
            String method = (String) paymentData.get("method");
            String description = (String) paymentData.get("description");
            
            if (orderId == null || amountStr == null || method == null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("订单号、金额和支付方式不能为空"));
            }
            
            Payment payment = paymentService.createPayment(username, orderId, amountStr, method, description);
            
            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()));
        }
    }
    
    /**
     * 更新支付方式和描述（用于切换支付方式时）
     */
    @PutMapping("/{id}/method")
    public ResponseEntity<Map<String, Object>> updatePaymentMethod(
            @PathVariable Long id,
            @RequestBody Map<String, String> methodData,
            Authentication authentication) {
        try {
            String method = methodData.get("method");
            String description = methodData.get("description");
            
            if (method == null) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("支付方式不能为空"));
            }
            
            // 调用Service层方法（带事务）
            Payment payment = paymentService.updatePaymentMethod(id, method, description, authentication.getName());
            
            logger.info("支付方式更新成功: paymentId={}, method={}, description={}", id, method, description);
            
            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 = paymentData.get("amount") != null ? paymentData.get("amount").toString() : null;
            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 transactionId = "TXN_" + System.currentTimeMillis();
            paymentService.confirmPaymentSuccess(id, transactionId);
            
            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("/subscription/info")
    public ResponseEntity<Map<String, Object>> getUserSubscriptionInfo(
            Authentication authentication,
            jakarta.servlet.http.HttpServletRequest request) {
        try {
            if (authentication == null || !authentication.isAuthenticated()) {
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("请先登录"));
            }
            
            User user = null;
            String username = authentication.getName();

            try {
                // Principal 现在是用户名字符串，直接通过用户名查找
                user = userService.findByUsernameOrNull(username);

                // 如果通过用户名找不到，尝试从JWT token中获取用户ID
                if (user == null) {
                    String authHeader = request.getHeader("Authorization");
                    if (authHeader != null && authHeader.startsWith("Bearer ")) {
                        String token = authHeader.substring(7);
                        try {
                            Long userId = jwtUtils.getUserIdFromToken(token);
                            if (userId != null) {
                                logger.warn("通过用户名未找到用户，尝试通过用户ID查找: {}", userId);
                                user = userService.findById(userId);
                            }
                        } catch (Exception e) {
                            logger.warn("从token获取用户ID失败: {}", e.getMessage());
                        }
                    }
                }

                // 如果通过用户名找不到，尝试通过邮箱查找（兼容邮箱登录的情况）
                if (user == null && username.contains("@")) {
                    logger.warn("通过用户名未找到用户，尝试通过邮箱查找: {}", username);
                    user = userService.findByEmailOrNull(username);
                }
            } catch (Exception e) {
                logger.error("查找用户失败: {}", e.getMessage(), e);
            }
            
            if (user == null) {
                logger.error("用户不存在: {}", username);
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("用户不存在"));
            }
            
            // 获取用户最近一次成功的支付记录（包括所有充值记录，不仅仅是订阅）
            List<Payment> allPayments;
            try {
                // 获取所有成功支付的记录，按支付时间倒序
                allPayments = paymentRepository.findByUserIdOrderByCreatedAtDesc(user.getId())
                    .stream()
                    .filter(p -> p.getStatus() == PaymentStatus.SUCCESS)
                    .sorted((p1, p2) -> {
                        LocalDateTime time1 = p1.getPaidAt() != null ? p1.getPaidAt() : p1.getCreatedAt();
                        LocalDateTime time2 = p2.getPaidAt() != null ? p2.getPaidAt() : p2.getCreatedAt();
                        return time2.compareTo(time1); // 倒序
                    })
                    .collect(java.util.stream.Collectors.toList());
            } catch (Exception e) {
                logger.error("查询支付记录失败，用户ID: {}", user.getId(), e);
                // 如果查询失败，使用空列表
                allPayments = new ArrayList<>();
            }
            
            Map<String, Object> subscriptionInfo = new HashMap<>();
            
            // 默认值
            String currentPlan = null;
            String expiryTime = "永久";
            LocalDateTime paidAt = null;
            
            // 优先从UserMembership表获取用户的实际会员等级（按到期时间降序，返回最新的）
            try {
                java.util.Optional<UserMembership> membershipOpt = userMembershipRepository.findFirstByUserIdAndStatusOrderByEndDateDesc(user.getId(), "ACTIVE");
                if (membershipOpt.isPresent()) {
                    UserMembership membership = membershipOpt.get();
                    LocalDateTime endDate = membership.getEndDate();
                    LocalDateTime now = LocalDateTime.now();
                    
                    if (endDate != null && endDate.isAfter(now)) {
                        // 会员未过期，获取会员等级名称
                        java.util.Optional<MembershipLevel> levelOpt = membershipLevelRepository.findById(membership.getMembershipLevelId());
                        if (levelOpt.isPresent()) {
                            MembershipLevel level = levelOpt.get();
                            String levelName = level.getName();
                            
                            // 所有等级统一使用 displayName
                            currentPlan = level.getDisplayName() != null ? level.getDisplayName() : level.getName();
                        }
                        expiryTime = endDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
                        paidAt = membership.getStartDate();
                    } else if (endDate != null) {
                        // 会员已过期，会员等级保留，但显示已过期
                        expiryTime = "已过期";
                        java.util.Optional<MembershipLevel> levelOpt = membershipLevelRepository.findById(membership.getMembershipLevelId());
                        if (levelOpt.isPresent()) {
                            MembershipLevel level = levelOpt.get();
                            String levelName = level.getName();
                            
                            // 过期后仍然按照原等级显示
                            currentPlan = level.getDisplayName() != null ? level.getDisplayName() : level.getName();
                        }
                    }
                }
            } catch (Exception e) {
                logger.warn("从UserMembership获取会员信息失败，将使用支付记录判断: {}", e.getMessage());
            }
            
            // 如果currentPlan为null（没有会员记录），默认为免费会员
            if (currentPlan == null) {
                try {
                    java.util.Optional<MembershipLevel> freeLevelOpt = membershipLevelRepository.findByName("free");
                    if (freeLevelOpt.isPresent()) {
                        currentPlan = freeLevelOpt.get().getDisplayName();
                    } else {
                        currentPlan = "免费会员";
                    }
                } catch (Exception e) {
                    logger.warn("获取 free 等级配置失败: {}", e.getMessage());
                    currentPlan = "免费会员";
                }
            }
            
            subscriptionInfo.put("currentPlan", currentPlan);
            subscriptionInfo.put("expiryTime", expiryTime);
            subscriptionInfo.put("paidAt", paidAt != null ? paidAt.toString() : null);
            subscriptionInfo.put("points", user.getPoints());
            subscriptionInfo.put("frozenPoints", user.getFrozenPoints() != null ? user.getFrozenPoints() : 0);
            subscriptionInfo.put("availablePoints", user.getAvailablePoints());
            subscriptionInfo.put("username", user.getUsername());
            subscriptionInfo.put("userId", user.getId());
            subscriptionInfo.put("email", user.getEmail());
            subscriptionInfo.put("nickname", user.getNickname());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", subscriptionInfo);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取用户订阅信息失败", e);
            return ResponseEntity.status(500)
                .body(createErrorResponse("获取用户订阅信息失败: " + e.getMessage()));
        }
    }
    
    // 注意：支付宝异步通知接口已移至 AlipayCallbackController，避免路由冲突
    
    /**
     * 创建支付宝支付
     */
    @PostMapping("/alipay/create")
    public ResponseEntity<Map<String, Object>> createAlipayPayment(
            @RequestBody Map<String, Object> paymentData,
            Authentication authentication,
            HttpServletRequest request) {
        try {
            String username;
            if (authentication != null && authentication.isAuthenticated()) {
                username = authentication.getName();
            } else {
                logger.warn("用户未认证，拒绝支付请求");
                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)) {
                logger.warn("用户{}无权限操作支付记录{}", username, paymentId);
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            // 获取客户端IP
            String clientIp = getClientIp(request);
            logger.info("创建支付宝支付，客户端IP: {}", clientIp);
            
            // 调用支付宝接口创建支付
            Map<String, Object> paymentResult = alipayService.createPayment(payment, clientIp);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付宝二维码生成成功");
            response.put("data", paymentResult);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建支付宝支付失败", e);
            // 简化错误消息，避免显示过长的URL
            String errorMsg = e.getMessage();
            if (errorMsg != null && errorMsg.length() > 100) {
                errorMsg = errorMsg.substring(0, 100) + "...";
            }
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建支付宝支付失败: " + errorMsg));
        }
    }
    
    /**
     * 创建噜噜支付（彩虹易支付）
     * 支持多种支付方式：alipay/wxpay/qqpay/bank
     */
    @PostMapping("/lulupay/create")
    public ResponseEntity<Map<String, Object>> createLuluPayment(
            @RequestBody Map<String, Object> paymentData,
            Authentication authentication,
            HttpServletRequest request) {
        try {
            String username;
            if (authentication != null && authentication.isAuthenticated()) {
                username = authentication.getName();
            } else {
                logger.warn("用户未认证，拒绝支付请求");
                return ResponseEntity.badRequest()
                    .body(createErrorResponse("请先登录后再创建支付"));
            }
            
            Long paymentId = Long.valueOf(paymentData.get("paymentId").toString());
            String payType = (String) paymentData.getOrDefault("payType", "alipay");
            
            Payment payment = paymentService.findById(paymentId)
                .orElseThrow(() -> new RuntimeException("支付记录不存在"));
            
            // 检查权限
            if (!payment.getUser().getUsername().equals(username)) {
                logger.warn("用户{}无权限操作支付记录{}", username, paymentId);
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限操作此支付记录"));
            }
            
            // 获取客户端IP
            String clientIp = getClientIp(request);
            logger.info("创建噜噜支付，客户端IP: {}", clientIp);
            
            // 调用噜噜支付接口创建支付
            Map<String, Object> paymentResult = luluPayService.createPayment(payment, payType, clientIp);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付创建成功");
            response.put("data", paymentResult);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建噜噜支付失败", e);
            String errorMsg = e.getMessage();
            if (errorMsg != null && errorMsg.length() > 100) {
                errorMsg = errorMsg.substring(0, 100) + "...";
            }
            return ResponseEntity.badRequest()
                .body(createErrorResponse("创建噜噜支付失败: " + errorMsg));
        }
    }
    
    /**
     * 删除支付记录（仅管理员）
     */
    @DeleteMapping("/{paymentId}")
    public ResponseEntity<Map<String, Object>> deletePayment(
            @PathVariable Long paymentId,
            Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            
            // 只有管理员可以删除
            if (!"ROLE_ADMIN".equals(user.getRole()) && !"ROLE_SUPER_ADMIN".equals(user.getRole())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限删除支付记录"));
            }
            
            paymentRepository.deleteById(paymentId);
            logger.info("管理员 {} 删除了支付记录: {}", username, paymentId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "支付记录删除成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("删除支付记录失败: {}", paymentId, e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("删除支付记录失败: " + e.getMessage()));
        }
    }
    
    /**
     * 批量删除支付记录（仅管理员）
     */
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deletePayments(
            @RequestBody List<Long> paymentIds,
            Authentication authentication) {
        try {
            String username = authentication.getName();
            User user = userService.findByUsername(username);
            
            // 只有管理员可以删除
            if (!"ROLE_ADMIN".equals(user.getRole()) && !"ROLE_SUPER_ADMIN".equals(user.getRole())) {
                return ResponseEntity.status(403)
                    .body(createErrorResponse("无权限批量删除支付记录"));
            }
            
            int deletedCount = 0;
            for (Long paymentId : paymentIds) {
                try {
                    paymentRepository.deleteById(paymentId);
                    deletedCount++;
                } catch (Exception e) {
                    logger.warn("删除支付记录 {} 失败: {}", paymentId, e.getMessage());
                }
            }
            
            logger.info("管理员 {} 批量删除了 {} 个支付记录", username, deletedCount);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "成功删除 " + deletedCount + " 个支付记录");
            response.put("deletedCount", deletedCount);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("批量删除支付记录失败", e);
            return ResponseEntity.badRequest()
                .body(createErrorResponse("批量删除支付记录失败: " + e.getMessage()));
        }
    }
    
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
    
    /**
     * 获取客户端真实IP地址
     */
    private String getClientIp(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.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}
