package com.reading.platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reading.platform.dto.response.*;
import com.reading.platform.entity.*;
import com.reading.platform.mapper.*;
import com.reading.platform.service.TeacherDashboardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * 教师仪表板服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeacherDashboardServiceImpl implements TeacherDashboardService {

    private final LessonMapper lessonMapper;
    private final TaskMapper taskMapper;
    private final GrowthRecordMapper growthRecordMapper;
    private final NotificationMapper notificationMapper;
    private final CourseMapper courseMapper;

    @Override
    public TeacherDashboardResponse getDashboard(String teacherId, String tenantId) {
        TeacherDashboardResponse response = new TeacherDashboardResponse();

        response.setLessonCount(Math.toIntExact(lessonMapper.selectCount(
                new LambdaQueryWrapper<Lesson>()
                        .eq(Lesson::getTeacherId, teacherId)
                        .eq(Lesson::getTenantId, tenantId))));
        response.setTaskCount(Math.toIntExact(taskMapper.selectCount(
                new LambdaQueryWrapper<Task>()
                        .eq(Task::getCreatorId, teacherId)
                        .eq(Task::getTenantId, tenantId))));
        response.setGrowthRecordCount(Math.toIntExact(growthRecordMapper.selectCount(
                new LambdaQueryWrapper<GrowthRecord>()
                        .eq(GrowthRecord::getRecordedBy, teacherId)
                        .eq(GrowthRecord::getTenantId, tenantId))));
        response.setUnreadNotifications(Math.toIntExact(notificationMapper.selectCount(
                new LambdaQueryWrapper<Notification>()
                        .eq(Notification::getTenantId, tenantId)
                        .eq(Notification::getIsRead, 0))));

        return response;
    }

    @Override
    public List<LessonSimpleResponse> getTodayLessons(String teacherId, String tenantId) {
        LocalDate today = LocalDate.now();
        LambdaQueryWrapper<Lesson> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Lesson::getTeacherId, teacherId)
               .eq(Lesson::getTenantId, tenantId)
               .eq(Lesson::getLessonDate, today)
               .orderByAsc(Lesson::getStartTime);
        List<Lesson> lessons = lessonMapper.selectList(wrapper);
        return lessons.stream().map(this::convertToLessonSimpleResponse).collect(Collectors.toList());
    }

    @Override
    public List<LessonSimpleResponse> getWeeklyLessons(String teacherId, String tenantId) {
        LocalDate today = LocalDate.now();
        LocalDate weekStart = today.minusDays(today.getDayOfWeek().getValue() - 1);
        LocalDate weekEnd = weekStart.plusDays(6);
        LambdaQueryWrapper<Lesson> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Lesson::getTeacherId, teacherId)
               .eq(Lesson::getTenantId, tenantId)
               .between(Lesson::getLessonDate, weekStart, weekEnd)
               .orderByAsc(Lesson::getLessonDate, Lesson::getStartTime);
        List<Lesson> lessons = lessonMapper.selectList(wrapper);
        return lessons.stream().map(this::convertToLessonSimpleResponse).collect(Collectors.toList());
    }

    @Override
    public List<RecommendedCourseResponse> getRecommendedCourses(String tenantId) {
        // 返回租户的校本课程或系统推荐课程
        LambdaQueryWrapper<Course> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Course::getTenantId, tenantId)
               .eq(Course::getStatus, "published")
               .orderByDesc(Course::getCreatedAt)
               .last("LIMIT 5");
        List<Course> courses = courseMapper.selectList(wrapper);
        return courses.stream().map(c -> {
            RecommendedCourseResponse response = new RecommendedCourseResponse();
            response.setId(c.getId().toString());
            response.setName(c.getName());
            response.setCategory(c.getCategory());
            response.setDifficultyLevel(c.getDifficultyLevel());
            response.setCoverUrl(c.getCoverUrl());
            return response;
        }).collect(Collectors.toList());
    }

    @Override
    public List<LessonTrendDataPoint> getLessonTrend(String teacherId, Integer months) {
        int monthLimit = months != null ? months : 6;
        List<LessonTrendDataPoint> trend = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        LocalDate now = LocalDate.now();

        for (int i = monthLimit - 1; i >= 0; i--) {
            LocalDate monthStart = now.minusMonths(i).withDayOfMonth(1);
            LocalDate monthEnd = monthStart.plusMonths(1).minusDays(1);
            long count = lessonMapper.selectCount(new LambdaQueryWrapper<Lesson>()
                    .eq(Lesson::getTeacherId, teacherId)
                    .between(Lesson::getLessonDate, monthStart, monthEnd));

            LessonTrendDataPoint point = new LessonTrendDataPoint();
            point.setMonth(monthStart.format(formatter));
            point.setLessonCount((int) count);
            point.setTeacherCount(1); // 当前教师
            point.setStudentCount(0); // 简化实现
            trend.add(point);
        }
        return trend;
    }

    @Override
    public List<CourseUsageItemResponse> getCourseUsage(String teacherId) {
        // 返回教师使用课程的统计
        List<Lesson> lessons = lessonMapper.selectList(
                new LambdaQueryWrapper<Lesson>().eq(Lesson::getTeacherId, teacherId));

        Map<String, CourseUsageItemResponse> usageMap = new HashMap<>();
        for (Lesson lesson : lessons) {
            String courseId = lesson.getCourseId() != null ? lesson.getCourseId().toString() : null;
            if (courseId == null) continue;

            CourseUsageItemResponse item = usageMap.computeIfAbsent(courseId, k -> {
                CourseUsageItemResponse response = new CourseUsageItemResponse();
                response.setCourseId(courseId);
                response.setUsageCount(0);
                return response;
            });
            item.setUsageCount(item.getUsageCount() + 1);
        }

        // 获取课程名称
        List<String> courseIds = new ArrayList<>(usageMap.keySet());
        if (!courseIds.isEmpty()) {
            List<Course> courses = courseMapper.selectBatchIds(courseIds);
            for (Course course : courses) {
                CourseUsageItemResponse item = usageMap.get(course.getId().toString());
                if (item != null) {
                    item.setCourseName(course.getName());
                }
            }
        }

        return new ArrayList<>(usageMap.values());
    }

    private LessonSimpleResponse convertToLessonSimpleResponse(Lesson lesson) {
        LessonSimpleResponse response = new LessonSimpleResponse();
        response.setId(lesson.getId().toString());
        response.setTitle(lesson.getTitle());
        response.setStartTime(lesson.getStartTime() != null ? lesson.getStartTime().toString() : null);
        response.setEndTime(lesson.getEndTime() != null ? lesson.getEndTime().toString() : null);
        response.setLocation(lesson.getLocation());
        response.setStatus(lesson.getStatus());
        return response;
    }
}
