package com.example.demo.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.model.User;
import com.example.demo.model.SystemSettings;
import com.example.demo.model.MembershipLevel;
import com.example.demo.repository.TaskStatusRepository;
import com.example.demo.repository.MembershipLevelRepository;
import com.example.demo.service.UserService;
import com.example.demo.service.SystemSettingsService;
import com.example.demo.service.OnlineStatsService;
import com.example.demo.util.JwtUtils;

/**
 * 管理员控制器
 * 提供管理员功能，包括积分管理
 */
@RestController
@RequestMapping("/api/admin")
public class AdminController {

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

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private SystemSettingsService systemSettingsService;

    @Autowired
    private TaskStatusRepository taskStatusRepository;

    @Autowired
    private OnlineStatsService onlineStatsService;

    @Autowired
    private MembershipLevelRepository membershipLevelRepository;

    /**
     * 给用户增加积分
     */
    @PostMapping("/add-points")
    public ResponseEntity<Map<String, Object>> addPoints(
            @RequestParam String username,
            @RequestParam Integer points,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 增加用户积分
            userService.addPoints(username, points);
            
            response.put("success", true);
            response.put("message", "积分增加成功");
            response.put("username", username);
            response.put("points", points);
            
            logger.info("管理员 {} 为用户 {} 增加了 {} 积分", adminUsername, username, points);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("增加积分失败", e);
            response.put("success", false);
            response.put("message", "增加积分失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 重置用户积分为默认值
     */
    @PostMapping("/reset-points")
    public ResponseEntity<Map<String, Object>> resetPoints(
            @RequestParam String username,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 重置用户积分为100
            userService.setPoints(username, 100);
            
            response.put("success", true);
            response.put("message", "积分重置成功");
            response.put("username", username);
            response.put("points", 100);
            
            logger.info("管理员 {} 重置用户 {} 的积分为 100", adminUsername, username);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("重置积分失败", e);
            response.put("success", false);
            response.put("message", "重置积分失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从Token中提取用户名
     */
    private String extractUsernameFromToken(String token) {
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                return null;
            }
            
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                return null;
            }
            
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username != null && !jwtUtils.isTokenExpired(actualToken)) {
                return username;
            }
            
            return null;
        } catch (Exception e) {
            logger.error("解析token失败", e);
            return null;
        }
    }

