package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.common.Result;
import com.zhentao.entity.Activity;
import com.zhentao.entity.Users;
import com.zhentao.mapper.ActivityMapper;
import com.zhentao.mapper.UsersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

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

/**
 * 数据面板控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/dashboard")
@CrossOrigin(origins = "*")
public class DashboardController {
    
    private final UsersMapper usersMapper;
    private final ActivityMapper activityMapper;
    private final RedisTemplate<String, Object> redisTemplate;
    
    // Redis缓存键
    private static final String CACHE_KEY_STATS = "admin:dashboard:stats";
    private static final String CACHE_KEY_RECENT_ACTIVITIES = "admin:dashboard:recent_activities";
    private static final int CACHE_EXPIRE_MINUTES = 5; // 缓存5分钟
    
    public DashboardController(UsersMapper usersMapper, ActivityMapper activityMapper, 
                              RedisTemplate<String, Object> redisTemplate) {
        this.usersMapper = usersMapper;
        this.activityMapper = activityMapper;
        this.redisTemplate = redisTemplate;
    }
    
    /**
     * 获取统计数据（使用Redis缓存）
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> stats() {
        try {
            // 1. 先从Redis获取缓存
            Object cachedStats = redisTemplate.opsForValue().get(CACHE_KEY_STATS);
            if (cachedStats != null && cachedStats instanceof Map) {
                log.info("从Redis缓存获取统计数据");
                return Result.success((Map<String, Object>) cachedStats);
            }
            
            // 2. 缓存不存在，从数据库查询
            log.info("从数据库查询统计数据");
            Map<String, Object> stats = new HashMap<>();
            
            // 总用户数
            Long totalUsers = usersMapper.selectCount(null);
            stats.put("totalUsers", totalUsers != null ? totalUsers : 0);
            
            // 总活动数
            Long totalActivities = activityMapper.selectCount(null);
            stats.put("totalActivities", totalActivities != null ? totalActivities : 0);
            
            // VIP用户数（查询vip_level > 0的用户）
            QueryWrapper<Users> vipWrapper = new QueryWrapper<>();
            vipWrapper.isNotNull("vip_level").gt("vip_level", 0);
            Long vipUsers = 0L;
            try {
                vipUsers = usersMapper.selectCount(vipWrapper);
            } catch (Exception e) {
                log.warn("VIP用户数查询失败，使用默认值: {}", e.getMessage());
            }
            stats.put("vipUsers", vipUsers != null ? vipUsers : 0);
            
            // 成功案例数（模拟数据）
            stats.put("totalCases", 89);
            
            // 课程数量（模拟数据）
            stats.put("totalCourses", 34);
            
            // 3. 存入Redis缓存（5分钟过期）
            try {
                redisTemplate.opsForValue().set(CACHE_KEY_STATS, stats, CACHE_EXPIRE_MINUTES, TimeUnit.MINUTES);
                log.info("统计数据已缓存到Redis，过期时间: {}分钟", CACHE_EXPIRE_MINUTES);
            } catch (Exception e) {
                log.warn("Redis缓存失败，继续返回数据: {}", e.getMessage());
            }
            
            log.info("统计数据: {}", stats);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return Result.error("统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取最近活动列表（使用Redis缓存）
     */
    @GetMapping("/recent-activities")
    public Result<List<Activity>> getRecentActivities(
            @RequestParam(defaultValue = "10") Integer limit) {
        try {
            // 1. 先从Redis获取缓存
            String cacheKey = CACHE_KEY_RECENT_ACTIVITIES + ":" + limit;
            Object cachedActivities = redisTemplate.opsForValue().get(cacheKey);
            if (cachedActivities != null && cachedActivities instanceof List) {
                log.info("从Redis缓存获取最近活动列表");
                return Result.success((List<Activity>) cachedActivities);
            }
            
            // 2. 缓存不存在，从数据库查询
            log.info("从数据库查询最近活动列表");
            QueryWrapper<Activity> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("id"); // 按ID倒序，最新的活动ID最大
            wrapper.last("LIMIT " + limit);
            
            List<Activity> activities = activityMapper.selectList(wrapper);
            
            // 3. 存入Redis缓存（5分钟过期）
            if (activities != null && !activities.isEmpty()) {
                try {
                    redisTemplate.opsForValue().set(cacheKey, activities, CACHE_EXPIRE_MINUTES, TimeUnit.MINUTES);
                    log.info("最近活动已缓存到Redis，数量: {}", activities.size());
                } catch (Exception e) {
                    log.warn("Redis缓存失败: {}", e.getMessage());
                }
            }
            
            log.info("查询到 {} 条最近活动", activities != null ? activities.size() : 0);
            return Result.success(activities != null ? activities : new ArrayList<>());
        } catch (Exception e) {
            log.error("获取最近活动失败", e);
            // 返回空列表而不是错误，避免前端显示异常
            return Result.success(new ArrayList<>());
        }
    }
    
    /**
     * 获取用户增长趋势（真实数据）
     */
    @GetMapping("/user-trend")
    public Result<Map<String, Object>> getUserTrend(@RequestParam(defaultValue = "7") Integer days) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<String> dates = new ArrayList<>();
            List<Long> counts = new ArrayList<>();
            
            // 从数据库按日期统计用户增长
            java.time.LocalDate today = java.time.LocalDate.now();
            
            for (int i = days - 1; i >= 0; i--) {
                java.time.LocalDate date = today.minusDays(i);
                String dateStr = String.format("%02d-%02d", date.getMonthValue(), date.getDayOfMonth());
                dates.add(dateStr);
                
                // 查询该日期注册的用户数
                try {
                    QueryWrapper<Users> wrapper = new QueryWrapper<>();
                    wrapper.apply("DATE(created_at) = {0}", date);
                    Long count = usersMapper.selectCount(wrapper);
                    counts.add(count != null ? count : 0L);
                } catch (Exception e) {
                    log.warn("查询{}日期用户数失败: {}", date, e.getMessage());
                    counts.add(0L);
                }
            }
            
            result.put("dates", dates);
            result.put("counts", counts);
            
            log.info("用户增长趋势: dates={}, counts={}", dates, counts);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取用户增长趋势失败", e);
            return Result.error("查询失败");
        }
    }
    
    /**
     * 获取活动报名统计（真实数据）
     */
    @GetMapping("/activity-stats")
    public Result<Map<String, Object>> getActivityStats(@RequestParam(defaultValue = "7") Integer days) {
        try {
            Map<String, Object> result = new HashMap<>();
            List<String> dates = new ArrayList<>();
            List<Long> counts = new ArrayList<>();
            
            // 从数据库按日期统计活动数
            java.time.LocalDate today = java.time.LocalDate.now();
            
            for (int i = days - 1; i >= 0; i--) {
                java.time.LocalDate date = today.minusDays(i);
                String dateStr = String.format("%02d-%02d", date.getMonthValue(), date.getDayOfMonth());
                dates.add(dateStr);
                
                // 查询该日期开始的活动数
                try {
                    QueryWrapper<Activity> wrapper = new QueryWrapper<>();
                    wrapper.apply("DATE(start_time) = {0}", date);
                    Long count = activityMapper.selectCount(wrapper);
                    counts.add(count != null ? count : 0L);
                } catch (Exception e) {
                    log.warn("查询{}日期活动数失败: {}", date, e.getMessage());
                    counts.add(0L);
                }
            }
            
            result.put("dates", dates);
            result.put("counts", counts);
            
            log.info("活动报名统计: dates={}, counts={}", dates, counts);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取活动报名统计失败", e);
            return Result.error("查询失败");
        }
    }
    
    /**
     * 清除缓存
     */
    @DeleteMapping("/cache/clear")
    public Result<String> clearCache() {
        try {
            redisTemplate.delete(CACHE_KEY_STATS);
            redisTemplate.delete(CACHE_KEY_RECENT_ACTIVITIES + ":*");
            log.info("数据面板缓存已清除");
            return Result.success("缓存清除成功");
        } catch (Exception e) {
            log.error("清除缓存失败", e);
            return Result.error("清除缓存失败");
        }
    }
}
