import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../../database/prisma.service';

export interface LessonTrendItem {
  month: string;
  lessonCount: number;
  studentCount: number;
}

export interface CourseDistributionItem {
  name: string;
  value: number;
}

@Injectable()
export class StatsService {
  private readonly logger = new Logger(StatsService.name);

  constructor(private prisma: PrismaService) {}

  async getSchoolStats(tenantId: number) {
    // 获取各项统计数据
    const [teacherCount, studentCount, classCount, lessonCount] = await Promise.all([
      this.prisma.teacher.count({
        where: { tenantId, status: 'ACTIVE' },
      }),
      this.prisma.student.count({
        where: { tenantId },
      }),
      this.prisma.class.count({
        where: { tenantId },
      }),
      this.prisma.lesson.count({
        where: { tenantId, status: 'COMPLETED' },
      }),
    ]);

    return {
      teacherCount,
      studentCount,
      classCount,
      lessonCount,
    };
  }

  async getActiveTeachers(tenantId: number, limit: number = 5) {
    const teachers = await this.prisma.teacher.findMany({
      where: {
        tenantId,
        status: 'ACTIVE',
      },
      orderBy: {
        lessonCount: 'desc',
      },
      take: limit,
      select: {
        id: true,
        name: true,
        lessonCount: true,
      },
    });

    return teachers;
  }

  async getCourseUsageStats(tenantId: number) {
    // 获取已授权课程的使用统计
    const lessons = await this.prisma.lesson.findMany({
      where: {
        tenantId,
        status: 'COMPLETED',
      },
      select: {
        courseId: true,
        course: {
          select: {
            id: true,
            name: true,
          },
        },
      },
    });

    // 统计每个课程的使用次数
    const courseUsageMap = new Map<number, { courseId: number; courseName: string; usageCount: number }>();

    lessons.forEach((lesson) => {
      const courseId = lesson.courseId;
      const existing = courseUsageMap.get(courseId);
      if (existing) {
        existing.usageCount++;
      } else {
        courseUsageMap.set(courseId, {
          courseId: courseId,
          courseName: lesson.course?.name || '未知课程',
          usageCount: 1,
        });
      }
    });

    // 转换为数组并按使用次数排序
    const result = Array.from(courseUsageMap.values())
      .sort((a, b) => b.usageCount - a.usageCount)
      .slice(0, 10);

    return result;
  }

