/**
 * Mock 班级详情 + 课表数据（P7-admin：班级详情聚合）
 *
 * 维护者：ai13（teacher-portal）
 *
 * 覆盖：
 * - 5 个班级详情（基本信息 + 学生 + 课表 + 近期作业 + 概览统计 + 成绩趋势）
 * - 课表数据（5 班 × 周一到周五 × 8 节 = 200 节）
 */

import type {
  ClassDetail,
  ClassDetailAggregate,
  ClassDetailStudent,
  ClassDetailHomework,
  ClassOverviewStats,
  ClassDetailTrendPoint,
  ClassScheduleItem,
} from "@/lib/graphql-p7-admin";
import { EXTENDED_CLASSES, SUBJECTS } from "./grades-extended";

/** 班级任课教师（确定性生成） */
const CLASS_TEACHERS = [
  "王老师",
  "刘老师",
  "陈老师",
  "杨老师",
  "周老师",
] as const;

/** 班主任名单 */
const HOMEROOM_TEACHERS = [
  "王主任",
  "李主任",
  "张主任",
  "赵主任",
  "钱主任",
] as const;

/** 教室编号 */
const ROOMS = ["A101", "A102", "A103", "A104", "A105"] as const;

/** 学校名 */
const SCHOOL_NAME = "示范中学";

/** 8 节课的起止时间 */
const PERIOD_TIMES: Array<{ start: string; end: string }> = [
  { start: "08:00", end: "08:45" },
  { start: "08:55", end: "09:40" },
  { start: "10:00", end: "10:45" },
  { start: "10:55", end: "11:40" },
  { start: "13:30", end: "14:15" },
  { start: "14:25", end: "15:10" },
  { start: "15:25", end: "16:10" },
  { start: "16:20", end: "17:05" },
];

/** 班级学科（班主任学科） */
const CLASS_SUBJECTS = ["数学", "语文", "英语", "物理", "化学"] as const;

/** 学生姓名（确定性） */
function studentNameFor(studentIdx: number): string {
  return `学生${String(studentIdx).padStart(2, "0")}`;
}

/** 学生学号 */
function studentNoFor(classIdx: number, studentIdx: number): string {
  return `2026${String(classIdx + 1).padStart(2, "0")}${String(studentIdx).padStart(3, "0")}`;
}

/** 学生邮箱 */
function emailFor(classIdx: number, studentIdx: number): string {
  return `student${classIdx + 1}_${studentIdx}@edu.test`;
}

/** 班级学生列表生成 */
function buildStudents(
  classId: string,
  classIdx: number,
  count: number,
): ClassDetailStudent[] {
  const items: ClassDetailStudent[] = [];
  for (let i = 1; i <= count; i++) {
    items.push({
      id: `stu-${classId.slice(-4)}-${String(i).padStart(3, "0")}`,
      name: studentNameFor(i),
      studentNo: studentNoFor(classIdx, i),
      email: emailFor(classIdx, i),
    });
  }
  return items;
}

/** 班级详情生成 */
function buildClassDetail(
  classId: string,
  classIdx: number,
): ClassDetail {
  const cls = EXTENDED_CLASSES[classIdx];
  const subject = CLASS_SUBJECTS[classIdx] ?? "数学";
  return {
    id: classId,
    name: cls?.name ?? `班级${classIdx + 1}`,
    gradeId: cls?.gradeId ?? "grade-12",
    subject,
    studentCount: 30,
    homeroomTeacher: HOMEROOM_TEACHERS[classIdx] ?? "王主任",
    room: ROOMS[classIdx] ?? "A101",
    schoolName: SCHOOL_NAME,
  };
}

/** 课表生成（5 班 × 周一到周五 × 8 节 = 200 节） */
function buildSchedule(
  classId: string,
  classIdx: number,
): ClassScheduleItem[] {
  const cls = EXTENDED_CLASSES[classIdx];
  const items: ClassScheduleItem[] = [];
  // 每天最多 6 节（最后两节为自习或空）
  const subjectRotation = SUBJECTS;
  for (let day = 1; day <= 5; day++) {
    for (let period = 1; period <= 8; period++) {
      // 第 7、8 节多数为自习（保留少量科目）
      const isSelfStudy = period >= 7 && (day + period) % 2 === 0;
      const subjectIdx = (day + period + classIdx) % subjectRotation.length;
      const subject = isSelfStudy
        ? "自习"
        : (subjectRotation[subjectIdx] ?? "数学");
      const teacherIdx = (day + period + classIdx) % CLASS_TEACHERS.length;
      const times = PERIOD_TIMES[period - 1];
      if (!times) continue;
      items.push({
        id: `sch-${classId.slice(-4)}-${day}-${period}`,
        classId,
        className: cls?.name ?? `班级${classIdx + 1}`,
        dayOfWeek: day,
        period,
        subject,
        teacherName: isSelfStudy
          ? "—"
          : (CLASS_TEACHERS[teacherIdx] ?? "未知"),
        room: ROOMS[classIdx] ?? "A101",
        startTime: times.start,
        endTime: times.end,
      });
    }
  }
  return items;
}

