package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.UvStatisticsDto;
import com.dora.service.UvStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UV统计管理控制器 - 管理端
 * 用于管理员查看详细的UV统计数据和分析
 * 
 * @author dora
 * @date 2024/12/01
 */
@Slf4j
@RestController
@RequestMapping("/admin/uv")
@Tag(name = "UV统计管理", description = "管理端UV统计分析接口")
@RequiredArgsConstructor
public class AdminUvController {

    private final UvStatisticsService uvStatisticsService;

    /**
     * 获取指定日期的UV详细数据
     */
    @GetMapping("/date/{date}")
    @Operation(summary = "获取指定日期UV数据", description = "获取指定日期的详细UV统计数据")
    public Result<UvStatisticsDto> getUvByDate(
            @Parameter(description = "日期，格式：yyyy-MM-dd") 
            @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate date) {
        
        try {
            // 限制查询范围，只能查询最近7天的数据
            LocalDate earliestDate = LocalDate.now().minusDays(6);
            if (date.isBefore(earliestDate)) {
                return Result.error("只能查询最近7天的数据");
            }

            UvStatisticsDto uvData = uvStatisticsService.getUvByDate(date);
            return Result.success(uvData);

        } catch (Exception e) {
            log.error("获取指定日期UV数据失败 - 日期: {}", date, e);
            return Result.error("获取UV数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取最近7天UV趋势数据
     */
    @GetMapping("/trend/weekly")
    @Operation(summary = "获取最近7天UV趋势", description = "获取最近7天的UV趋势分析数据")
    public Result<List<UvStatisticsDto>> getWeeklyUvTrend() {
        try {
            List<UvStatisticsDto> trendData = uvStatisticsService.getRecentSevenDaysUv();
            return Result.success(trendData);

        } catch (Exception e) {
            log.error("获取最近7天UV趋势失败", e);
            return Result.error("获取趋势数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取UV统计汇总报告
     */
    @GetMapping("/summary")
    @Operation(summary = "获取UV汇总报告", description = "获取完整的UV统计汇总分析报告")
    public Result<UvStatisticsDto.UvSummary> getUvSummary() {
        try {
            UvStatisticsDto.UvSummary summary = uvStatisticsService.getUvSummary();
            return Result.success(summary);

        } catch (Exception e) {
            log.error("获取UV汇总报告失败", e);
            return Result.error("获取汇总报告失败：" + e.getMessage());
        }
    }

    /**
     * 获取今日UV实时数据
     */
    @GetMapping("/realtime/today")
    @Operation(summary = "获取今日实时UV", description = "获取今日实时UV统计数据")
    public Result<UvStatisticsDto> getTodayRealtimeUv() {
        try {
            UvStatisticsDto todayData = uvStatisticsService.getTodayUv();
            return Result.success(todayData);

        } catch (Exception e) {
            log.error("获取今日实时UV失败", e);
            return Result.error("获取实时数据失败：" + e.getMessage());
        }
    }

    /**
     * 手动清理过期UV数据
     */
    @PostMapping("/cleanup")
    @Operation(summary = "清理过期数据", description = "手动清理7天前的过期UV数据")
    public Result<String> cleanupExpiredData() {
        try {
            uvStatisticsService.cleanExpiredUvData();
            log.info("管理员手动清理过期UV数据完成");
            return Result.success("过期数据清理完成");

        } catch (Exception e) {
            log.error("手动清理过期数据失败", e);
            return Result.error("清理数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取UV统计配置信息
     */
    @GetMapping("/config")
    @Operation(summary = "获取统计配置", description = "获取UV统计的配置信息")
    public Result<Object> getUvConfig() {
        try {
            Map<String, Object> config = new HashMap<>();
            config.put("dataRetentionDays", 7);
            config.put("description", "UV数据保留7天，自动过期清理");
            config.put("timezone", "Asia/Shanghai");
            config.put("updateTime", System.currentTimeMillis());
            return Result.success(config);

        } catch (Exception e) {
            log.error("获取UV配置信息失败", e);
            return Result.error("获取配置失败：" + e.getMessage());
        }
    }

    /**
     * 导出UV统计数据
     */
    @GetMapping("/export")
    @Operation(summary = "导出UV数据", description = "导出最近7天的UV统计数据")
    public Result<Object> exportUvData(
            @Parameter(description = "导出格式") @RequestParam(defaultValue = "json") String format) {
        
        try {
            List<UvStatisticsDto> weeklyData = uvStatisticsService.getRecentSevenDaysUv();
            UvStatisticsDto.UvSummary summary = uvStatisticsService.getUvSummary();

            Map<String, Object> exportData = new HashMap<>();
            exportData.put("exportTime", System.currentTimeMillis());
            exportData.put("dataRange", "最近7天");
            exportData.put("summary", summary);
            exportData.put("dailyData", weeklyData);
            exportData.put("format", format);

            log.info("导出UV统计数据 - 格式: {}, 数据量: {}", format, weeklyData.size());
            return Result.success(exportData);

        } catch (Exception e) {
            log.error("导出UV数据失败", e);
            return Result.error("导出数据失败：" + e.getMessage());
        }
    }
}