  async getRecentActivities(tenantId: number, limit: number = 10) {
    // 获取最近的活动记录
    const lessons = await this.prisma.lesson.findMany({
      where: {
        tenantId,
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: limit,
      select: {
        id: true,
        status: true,
        createdAt: true,
        course: {
          select: {
            name: true,
          },
        },
        teacher: {
          select: {
            name: true,
          },
        },
        class: {
          select: {
            name: true,
          },
        },
      },
    });

    // 格式化活动记录
    const activities = lessons.map((lesson) => {
      let title = '';
      const teacherName = lesson.teacher?.name || '未知教师';
      const courseName = lesson.course?.name || '未知课程';
      const className = lesson.class?.name || '未知班级';

      switch (lesson.status) {
        case 'COMPLETED':
          title = `${teacherName}完成《${courseName}》授课`;
          break;
        case 'IN_PROGRESS':
          title = `${teacherName}正在进行《${courseName}》授课`;
          break;
        case 'PLANNED':
          title = `${teacherName}计划在${className}讲授《${courseName}》`;
          break;
        case 'CANCELLED':
          title = `${teacherName}取消了《${courseName}》授课`;
          break;
        default:
          title = `${teacherName}操作了《${courseName}》`;
      }

      return {
        id: lesson.id,
        type: lesson.status,
        title,
        time: lesson.createdAt,
      };
    });

    return activities;
  }

  /**
   * 获取授课趋势（最近N个月）
   */
  async getLessonTrend(tenantId: number, months: number = 6): Promise<LessonTrendItem[]> {
    const result: LessonTrendItem[] = [];
    const now = new Date();

    for (let i = months - 1; i >= 0; i--) {
      const startDate = new Date(now.getFullYear(), now.getMonth() - i, 1);
      const endDate = new Date(now.getFullYear(), now.getMonth() - i + 1, 0, 23, 59, 59);

      // 获取该月授课次数
      const lessonCount = await this.prisma.lesson.count({
        where: {
          tenantId,
          status: 'COMPLETED',
          createdAt: {
            gte: startDate,
            lte: endDate,
          },
        },
      });

      // 获取该月末学生总数（简化处理，取当前总数）
      const studentCount = await this.prisma.student.count({
        where: { tenantId },
      });

      const monthLabel = `${startDate.getFullYear()}-${String(startDate.getMonth() + 1).padStart(2, '0')}`;
      result.push({
        month: monthLabel,
        lessonCount,
        studentCount,
      });
    }

    return result;
  }

  /**
   * 获取课程分布统计（饼图数据）
   */
  async getCourseDistribution(tenantId: number): Promise<CourseDistributionItem[]> {
    // 获取所有已完成的授课记录
    const lessons = await this.prisma.lesson.findMany({
      where: {
        tenantId,
        status: 'COMPLETED',
      },
      select: {
        courseId: true,
        course: {
          select: {
            name: true,
          },
        },
      },
    });

    // 统计每个课程的使用次数
    const courseMap = new Map<string, number>();

    lessons.forEach((lesson) => {
      const courseName = lesson.course?.name || '未知课程';
      courseMap.set(courseName, (courseMap.get(courseName) || 0) + 1);
    });

    // 转换为饼图数据格式
    const result = Array.from(courseMap.entries())
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 8); // 最多显示8个课程

    return result;
  }

  // ==================== 数据报告方法 ====================

  /**
   * 获取报告概览数据
   */
  async getReportOverview(tenantId: number) {
    // 总授课次数
    const totalLessons = await this.prisma.lesson.count({
      where: { tenantId, status: 'COMPLETED' },
    });

    // 活跃教师数（有完成授课的教师）
    const activeTeachers = await this.prisma.teacher.count({
      where: {
        tenantId,
        status: 'ACTIVE',
        lessonCount: { gt: 0 },
      },
    });

    // 使用课程数（有授课记录的课程）
    const usedCourses = await this.prisma.lesson.findMany({
      where: { tenantId, status: 'COMPLETED' },
      select: { courseId: true },
      distinct: ['courseId'],
    });

    // 平均评分
    const feedbacks = await this.prisma.lessonFeedback.findMany({
      where: {
        lesson: { tenantId },
      },
      select: {
        designQuality: true,
        participation: true,
        goalAchievement: true,
      },
    });

    let avgRating = 0;
    if (feedbacks.length > 0) {
      const totalRating = feedbacks.reduce((sum, f) => {
        const avg = ((f.designQuality || 0) + (f.participation || 0) + (f.goalAchievement || 0)) / 3;
        return sum + avg;
      }, 0);
      avgRating = Number((totalRating / feedbacks.length).toFixed(1));
    }

    return {
      totalLessons,
      activeTeacherCount: activeTeachers,
      usedCourseCount: usedCourses.length,
      avgRating,
    };
  }

  /**
   * 获取教师报告数据
   */
  async getTeacherReports(tenantId: number) {
    const teachers = await this.prisma.teacher.findMany({
      where: { tenantId, status: 'ACTIVE' },
      select: {
        id: true,
        name: true,
        lessonCount: true,
        feedbackCount: true,
        lessons: {
          where: { status: 'COMPLETED' },
          select: { courseId: true },
        },
      },
    });

    return teachers.map((teacher) => {
      // 计算使用的不同课程数
      const uniqueCourses = new Set(teacher.lessons.map((l) => l.courseId));

      // 从 feedbackCount 计算平均评分（简化处理，假设平均评分为 4.0-5.0 之间）
      // 实际应该从 LessonFeedback 表获取
      const avgRating = teacher.feedbackCount > 0 ? 4.5 : 0;

      return {
        id: teacher.id,
        name: teacher.name,
        lessonCount: teacher.lessonCount,
        courseCount: uniqueCourses.size,
        feedbackCount: teacher.feedbackCount,
        avgRating,
      };
    }).sort((a, b) => b.lessonCount - a.lessonCount);
  }