/** 近期作业生成（5 个） */
function buildRecentHomework(classId: string): ClassDetailHomework[] {
  const items: ClassDetailHomework[] = [];
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  for (let i = 0; i < 5; i++) {
    const due = new Date(today);
    due.setDate(due.getDate() + i - 1);
    const dueStr = `${due.getFullYear()}-${String(due.getMonth() + 1).padStart(2, "0")}-${String(due.getDate()).padStart(2, "0")}`;
    const subject = SUBJECTS[i % SUBJECTS.length] ?? "数学";
    items.push({
      id: `hw-${classId.slice(-4)}-${i}`,
      title: `${subject} - 作业 ${i + 1}`,
      dueDate: dueStr,
      submissionRate: 70 + ((i * 7) % 25),
      avgScore: i === 4 ? null : 75 + ((i * 5) % 18),
    });
  }
  return items;
}

/** 概览统计 */
function buildOverview(
  classId: string,
  classIdx: number,
): ClassOverviewStats {
  const base = 78 + classIdx * 2;
  return {
    attendanceRate: 90 + (classIdx % 5),
    averageScore: base,
    homeworkCompletionRate: 80 + (classIdx % 10),
    recentExamTitle: `高三第${classIdx + 1}次月考`,
    recentExamAvg: base - 4,
  };
}

/** 成绩趋势（6 个月） */
function buildTrend(classId: string): ClassDetailTrendPoint[] {
  const months = ["1月", "2月", "3月", "4月", "5月", "6月"];
  const base = 75 + (classId.charCodeAt(classId.length - 1) % 8);
  return months.map((m, i) => ({
    month: m,
    avgScore: base + ((i * 3) % 8) - 2,
  }));
}

/** 班级详情缓存（按 id 索引） */
const CLASS_DETAIL_CACHE: Record<string, ClassDetailAggregate> = {};

/** 初始化所有班级详情 */
function initClassDetails(): void {
  EXTENDED_CLASSES.forEach((cls, idx) => {
    const classId = cls.id;
    CLASS_DETAIL_CACHE[classId] = {
      class: buildClassDetail(classId, idx),
      students: buildStudents(classId, idx, 30),
      schedule: buildSchedule(classId, idx),
      recentHomework: buildRecentHomework(classId),
      overview: buildOverview(classId, idx),
      trend: buildTrend(classId),
    };
  });
}

initClassDetails();

/** 查询班级详情聚合 */
export function queryClassDetail(
  classId: string,
): ClassDetailAggregate | null {
  return CLASS_DETAIL_CACHE[classId] ?? null;
}

/** 查询班级课表（支持 classId 过滤） */
export function queryClassSchedule(classId?: string): ClassScheduleItem[] {
  const allItems: ClassScheduleItem[] = [];
  for (const cls of EXTENDED_CLASSES) {
    const detail = CLASS_DETAIL_CACHE[cls.id];
    if (!detail) continue;
    if (classId && cls.id !== classId) continue;
    allItems.push(...detail.schedule);
  }
  // 按 dayOfWeek 升序，再按 period 升序
  allItems.sort((a, b) => {
    if (a.dayOfWeek !== b.dayOfWeek) return a.dayOfWeek - b.dayOfWeek;
    return a.period - b.period;
  });
  return allItems;
}

/** 班级详情基本信息（独立访问） */
export function queryClassBasicInfo(classId: string): ClassDetail | null {
  return CLASS_DETAIL_CACHE[classId]?.class ?? null;
}

/** 班级课表按 dayOfWeek 分组 */
export function groupScheduleByDay(
  schedule: ClassScheduleItem[],
): Record<number, ClassScheduleItem[]> {
  const grouped: Record<number, ClassScheduleItem[]> = {
    1: [],
    2: [],
    3: [],
    4: [],
    5: [],
    6: [],
    7: [],
  };
  for (const item of schedule) {
    const list = grouped[item.dayOfWeek];
    if (list) list.push(item);
  }
  return grouped;
}
