package com.lesingle.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lesingle.edu.dto.response.TeacherActivityRankResponse;
import com.lesingle.edu.dto.response.CourseUsageStatsVO;
import com.lesingle.edu.entity.Clazz;
import com.lesingle.edu.entity.Student;
import com.lesingle.edu.entity.Teacher;
import com.lesingle.edu.entity.Lesson;
import com.lesingle.edu.common.enums.LessonStatus;
import com.lesingle.edu.common.enums.TeacherActivityLevel;
import com.lesingle.edu.mapper.ClazzMapper;
import com.lesingle.edu.mapper.StudentMapper;
import com.lesingle.edu.mapper.TeacherMapper;
import com.lesingle.edu.mapper.LessonMapper;
import com.lesingle.edu.mapper.StudentRecordMapper;
import com.lesingle.edu.mapper.CoursePackageMapper;
import com.lesingle.edu.service.SchoolStatsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * 学校统计服务实现类
 */
@Slf4j
@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 StudentRecordMapper studentRecordMapper;
    private final CoursePackageMapper coursePackageMapper;

    @Override
    public Map<String, Object> getSchoolStats(Long tenantId) {
        Map<String, Object> stats = new HashMap<>();
        stats.put("teacherCount", teacherMapper.selectCount(
                new LambdaQueryWrapper<Teacher>().eq(Teacher::getTenantId, tenantId)
        ));
        stats.put("studentCount", studentMapper.selectCount(
                new LambdaQueryWrapper<Student>().eq(Student::getTenantId, tenantId)
        ));
        stats.put("classCount", clazzMapper.selectCount(
                new LambdaQueryWrapper<Clazz>().eq(Clazz::getTenantId, tenantId)
        ));

        // 月授课次数：本月自然月内该租户 COMPLETED 状态的 lesson 总数
        LocalDateTime monthStart = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
        LocalDateTime monthEnd = monthStart.plusMonths(1);
        Long monthlyLessons = lessonMapper.selectCount(
                new LambdaQueryWrapper<Lesson>()
                        .eq(Lesson::getTenantId, tenantId)
                        .eq(Lesson::getStatus, LessonStatus.COMPLETED.getCode())
                        .ge(Lesson::getEndDatetime, monthStart)
                        .lt(Lesson::getEndDatetime, monthEnd)
        );
        stats.put("lessonCount", monthlyLessons != null ? monthlyLessons.intValue() : 0);

        return stats;
    }

    @Override
    public List<TeacherActivityRankResponse> getActiveTeachers(Long tenantId, LocalDate startDate, LocalDate endDate, int limit) {
        // 计算时间范围
        LocalDateTime startTime;
        LocalDateTime endTime;

        if (startDate != null) {
            startTime = startDate.atStartOfDay();
        } else {
            // 默认本月 1 号
            startTime = LocalDateTime.now()
                    .withDayOfMonth(1)
                    .withHour(0)
                    .withMinute(0)
                    .withSecond(0)
                    .withNano(0);
        }

        if (endDate != null) {
            endTime = endDate.atTime(23, 59, 59);
        } else {
            // 默认今天
            endTime = LocalDateTime.now();
        }

        log.info("获取活跃教师排行，租户 ID: {}, 统计周期：{} ~ {}", tenantId, startTime, endTime);

        // 调用 Mapper 查询原始数据
        List<Map<String, Object>> rawData = lessonMapper.getTeacherActivityRank(tenantId, startTime, endTime, limit);

        if (rawData == null || rawData.isEmpty()) {
            log.info("未查询到活跃教师数据");
            return Collections.emptyList();
        }

        // 转换为响应对象
        return rawData.stream().map(row -> {
            Integer lessonCount = convertToInt(row.get("lessonCount"));
            Integer courseCount = convertToInt(row.get("courseCount"));
            LocalDateTime lastActiveAt = (LocalDateTime) row.get("lastActiveAt");
            String classNames = (String) row.get("classNames");

            // 根据授课次数计算活跃度等级
            TeacherActivityLevel activityLevel = TeacherActivityLevel.fromLessonCount(lessonCount);

            return TeacherActivityRankResponse.builder()
                    .teacherId((Long) row.get("teacherId"))
                    .teacherName((String) row.get("teacherName"))
                    .classNames(classNames != null ? classNames : "")
                    .lessonCount(lessonCount)
                    .courseCount(courseCount)
                    .lastActiveAt(lastActiveAt)
                    .activityLevelCode(activityLevel.getCode())
                    .activityLevelDesc(activityLevel.getDescription())
                    .build();
        }).collect(Collectors.toList());
    }

    /**
     * 将 Object 转换为 Integer，处理 null 和 Number 类型
     */
    private Integer convertToInt(Object value) {
        if (value == null) {
            return 0;
        }
        if (value instanceof Number) {
            return ((Number) value).intValue();
        }
        return 0;
    }

    @Override
    public List<Map<String, Object>> getCourseUsageStats(Long tenantId, LocalDate startDate, LocalDate endDate) {
        // 计算时间范围
        LocalDateTime startTime;
        LocalDateTime endTime;

        if (startDate != null) {
            startTime = startDate.atStartOfDay();
        } else {
            // 默认本月 1 号
            startTime = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        }

        if (endDate != null) {
            endTime = endDate.atTime(23, 59, 59);
        } else {
            // 默认今天
            endTime = LocalDateTime.now();
        }

        // 调用 Mapper 查询（教师 ID 为 null 表示统计全校）
        List<CourseUsageStatsVO> stats = lessonMapper.getCourseUsageStats(
                tenantId, null, startTime, endTime
        );

        log.info("获取学校课程使用统计，租户 ID: {}, 统计周期：{} ~ {}, 返回{}条数据",
                tenantId, startTime, endTime, stats != null ? stats.size() : 0);

        // 转换为 Map 格式返回（兼容前端现有类型）
        if (stats == null || stats.isEmpty()) {
            return new ArrayList<>();
        }

        return stats.stream().map(vo -> {
            Map<String, Object> map = new HashMap<>();
            map.put("courseId", vo.getCoursePackageId());
            map.put("courseName", vo.getCoursePackageName());
            map.put("usageCount", vo.getUsageCount());
            map.put("studentCount", vo.getStudentCount() != null ? vo.getStudentCount() : 0);
            map.put("avgDuration", vo.getAvgDuration() != null ? vo.getAvgDuration() : 0);
            map.put("lastUsedAt", vo.getLastUsedAt());
            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> getLessonTrend(Long tenantId, LocalDate startDate, LocalDate endDate) {
        // 计算时间范围
        LocalDateTime startTime;
        LocalDateTime endTime;

        if (startDate != null) {
            startTime = startDate.atStartOfDay();
        } else {
            // 默认 7 天前
            startTime = LocalDateTime.now().minusDays(7).withHour(0).withMinute(0).withSecond(0).withNano(0);
        }

        if (endDate != null) {
            endTime = endDate.atTime(23, 59, 59);
        } else {
            // 默认今天
            endTime = LocalDateTime.now();
        }

        List<Map<String, Object>> trend = new ArrayList<>();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM-dd");

        // 按天统计
        LocalDate currentDate = startTime.toLocalDate();
        LocalDate endDateLocal = endTime.toLocalDate();
        while (!currentDate.isAfter(endDateLocal)) {
            String dateStr = currentDate.format(dateFormatter);

            // 当天时间范围
            LocalDateTime dayStart = currentDate.atStartOfDay();
            LocalDateTime dayEnd = currentDate.plusDays(1).atStartOfDay();

            // 当天完成的授课次数（按租户过滤）
            Long lessons = lessonMapper.selectCount(
                    new LambdaQueryWrapper<Lesson>()
                            .eq(Lesson::getTenantId, tenantId)
                            .eq(Lesson::getStatus, LessonStatus.COMPLETED.getCode())
                            .ge(Lesson::getEndDatetime, dayStart)
                            .lt(Lesson::getEndDatetime, dayEnd)
            );

            // 当天活跃学生数（按租户过滤）
            Long activeStudents = studentRecordMapper.countActiveStudentsByTenant(tenantId, dayStart, dayEnd);

            Map<String, Object> item = new HashMap<>();
            item.put("date", dateStr);
            item.put("lessonCount", lessons != null ? lessons.intValue() : 0);
            item.put("studentCount", activeStudents != null ? activeStudents.intValue() : 0);
            trend.add(item);

            currentDate = currentDate.plusDays(1);
        }

        return trend;
    }

    @Override
    public List<Map<String, Object>> getCourseDistribution(Long tenantId) {
        // 调用 Mapper 查询课程分布数据
        List<Map<String, Object>> result = coursePackageMapper.getCourseDistribution(tenantId);

        // 处理空数据情况，确保返回空列表而不是 null
        if (result == null) {
            return new ArrayList<>();
        }

        // 限制返回数量，最多返回前 10 个课程包
        if (result.size() > 10) {
            return result.subList(0, 10);
        }

        return result;
    }
}