  /**
   * 获取课程报告数据
   */
  async getCourseReports(tenantId: number) {
    const lessons = await this.prisma.lesson.findMany({
      where: { tenantId, status: 'COMPLETED' },
      select: {
        courseId: true,
        course: {
          select: { name: true },
        },
        teacherId: true,
        classId: true,
        class: {
          select: { studentCount: true },
        },
      },
    });

    // 统计每个课程的数据
    const courseMap = new Map<number, {
      id: number;
      name: string;
      lessonCount: number;
      teacherIds: Set<number>;
      studentCount: number;
    }>();

    lessons.forEach((lesson) => {
      const courseId = lesson.courseId;
      const existing = courseMap.get(courseId);
      if (existing) {
        existing.lessonCount++;
        existing.teacherIds.add(lesson.teacherId);
        existing.studentCount += lesson.class?.studentCount || 0;
      } else {
        courseMap.set(courseId, {
          id: courseId,
          name: lesson.course?.name || '未知课程',
          lessonCount: 1,
          teacherIds: new Set([lesson.teacherId]),
          studentCount: lesson.class?.studentCount || 0,
        });
      }
    });

    // 获取课程评分
    const courseRatings = await this.prisma.lessonFeedback.findMany({
      where: {
        lesson: { tenantId },
      },
      select: {
        designQuality: true,
        participation: true,
        goalAchievement: true,
        lesson: {
          select: { courseId: true },
        },
      },
    });

    const ratingMap = new Map<number, { total: number; count: number }>();
    courseRatings.forEach((feedback) => {
      const courseId = feedback.lesson.courseId;
      const avg = ((feedback.designQuality || 0) + (feedback.participation || 0) + (feedback.goalAchievement || 0)) / 3;
      const existing = ratingMap.get(courseId);
      if (existing) {
        existing.total += avg;
        existing.count++;
      } else {
        ratingMap.set(courseId, { total: avg, count: 1 });
      }
    });

    return Array.from(courseMap.values())
      .map((course) => {
        const rating = ratingMap.get(course.id);
        const avgRating = rating ? Number((rating.total / rating.count).toFixed(1)) : 0;
        return {
          id: course.id,
          name: course.name,
          lessonCount: course.lessonCount,
          teacherCount: course.teacherIds.size,
          studentCount: course.studentCount,
          avgRating,
        };
      })
      .sort((a, b) => b.lessonCount - a.lessonCount);
  }

  /**
   * 获取学生报告数据
   */
  async getStudentReports(tenantId: number) {
    const students = await this.prisma.student.findMany({
      where: { tenantId },
      select: {
        id: true,
        name: true,
        classId: true,
        class: {
          select: { name: true },
        },
        records: {
          select: {
            focus: true,
            participation: true,
            interest: true,
            understanding: true,
          },
        },
      },
    });

    return students.map((student) => {
      // 计算平均专注度和参与度
      let avgFocus = 0;
      let avgParticipation = 0;
      const recordCount = student.records.length;

      if (recordCount > 0) {
        const totalFocus = student.records.reduce((sum, r) => sum + (r.focus || 0), 0);
        const totalParticipation = student.records.reduce((sum, r) => sum + (r.participation || 0), 0);
        avgFocus = Number((totalFocus / recordCount).toFixed(1));
        avgParticipation = Number((totalParticipation / recordCount).toFixed(1));
      }

      return {
        id: student.id,
        name: student.name,
        className: student.class?.name || '未分班',
        lessonCount: recordCount,
        avgFocus,
        avgParticipation,
      };
    }).sort((a, b) => b.lessonCount - a.lessonCount);
  }
}