    /**
     * 获取所有用户列表
     */
    @GetMapping("/users")
    public ResponseEntity<Map<String, Object>> getAllUsers(
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 获取所有用户
            List<User> users = userService.findAll();
            
            // 转换为DTO格式
            List<Map<String, Object>> userList = users.stream().map(user -> {
                Map<String, Object> userMap = new HashMap<>();
                userMap.put("id", user.getId());
                userMap.put("username", user.getUsername());
                userMap.put("email", user.getEmail());
                userMap.put("role", user.getRole());
                userMap.put("points", user.getPoints());
                userMap.put("frozenPoints", user.getFrozenPoints());
                userMap.put("createdAt", user.getCreatedAt());
                userMap.put("lastLoginAt", user.getLastLoginAt());
                userMap.put("isActive", user.getIsActive());
                return userMap;
            }).collect(Collectors.toList());
            
            response.put("success", true);
            response.put("data", userList);
            
            logger.info("管理员 {} 获取用户列表，共 {} 个用户", adminUsername, users.size());
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取用户列表失败", e);
            response.put("success", false);
            response.put("message", "获取用户列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 创建新用户
     */
    @PostMapping("/users")
    public ResponseEntity<Map<String, Object>> createUser(
            @RequestBody Map<String, Object> userData,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 提取用户数据
            String username = (String) userData.get("username");
            String email = (String) userData.get("email");
            String password = (String) userData.get("password");
            String role = (String) userData.getOrDefault("role", "ROLE_USER");

            // 验证必填字段
            if (username == null || username.isBlank()) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (email == null || email.isBlank()) {
                response.put("success", false);
                response.put("message", "邮箱不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (password == null || password.isBlank()) {
                response.put("success", false);
                response.put("message", "密码不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建用户
            User user = userService.create(username, email, password);
            
            // 如果指定了角色，更新角色
            if (!role.equals("ROLE_USER")) {
                userService.update(user.getId(), username, email, null, role);
                user = userService.findById(user.getId());
            }
            
            // 构建响应
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("email", user.getEmail());
            userMap.put("role", user.getRole());
            userMap.put("points", user.getPoints());
            userMap.put("createdAt", user.getCreatedAt());
            
            response.put("success", true);
            response.put("message", "用户创建成功");
            response.put("data", userMap);
            
            logger.info("管理员 {} 创建用户: {}", adminUsername, username);
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            logger.error("创建用户失败: {}", e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            logger.error("创建用户失败", e);
            response.put("success", false);
            response.put("message", "创建用户失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> updateUser(
            @PathVariable Long id,
            @RequestBody Map<String, Object> userData,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 提取用户数据
            String username = (String) userData.get("username");
            String email = (String) userData.get("email");
            String password = (String) userData.get("password");
            String role = (String) userData.get("role");

            // 验证必填字段
            if (username == null || username.isBlank()) {
                response.put("success", false);
                response.put("message", "用户名不能为空");
                return ResponseEntity.badRequest().body(response);
            }
            if (email == null || email.isBlank()) {
                response.put("success", false);
                response.put("message", "邮箱不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 更新用户（密码可选）
            User user = userService.update(id, username, email, password, role);
            
            // 构建响应
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("id", user.getId());
            userMap.put("username", user.getUsername());
            userMap.put("email", user.getEmail());
            userMap.put("role", user.getRole());
            userMap.put("points", user.getPoints());
            userMap.put("updatedAt", user.getUpdatedAt());
            
            response.put("success", true);
            response.put("message", "用户更新成功");
            response.put("data", userMap);
            
            logger.info("管理员 {} 更新用户: {}", adminUsername, username);
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            logger.error("更新用户失败: {}", e.getMessage());
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception e) {
            logger.error("更新用户失败", e);
            response.put("success", false);
            response.put("message", "更新用户失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{id}")
    public ResponseEntity<Map<String, Object>> deleteUser(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String adminUsername = extractUsernameFromToken(token);
            if (adminUsername == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return ResponseEntity.status(401).body(response);
            }

            // 删除用户
            userService.delete(id);
            
            response.put("success", true);
            response.put("message", "用户删除成功");
            
            logger.info("管理员 {} 删除用户ID: {}", adminUsername, id);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("删除用户失败", e);
            response.put("success", false);
            response.put("message", "删除用户失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取系统设置
     */
    @GetMapping("/settings")
    public ResponseEntity<Map<String, Object>> getSettings() {
        Map<String, Object> response = new HashMap<>();
        
        try {
            SystemSettings settings = systemSettingsService.getOrCreate();
            
            response.put("promptOptimizationModel", settings.getPromptOptimizationModel());
            response.put("storyboardSystemPrompt", settings.getStoryboardSystemPrompt());
            response.put("siteName", settings.getSiteName());
            response.put("siteSubtitle", settings.getSiteSubtitle());
            response.put("registrationOpen", settings.getRegistrationOpen());
            response.put("maintenanceMode", settings.getMaintenanceMode());
            response.put("contactEmail", settings.getContactEmail());
            response.put("tokenExpireHours", settings.getTokenExpireHours());
            // 套餐价格配置（从membership_levels表读取）
            membershipLevelRepository.findByName("starter").ifPresent(level -> 
                response.put("starterPriceCny", level.getPrice().intValue()));
            membershipLevelRepository.findByName("standard").ifPresent(level -> 
                response.put("standardPriceCny", level.getPrice().intValue()));
            membershipLevelRepository.findByName("professional").ifPresent(level -> 
                response.put("proPriceCny", level.getPrice().intValue()));
            response.put("pointsPerGeneration", settings.getPointsPerGeneration());
            // 各服务资源点消耗配置
            response.put("textToVideoPoints", settings.getTextToVideoPoints());
            response.put("imageToVideoPoints", settings.getImageToVideoPoints());
            response.put("storyboardImagePoints", settings.getStoryboardImagePoints());
            response.put("storyboardVideoPoints", settings.getStoryboardVideoPoints());
            // 支付渠道开关
            response.put("enableAlipay", settings.getEnableAlipay());
            response.put("enablePaypal", settings.getEnablePaypal());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("获取系统设置失败", e);
            response.put("error", "获取系统设置失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新系统设置
     */
    @PutMapping("/settings")
    public ResponseEntity<Map<String, Object>> updateSettings(
            @RequestBody Map<String, Object> settingsData) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            SystemSettings settings = systemSettingsService.getOrCreate();
            
            // 更新优化提示词模型
            if (settingsData.containsKey("promptOptimizationModel")) {
                String model = (String) settingsData.get("promptOptimizationModel");
                settings.setPromptOptimizationModel(model);
                logger.info("更新优化提示词模型为: {}", model);
            }
            
            // 更新分镜图系统引导词
            if (settingsData.containsKey("storyboardSystemPrompt")) {
                String prompt = (String) settingsData.get("storyboardSystemPrompt");
                settings.setStoryboardSystemPrompt(prompt);
                logger.info("更新分镜图系统引导词");
            }
            
            // 更新Token过期时间（小时）
            if (settingsData.containsKey("tokenExpireHours")) {
                Object value = settingsData.get("tokenExpireHours");
                Integer hours = null;
                if (value instanceof Number) {
                    hours = ((Number) value).intValue();
                } else if (value instanceof String) {
                    try {
                        hours = Integer.parseInt((String) value);
                    } catch (NumberFormatException e) {
                        logger.warn("无效的Token过期时间值: {}", value);
                    }
                }
                if (hours != null && hours >= 1 && hours <= 720) {
                    settings.setTokenExpireHours(hours);
                    logger.info("更新Token过期时间为: {} 小时", hours);
                } else {
                    logger.warn("Token过期时间超出范围(1-720小时): {}", hours);
                }
            }
            
            // 更新套餐价格（只更新membership_levels表）
            if (settingsData.containsKey("starterPriceCny")) {
                Object value = settingsData.get("starterPriceCny");
                Integer price = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString());
                membershipLevelRepository.findByName("starter").ifPresent(level -> {
                    level.setPrice(price.doubleValue());
                    level.setUpdatedAt(java.time.LocalDateTime.now());
                    membershipLevelRepository.save(level);
                    logger.info("更新membership_levels表: starter价格={}", price);
                });
                logger.info("更新入门版价格为: {} 元", price);
            }
            if (settingsData.containsKey("standardPriceCny")) {
                Object value = settingsData.get("standardPriceCny");
                Integer price = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString());
                membershipLevelRepository.findByName("standard").ifPresent(level -> {
                    level.setPrice(price.doubleValue());
                    level.setUpdatedAt(java.time.LocalDateTime.now());
                    membershipLevelRepository.save(level);
                    logger.info("更新membership_levels表: standard价格={}", price);
                });
                logger.info("更新标准版价格为: {} 元", price);
            }
            if (settingsData.containsKey("proPriceCny")) {
                Object value = settingsData.get("proPriceCny");
                Integer price = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString());
                membershipLevelRepository.findByName("professional").ifPresent(level -> {
                    level.setPrice(price.doubleValue());
                    level.setUpdatedAt(java.time.LocalDateTime.now());
                    membershipLevelRepository.save(level);
                    logger.info("更新membership_levels表: professional价格={}", price);
                });
                logger.info("更新专业版价格为: {} 元", price);
            }
            if (settingsData.containsKey("pointsPerGeneration")) {
                Object value = settingsData.get("pointsPerGeneration");
                Integer points = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString());
                settings.setPointsPerGeneration(points);
                logger.info("更新每次生成消耗积分为: {}", points);
            }
            
            // 更新各服务资源点消耗
            if (settingsData.containsKey("textToVideoPoints")) {
                Object value = settingsData.get("textToVideoPoints");
                if (value instanceof Number num) {
                    settings.setTextToVideoPoints(num.intValue());
                    logger.info("更新文生视频消耗积分为: {}", num.intValue());
                } else if (value != null) {
                    int pts = Integer.parseInt(String.valueOf(value));
                    settings.setTextToVideoPoints(pts);
                    logger.info("更新文生视频消耗积分为: {}", pts);
                }
            }
            if (settingsData.containsKey("imageToVideoPoints")) {
                Object value = settingsData.get("imageToVideoPoints");
                if (value instanceof Number num) {
                    settings.setImageToVideoPoints(num.intValue());
                    logger.info("更新图生视频消耗积分为: {}", num.intValue());
                } else if (value != null) {
                    int pts = Integer.parseInt(String.valueOf(value));
                    settings.setImageToVideoPoints(pts);
                    logger.info("更新图生视频消耗积分为: {}", pts);
                }
            }
            if (settingsData.containsKey("storyboardImagePoints")) {
                Object value = settingsData.get("storyboardImagePoints");
                if (value instanceof Number num) {
                    settings.setStoryboardImagePoints(num.intValue());
                    logger.info("更新分镜图生成消耗积分为: {}", num.intValue());
                } else if (value != null) {
                    int pts = Integer.parseInt(String.valueOf(value));
                    settings.setStoryboardImagePoints(pts);
                    logger.info("更新分镜图生成消耗积分为: {}", pts);
                }
            }
            if (settingsData.containsKey("storyboardVideoPoints")) {
                Object value = settingsData.get("storyboardVideoPoints");
                if (value instanceof Number num) {
                    settings.setStoryboardVideoPoints(num.intValue());
                    logger.info("更新分镜视频生成消耗积分为: {}", num.intValue());
                } else if (value != null) {
                    int pts = Integer.parseInt(String.valueOf(value));
                    settings.setStoryboardVideoPoints(pts);
                    logger.info("更新分镜视频生成消耗积分为: {}", pts);
                }
            }

            // 更新支付渠道开关
            if (settingsData.containsKey("enableAlipay")) {
                Boolean enable = (Boolean) settingsData.get("enableAlipay");
                settings.setEnableAlipay(enable);
                logger.info("更新支付宝开关为: {}", enable);
            }
            if (settingsData.containsKey("enablePaypal")) {
                Boolean enable = (Boolean) settingsData.get("enablePaypal");
                settings.setEnablePaypal(enable);
                logger.info("更新PayPal开关为: {}", enable);
            }
            
            systemSettingsService.update(settings);
            
            response.put("success", true);
            response.put("message", "系统设置更新成功");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("更新系统设置失败", e);
            response.put("success", false);
            response.put("message", "更新系统设置失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除单个任务记录
     */
    @DeleteMapping("/tasks/{taskId}")
    public ResponseEntity<Map<String, Object>> deleteTask(
            @PathVariable String taskId,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                response.put("success", false);
                response.put("message", "未授权访问");
                return ResponseEntity.status(401).body(response);
            }
            
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username == null || jwtUtils.isTokenExpired(actualToken)) {
                response.put("success", false);
                response.put("message", "Token无效或已过期");
                return ResponseEntity.status(401).body(response);
            }
            
            User admin = userService.findByUsername(username);
            if (admin == null || !"ROLE_ADMIN".equals(admin.getRole())) {
                response.put("success", false);
                response.put("message", "需要管理员权限");
                return ResponseEntity.status(403).body(response);
            }

            // 查找并删除任务（使用 findFirst 处理可能的重复记录）
            var taskOpt = taskStatusRepository.findFirstByTaskIdOrderByIdDesc(taskId);
            if (taskOpt.isPresent()) {
                taskStatusRepository.delete(taskOpt.get());
                logger.info("管理员 {} 删除了任务: {}", username, taskId);
                response.put("success", true);
                response.put("message", "任务删除成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "任务不存在");
                return ResponseEntity.status(404).body(response);
            }
            
        } catch (Exception e) {
            logger.error("删除任务失败: {}", taskId, e);
            response.put("success", false);
            response.put("message", "删除任务失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 批量删除任务记录
     */
    @DeleteMapping("/tasks/batch")
    public ResponseEntity<Map<String, Object>> batchDeleteTasks(
            @RequestBody List<String> taskIds,
            @RequestHeader("Authorization") String token) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 验证管理员权限
            String actualToken = jwtUtils.extractTokenFromHeader(token);
            if (actualToken == null) {
                response.put("success", false);
                response.put("message", "未授权访问");
                return ResponseEntity.status(401).body(response);
            }
            
            String username = jwtUtils.getUsernameFromToken(actualToken);
            if (username == null || jwtUtils.isTokenExpired(actualToken)) {
                response.put("success", false);
                response.put("message", "Token无效或已过期");
                return ResponseEntity.status(401).body(response);
            }
            
            User admin = userService.findByUsername(username);
            if (admin == null || !"ROLE_ADMIN".equals(admin.getRole())) {
                response.put("success", false);
                response.put("message", "需要管理员权限");
                return ResponseEntity.status(403).body(response);
            }

            // 批量删除任务
            int deletedCount = 0;
            for (String taskId : taskIds) {
                var taskOpt = taskStatusRepository.findFirstByTaskIdOrderByIdDesc(taskId);
                if (taskOpt.isPresent()) {
                    taskStatusRepository.delete(taskOpt.get());
                    deletedCount++;
                }
            }
            
            logger.info("管理员 {} 批量删除了 {} 个任务", username, deletedCount);
            response.put("success", true);
            response.put("message", "成功删除 " + deletedCount + " 个任务");
            response.put("deletedCount", deletedCount);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("批量删除任务失败", e);
            response.put("success", false);
            response.put("message", "批量删除任务失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取系统在线统计
     * 返回当天访问的独立IP数（通过IP判断在线人数）
     */
    @GetMapping("/online-stats")
    public ResponseEntity<Map<String, Object>> getOnlineStats() {
        Map<String, Object> response = new HashMap<>();
        try {
            int todayVisitors = onlineStatsService.getTodayVisitorCount();
            Map<String, Object> stats = onlineStatsService.getStats();
            
            response.put("success", true);
            response.put("todayVisitors", todayVisitors);
            response.put("date", stats.get("date"));
            response.put("uptime", stats.get("uptime"));
            return ResponseEntity.ok()
                .header("Cache-Control", "no-cache, no-store, must-revalidate")
                .header("Pragma", "no-cache")
                .header("Expires", "0")
                .body(response);
        } catch (Exception e) {
            logger.error("获取在线统计失败", e);
            response.put("success", false);
            response.put("message", "获取在线统计失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}

