package com.reading.platform.controller.school;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reading.platform.common.annotation.RequireRole;
import com.reading.platform.common.enums.UserRole;
import com.reading.platform.common.response.Result;
import com.reading.platform.common.security.SecurityUtils;
import com.reading.platform.dto.response.*;
import com.reading.platform.service.SchoolStatsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.ArrayList;

@Tag(name = "学校 - 统计", description = "学校统计仪表盘接口（学校管理员专用）")
@RestController
@RequestMapping("/api/v1/school/stats")
@RequiredArgsConstructor
@RequireRole(UserRole.SCHOOL)
public class SchoolStatsController {

    private final SchoolStatsService schoolStatsService;

    @Operation(summary = "获取学校统计数据")
    @GetMapping
    public Result<StatsResponse> getStats() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        Map<String, Object> stats = schoolStatsService.getStats(tenantId);

        StatsResponse response = new StatsResponse();
        response.setTotalTeachers((Integer) stats.get("teacherCount"));
        response.setTotalStudents((Integer) stats.get("studentCount"));
        response.setTotalClasses((Integer) stats.get("classCount"));
        response.setTotalCourses((Integer) stats.get("courseCount"));

        return Result.success(response);
    }

    @Operation(summary = "获取活跃教师统计")
    @GetMapping("/teachers")
    public Result<List<ActiveTeacherStatsResponse>> getActiveTeachers(
            @RequestParam(value = "limit", required = false, defaultValue = "5") Integer limit) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> teachers = schoolStatsService.getActiveTeachers(tenantId, limit);

        List<ActiveTeacherStatsResponse> result = new ArrayList<>();
        for (Map<String, Object> item : teachers) {
            ActiveTeacherStatsResponse response = new ActiveTeacherStatsResponse();
            response.setId(item.get("id") != null ? item.get("id") != null ? item.get("id").toString() : null : null);
            response.setName((String) item.get("name"));
            response.setLessonCount((Integer) item.get("lessonCount"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取课程使用统计")
    @GetMapping("/courses")
    public Result<List<CourseUsageStatsResponse>> getCourseUsageStats() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> stats = schoolStatsService.getCourseUsageStats(tenantId);

        List<CourseUsageStatsResponse> result = new ArrayList<>();
        for (Map<String, Object> item : stats) {
            CourseUsageStatsResponse response = new CourseUsageStatsResponse();
            response.setCourseId(item.get("courseId") != null ? item.get("courseId") != null ? item.get("courseId").toString() : null : null);
            response.setCourseName((String) item.get("courseName"));
            response.setUsageCount((Integer) item.get("usageCount"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取最近活动记录")
    @GetMapping("/activities")
    public Result<List<RecentActivityResponse>> getRecentActivities(
            @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> activities = schoolStatsService.getRecentActivities(tenantId, limit);

        List<RecentActivityResponse> result = new ArrayList<>();
        for (Map<String, Object> item : activities) {
            RecentActivityResponse response = new RecentActivityResponse();
            response.setId(item.get("id") != null ? item.get("id") != null ? item.get("id").toString() : null : null);
            response.setType((String) item.get("type"));
            response.setTitle((String) item.get("title"));
            response.setTime(item.get("time") != null ? item.get("time").toString() : null);
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取课时趋势（最近 N 个月）")
    @GetMapping("/lesson-trend")
    public Result<List<TrendDataResponse>> getLessonTrend(
            @RequestParam(value = "months", required = false, defaultValue = "6") Integer months) {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> trend = schoolStatsService.getLessonTrend(tenantId, months);

        List<TrendDataResponse> result = new ArrayList<>();
        for (Map<String, Object> item : trend) {
            TrendDataResponse response = new TrendDataResponse();
            response.setMonth((String) item.get("month"));
            response.setLessonCount((Integer) item.get("lessonCount"));
            response.setStudentCount((Integer) item.get("studentCount"));
            result.add(response);
        }
        return Result.success(result);
    }

    @Operation(summary = "获取课程分布统计（饼图数据）")
    @GetMapping("/course-distribution")
    public Result<List<CourseDistributionResponse>> getCourseDistribution() {
        String tenantId = SecurityUtils.getCurrentTenantId();
        List<Map<String, Object>> distribution = schoolStatsService.getCourseDistribution(tenantId);

        List<CourseDistributionResponse> result = new ArrayList<>();
        for (Map<String, Object> item : distribution) {
            CourseDistributionResponse response = new CourseDistributionResponse();
            response.setName((String) item.get("name"));
            response.setValue((Integer) item.get("value"));
            result.add(response);
        }
        return Result.success(result);
    }
}
