package com.example.demo.controller;

import com.example.demo.repository.UserActivityStatsRepository;
import com.example.demo.service.UserActivityStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/analytics")
@CrossOrigin(origins = "*")
public class AnalyticsApiController {

    @Autowired
    private UserActivityStatsRepository userActivityStatsRepository;
    
    @Autowired
    private UserActivityStatsService userActivityStatsService;

    /**
     * 获取日活用户趋势数据
     */
    @GetMapping("/daily-active-users")
    public ResponseEntity<Map<String, Object>> getDailyActiveUsersTrend(
            @RequestParam(defaultValue = "2024") String year,
            @RequestParam(defaultValue = "monthly") String granularity) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            if ("monthly".equals(granularity)) {
                // 按月聚合数据
                List<Map<String, Object>> monthlyData = userActivityStatsRepository.findMonthlyActiveUsers(Integer.parseInt(year));
                
                // 确保12个月都有数据
                List<Map<String, Object>> completeData = new ArrayList<>();
                for (int month = 1; month <= 12; month++) {
                    final int currentMonth = month;
                    Optional<Map<String, Object>> monthData = monthlyData.stream()
                        .filter(data -> {
                            Object monthObj = data.get("month");
                            if (monthObj instanceof Number) {
                                return ((Number) monthObj).intValue() == currentMonth;
                            }
                            return false;
                        })
                        .findFirst();
                    
                    if (monthData.isPresent()) {
                        completeData.add(monthData.get());
                    } else {
                        Map<String, Object> emptyMonth = new HashMap<>();
                        emptyMonth.put("month", currentMonth);
                        emptyMonth.put("dailyActiveUsers", 0);
                        emptyMonth.put("avgDailyActive", 0.0);
                        completeData.add(emptyMonth);
                    }
                }
                
                response.put("monthlyData", completeData);
            } else {
                // 按日返回数据
                List<Map<String, Object>> dailyData = userActivityStatsRepository.findDailyActiveUsersByYear(Integer.parseInt(year));
                response.put("dailyData", dailyData);
            }
            
            response.put("year", year);
            response.put("granularity", granularity);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取日活用户趋势数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 手动触发重新计算日活用户统计数据
     * @param days 要重新计算的天数，默认30天
     */
    @PostMapping("/recalculate-daily-active")
    public ResponseEntity<Map<String, Object>> recalculateDailyActiveUsers(
            @RequestParam(defaultValue = "30") int days) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            userActivityStatsService.calculateDailyActiveUsersForRecentDays(days);
            
            response.put("success", true);
            response.put("message", "已重新计算最近 " + days + " 天的日活用户数据");
            response.put("days", days);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", "重新计算日活用户数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 获取今日实时日活用户数
     */
    @GetMapping("/today-active-users")
    public ResponseEntity<Map<String, Object>> getTodayActiveUsers() {
        try {
            Map<String, Object> response = new HashMap<>();
            
            int todayActiveUsers = userActivityStatsService.getTodayActiveUsersCount();
            
            response.put("todayActiveUsers", todayActiveUsers);
            response.put("date", LocalDate.now().toString());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取今日日活用户数失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取用户活跃度概览
     */
    @GetMapping("/user-activity-overview")
    public ResponseEntity<Map<String, Object>> getUserActivityOverview() {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 获取最新数据
            LocalDate today = LocalDate.now();
            LocalDate yesterday = today.minusDays(1);
            LocalDate lastMonth = today.minusMonths(1);
            LocalDate lastYear = today.minusYears(1);
            
            // 今日日活
            Integer todayDAU = userActivityStatsRepository.findDailyActiveUsersByDate(today);
            response.put("todayDAU", todayDAU != null ? todayDAU : 0);
            
            // 昨日日活
            Integer yesterdayDAU = userActivityStatsRepository.findDailyActiveUsersByDate(yesterday);
            response.put("yesterdayDAU", yesterdayDAU != null ? yesterdayDAU : 0);
            
            // 本月平均日活
            Double monthlyAvgDAU = userActivityStatsRepository.findAverageDailyActiveUsersByMonth(today.getYear(), today.getMonthValue());
            response.put("monthlyAvgDAU", monthlyAvgDAU != null ? monthlyAvgDAU : 0.0);
            
            // 上月平均日活
            LocalDate lastMonthDate = today.minusMonths(1);
            Double lastMonthAvgDAU = userActivityStatsRepository.findAverageDailyActiveUsersByMonth(lastMonthDate.getYear(), lastMonthDate.getMonthValue());
            response.put("lastMonthAvgDAU", lastMonthAvgDAU != null ? lastMonthAvgDAU : 0.0);
            
            // 年度平均日活
            Double yearlyAvgDAU = userActivityStatsRepository.findAverageDailyActiveUsersByYear(today.getYear());
            response.put("yearlyAvgDAU", yearlyAvgDAU != null ? yearlyAvgDAU : 0.0);
            
            // 计算增长率
            if (yesterdayDAU != null && yesterdayDAU > 0) {
                double dayGrowthRate = ((todayDAU != null ? todayDAU : 0) - yesterdayDAU) / (double) yesterdayDAU * 100;
                response.put("dayGrowthRate", Math.round(dayGrowthRate * 100.0) / 100.0);
            } else {
                response.put("dayGrowthRate", 0.0);
            }
            
            if (lastMonthAvgDAU != null && lastMonthAvgDAU > 0) {
                double monthGrowthRate = ((monthlyAvgDAU != null ? monthlyAvgDAU : 0) - lastMonthAvgDAU) / lastMonthAvgDAU * 100;
                response.put("monthGrowthRate", Math.round(monthGrowthRate * 100.0) / 100.0);
            } else {
                response.put("monthGrowthRate", 0.0);
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取用户活跃度概览失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取用户活跃度热力图数据
     */
    @GetMapping("/user-activity-heatmap")
    public ResponseEntity<Map<String, Object>> getUserActivityHeatmap(
            @RequestParam(defaultValue = "2024") String year) {
        try {
            Map<String, Object> response = new HashMap<>();
            
            // 获取全年每日数据
            List<Map<String, Object>> dailyData = userActivityStatsRepository.findDailyActiveUsersByYear(Integer.parseInt(year));
            
            // 转换为热力图格式
            List<List<Object>> heatmapData = new ArrayList<>();
            for (Map<String, Object> data : dailyData) {
                List<Object> point = new ArrayList<>();
                point.add(data.get("dayOfYear")); // 一年中的第几天
                point.add(data.get("weekOfYear")); // 一年中的第几周
                point.add(data.get("dailyActiveUsers")); // 日活用户数
                heatmapData.add(point);
            }
            
            response.put("heatmapData", heatmapData);
            response.put("year", year);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            Map<String, Object> error = new HashMap<>();
            error.put("error", "获取用户活跃度热力图数据失败");
            error.put("message", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
}
