package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reading.platform.entity.*;
import com.reading.platform.mapper.*;
import com.reading.platform.service.SchoolStatsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 学校统计服务实现类
 */
@Service
@RequiredArgsConstructor
public class SchoolStatsServiceImpl implements SchoolStatsService {

    private final TeacherMapper teacherMapper;
    private final StudentMapper studentMapper;
    private final ClazzMapper clazzMapper;
    private final LessonMapper lessonMapper;
    private final CourseMapper courseMapper;

    @Override
    public Map<String, Object> getStats(String tenantId) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("teacherCount", Math.toIntExact(teacherMapper.selectCount(
                new LambdaQueryWrapper<Teacher>().eq(Teacher::getTenantId, tenantId))));
        stats.put("studentCount", Math.toIntExact(studentMapper.selectCount(
                new LambdaQueryWrapper<Student>().eq(Student::getTenantId, tenantId))));
        stats.put("classCount", Math.toIntExact(clazzMapper.selectCount(
                new LambdaQueryWrapper<Clazz>().eq(Clazz::getTenantId, tenantId))));
        stats.put("lessonCount", Math.toIntExact(lessonMapper.selectCount(
                new LambdaQueryWrapper<Lesson>().eq(Lesson::getTenantId, tenantId))));
        return stats;
    }

    @Override
    public List<Map<String, Object>> getActiveTeachers(String tenantId, Integer limit) {
        if (limit == null) {
            limit = 5;
        }

        // 获取所有活跃教师
        List<Teacher> teachers = teacherMapper.selectList(
                new LambdaQueryWrapper<Teacher>()
                        .eq(Teacher::getTenantId, tenantId)
                        .eq(Teacher::getStatus, "ACTIVE")
        );

        // 统计每位教师的授课次数
        List<Map<String, Object>> result = new ArrayList<>();

        for (Teacher teacher : teachers) {
            long lessonCount = lessonMapper.selectCount(
                    new LambdaQueryWrapper<Lesson>()
                            .eq(Lesson::getTenantId, tenantId)
                            .eq(Lesson::getTeacherId, teacher.getId())
                            .eq(Lesson::getStatus, "COMPLETED")
            );

            if (lessonCount > 0) {
                Map<String, Object> item = new HashMap<>();
                item.put("id", teacher.getId());
                item.put("name", teacher.getName());
                item.put("lessonCount", Math.toIntExact(lessonCount));
                result.add(item);
            }
        }

        // 按授课次数排序
        result.sort((a, b) -> (Integer) b.get("lessonCount") - (Integer) a.get("lessonCount"));

        // 返回前 N 名
        if (result.size() > limit) {
            result = result.subList(0, limit);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getCourseUsageStats(String tenantId) {
        // 获取所有已完成的课时
        List<Lesson> lessons = lessonMapper.selectList(
                new LambdaQueryWrapper<Lesson>()
                        .eq(Lesson::getTenantId, tenantId)
                        .eq(Lesson::getStatus, "COMPLETED")
        );

        // 统计每个课程的使用次数
        Map<String, Map<String, Object>> courseUsageMap = new LinkedHashMap<>();

        for (Lesson lesson : lessons) {
            String courseId = lesson.getCourseId();
            if (courseId == null) continue;

            if (!courseUsageMap.containsKey(courseId)) {
                Course course = courseMapper.selectById(courseId);
                Map<String, Object> courseData = new HashMap<>();
                courseData.put("courseId", courseId);
                courseData.put("courseName", course != null ? course.getName() : "未知课程");
                courseData.put("usageCount", 0);
                courseUsageMap.put(courseId, courseData);
            }

            Map<String, Object> courseData = courseUsageMap.get(courseId);
            int currentCount = (Integer) courseData.get("usageCount");
            courseData.put("usageCount", currentCount + 1);
        }

        // 转换为列表并按使用次数排序
        List<Map<String, Object>> result = new ArrayList<>(courseUsageMap.values());
        result.sort((a, b) -> Integer.compare((Integer) b.get("usageCount"), (Integer) a.get("usageCount")));

        // 最多返回前 10 个
        if (result.size() > 10) {
            result = result.subList(0, 10);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getRecentActivities(String tenantId, Integer limit) {
        if (limit == null) {
            limit = 10;
        }

        List<Lesson> lessons = lessonMapper.selectList(
                new LambdaQueryWrapper<Lesson>()
                        .eq(Lesson::getTenantId, tenantId)
                        .orderByDesc(Lesson::getCreatedAt)
                        .last("LIMIT " + limit)
        );

        List<Map<String, Object>> activities = new ArrayList<>();

        for (Lesson lesson : lessons) {
            Map<String, Object> activity = new HashMap<>();
            activity.put("id", lesson.getId());
            activity.put("type", lesson.getStatus());
            activity.put("title", formatActivityTitle(lesson));
            activity.put("time", lesson.getCreatedAt());
            activities.add(activity);
        }

        return activities;
    }

    @Override
    public List<Map<String, Object>> getLessonTrend(String tenantId, Integer months) {
        if (months == null) {
            months = 6;
        }

        List<Map<String, Object>> result = new ArrayList<>();
        LocalDate now = LocalDate.now();

        // 获取当前学生总数
        long studentCount = studentMapper.selectCount(
                new LambdaQueryWrapper<Student>().eq(Student::getTenantId, tenantId)
        );

        for (int i = months - 1; i >= 0; i--) {
            LocalDate startDate = now.minusMonths(i).withDayOfMonth(1);
            LocalDate endDate = now.minusMonths(i).withDayOfMonth(startDate.lengthOfMonth());

            LocalDateTime startDateTime = startDate.atStartOfDay();
            LocalDateTime endDateTime = endDate.atTime(23, 59, 59);

            // 获取该月完成的课时数
            long lessonCount = lessonMapper.selectCount(
                    new LambdaQueryWrapper<Lesson>()
                            .eq(Lesson::getTenantId, tenantId)
                            .eq(Lesson::getStatus, "COMPLETED")
                            .ge(Lesson::getCreatedAt, startDateTime)
                            .le(Lesson::getCreatedAt, endDateTime)
            );

            Map<String, Object> item = new HashMap<>();
            item.put("month", String.format("%04d-%02d", startDate.getYear(), startDate.getMonthValue()));
            item.put("lessonCount", Math.toIntExact(lessonCount));
            item.put("studentCount", Math.toIntExact(studentCount));
            result.add(item);
        }

        return result;
    }

    @Override
    public List<Map<String, Object>> getCourseDistribution(String tenantId) {
        // 获取所有已完成的课时
        List<Lesson> lessons = lessonMapper.selectList(
                new LambdaQueryWrapper<Lesson>()
                        .eq(Lesson::getTenantId, tenantId)
                        .eq(Lesson::getStatus, "COMPLETED")
        );

        // 统计每个课程的完成次数
        Map<String, Long> courseMap = new LinkedHashMap<>();

        for (Lesson lesson : lessons) {
            String courseId = lesson.getCourseId();
            if (courseId == null) continue;

            Course course = courseMapper.selectById(courseId);
            String courseName = course != null ? course.getName() : "未知课程";

            courseMap.put(courseName, courseMap.getOrDefault(courseName, 0L) + 1);
        }

        // 转换为列表并按次数排序
        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Long> entry : courseMap.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", entry.getKey());
            item.put("value", Math.toIntExact(entry.getValue()));
            result.add(item);
        }

        result.sort((a, b) -> Integer.compare((Integer) b.get("value"), (Integer) a.get("value")));

        // 最多返回前 8 个
        if (result.size() > 8) {
            result = result.subList(0, 8);
        }

        return result;
    }

    /**
     * 格式化活动标题
     */
    private String formatActivityTitle(Lesson lesson) {
        String teacherName = "未知教师";
        String courseName = "未知课程";
        String className = "未知班级";

        if (lesson.getTeacherId() != null) {
            Teacher teacher = teacherMapper.selectById(lesson.getTeacherId());
            if (teacher != null) {
                teacherName = teacher.getName();
            }
        }

        if (lesson.getCourseId() != null) {
            Course course = courseMapper.selectById(lesson.getCourseId());
            if (course != null) {
                courseName = course.getName();
            }
        }

        if (lesson.getClassId() != null) {
            Clazz clazz = clazzMapper.selectById(lesson.getClassId());
            if (clazz != null) {
                className = clazz.getName();
            }
        }

        String status = lesson.getStatus();
        if ("COMPLETED".equals(status)) {
            return teacherName + "完成《" + courseName + "》授课";
        } else if ("IN_PROGRESS".equals(status)) {
            return teacherName + "正在进行《" + courseName + "》授课";
        } else if ("PLANNED".equals(status)) {
            return teacherName + "计划在" + className + "讲授《" + courseName + "》";
        } else if ("CANCELLED".equals(status)) {
            return teacherName + "取消了《" + courseName + "》授课";
        } else {
            return teacherName + "操作了《" + courseName + "》";
        }
    }
}
