/**
 * GraphQL operations - P7 扩展（行政管理子模块：考勤 + 班级详情 + 课表 + 请假 + 调课）
 *
 * 维护者：ai13（teacher-portal）
 * 关联：graphql.ts P2/P3 扩展、workline.md §3 P7 交付物
 *
 * schema 尚未在 ARB-001 P2 第一版中定义，开发期通过 MSW 拦截返回 mock 响应；
 * 上游就绪后由 ai03 在 teacher-bff.graphql 扩展，届时合并本文件到 graphql.ts。
 *
 * 查询范围（P7-admin）：
 * - AttendanceList：考勤记录列表（按 classId/date/status 筛选 + 分页）
 * - AttendanceSheet：批量录入用学生 + 当天状态
 * - SaveAttendanceSheet：批量保存考勤录入
 * - AttendanceStats：班级考勤统计（出勤率/迟到率/早退率/请假率/预警/趋势）
 * - AttendanceReport：周报/月报数据
 * - ClassDetail：班级详情聚合（基本信息 + 学生 + 课表 + 近期作业 + 概览统计）
 * - ClassSchedule：班级课表（周一到周日 × 节次）
 * - LeaveRequests：教师请假审批列表
 * - ApproveLeaveRequest：批准/拒绝请假
 * - SubmitLeaveRequest：教师提交请假/调课申请
 * - ScheduleChanges：我的调课申请列表
 */

import { gql } from "urql";
import type { DataScope } from "./graphql";

// ============ Types（考勤） ============

/** 考勤状态 */
export type AttendanceStatus =
  | "PRESENT"
  | "ABSENT"
  | "LATE"
  | "EARLY_LEAVE"
  | "LEAVE";

/** 考勤记录项 */
export interface AttendanceRecord {
  id: string;
  classId: string;
  className: string;
  studentId: string;
  studentName: string;
  studentNo: string;
  date: string; // YYYY-MM-DD
  status: AttendanceStatus;
  note: string | null;
}

/** 考勤列表筛选条件 */
export interface AttendanceListFilter {
  classId?: string | null;
  startDate?: string | null;
  endDate?: string | null;
  statuses?: AttendanceStatus[] | null;
  page?: number | null;
  pageSize?: number | null;
}

/** 考勤列表分页结果 */
export interface AttendanceListResult {
  items: AttendanceRecord[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

/** 考勤录入项（按学生 + 日期） */
export interface AttendanceSheetItem {
  studentId: string;
  studentName: string;
  studentNo: string;
  date: string;
  status: AttendanceStatus | null;
  note: string | null;
}

/** 考勤批量保存项 */
export interface SaveAttendanceRecordInput {
  studentId: string;
  status: AttendanceStatus;
  note?: string | null;
}

/** 考勤批量保存输入 */
export interface SaveAttendanceSheetInput {
  classId: string;
  date: string;
  records: SaveAttendanceRecordInput[];
}

/** 考勤批量保存结果 */
export interface SaveAttendanceSheetResult {
  classId: string;
  date: string;
  savedCount: number;
  savedAt: string;
}

// ============ Types（考勤统计） ============

/** 班级考勤统计 */
export interface AttendanceStats {
  classId: string;
  className: string;
  startDate: string;
  endDate: string;
  totalRecords: number;
  presentCount: number;
  absentCount: number;
  lateCount: number;
  earlyLeaveCount: number;
  leaveCount: number;
  presentRate: number;
  lateRate: number;
  earlyLeaveRate: number;
  leaveRate: number;
  warningCount: number;
  trend: AttendanceTrendPoint[];
}

/** 考勤趋势点 */
export interface AttendanceTrendPoint {
  date: string;
  presentRate: number;
  lateRate: number;
  absentRate: number;
}

/** 班级考勤对比项 */
export interface AttendanceClassComparison {
  classId: string;
  className: string;
  presentRate: number;
  lateRate: number;
  absentRate: number;
}

/** 学生考勤预警项 */
export interface AttendanceWarning {
  studentId: string;
  studentName: string;
  studentNo: string;
  className: string;
  presentRate: number;
  absentCount: number;
  lateCount: number;
}

// ============ Types（考勤报告） ============

/** 报告类型 */
export type AttendanceReportType = "WEEKLY" | "MONTHLY";

/** 考勤报告数据 */
export interface AttendanceReport {
  classId: string;
  className: string;
  reportType: AttendanceReportType;
  startDate: string;
  endDate: string;
  generatedAt: string;
  summary: AttendanceReportSummary;
  details: AttendanceReportDetail[];
}

/** 考勤报告摘要 */
export interface AttendanceReportSummary {
  totalRecords: number;
  presentRate: number;
  lateRate: number;
  earlyLeaveRate: number;
  leaveRate: number;
  warningCount: number;
}

/** 考勤报告明细 */
export interface AttendanceReportDetail {
  studentId: string;
  studentName: string;
  studentNo: string;
  presentCount: number;
  absentCount: number;
  lateCount: number;
  earlyLeaveCount: number;
  leaveCount: number;
  presentRate: number;
}

// ============ Types（班级详情） ============

/** 班级详情 */
export interface ClassDetail {
  id: string;
  name: string;
  gradeId: string;
  subject: string;
  studentCount: number;
  homeroomTeacher: string;
  room: string | null;
  schoolName: string;
}

/** 班级详情聚合 */
export interface ClassDetailAggregate {
  class: ClassDetail;
  students: ClassDetailStudent[];
  schedule: ClassScheduleItem[];
  recentHomework: ClassDetailHomework[];
  overview: ClassOverviewStats;
  trend: ClassDetailTrendPoint[];
}

/** 班级详情学生 */
export interface ClassDetailStudent {
  id: string;
  name: string;
  studentNo: string;
  email: string;
}

/** 班级详情近期作业 */
export interface ClassDetailHomework {
  id: string;
  title: string;
  dueDate: string;
  submissionRate: number;
  avgScore: number | null;
}

/** 班级概览统计 */
export interface ClassOverviewStats {
  attendanceRate: number;
  averageScore: number;
  homeworkCompletionRate: number;
  recentExamTitle: string | null;
  recentExamAvg: number | null;
}

/** 班级详情趋势点 */
export interface ClassDetailTrendPoint {
  month: string;
  avgScore: number;
}

// ============ Types（课表） ============

/** 课表项 */
export interface ClassScheduleItem {
  id: string;
  classId: string;
  className: string;
  dayOfWeek: number; // 1=周一 ... 7=周日
  period: number; // 第 N 节（1-8）
  subject: string;
  teacherName: string;
  room: string;
  startTime: string;
  endTime: string;
}

// ============ Types（请假） ============

/** 请假类型 */
export type LeaveType = "SICK" | "PERSONAL" | "ANNUAL" | "OTHER";

/** 请假申请状态 */
export type LeaveStatus = "PENDING" | "APPROVED" | "REJECTED";

/** 请假申请项 */
export interface LeaveRequest {
  id: string;
  applicantId: string;
  applicantName: string;
  applicantRole: string;
  type: LeaveType;
  startDate: string;
  endDate: string;
  reason: string;
  status: LeaveStatus;
  submittedAt: string;
  reviewedAt: string | null;
  reviewerId: string | null;
  reviewerName: string | null;
  reviewComment: string | null;
}

/** 请假列表筛选 */
export interface LeaveRequestsFilter {
  dataScope?: DataScope | null;
  status?: LeaveStatus | null;
  page?: number | null;
  pageSize?: number | null;
}

/** 请假列表分页结果 */
export interface LeaveRequestsResult {
  items: LeaveRequest[];
  total: number;
  page: number;
  pageSize: number;
}

/** 审批请假输入 */
export interface ApproveLeaveRequestInput {
  requestId: string;
  action: "APPROVE" | "REJECT";
  comment?: string | null;
}

/** 审批请假结果 */
export interface ApproveLeaveRequestResult {
  requestId: string;
  status: LeaveStatus;
  reviewedAt: string;
  reviewerId: string;
  reviewerName: string;
  reviewComment: string | null;
}

/** 提交请假申请输入 */
export interface SubmitLeaveRequestInput {
  type: LeaveType;
  startDate: string;
  endDate: string;
  reason: string;
}

/** 提交请假申请结果 */
export interface SubmitLeaveRequestResult {
  requestId: string;
  status: LeaveStatus;
  submittedAt: string;
}

// ============ Types（调课） ============

/** 调课类型 */
export type ScheduleChangeType = "ADJUST" | "SUBSTITUTE";

/** 调课状态 */
export type ScheduleChangeStatus = "PENDING" | "APPROVED" | "REJECTED";

/** 调课申请项 */
export interface ScheduleChange {
  id: string;
  requesterId: string;
  requesterName: string;
  classId: string;
  className: string;
  originalDate: string;
  originalPeriod: number;
  originalSubject: string;
  adjustedDate: string;
  adjustedPeriod: number;
  adjustedSubject: string;
  substituteTeacherId: string | null;
  substituteTeacherName: string | null;
  type: ScheduleChangeType;
  reason: string;
  status: ScheduleChangeStatus;
  submittedAt: string;
  reviewedAt: string | null;
  reviewComment: string | null;
}

/** 调课列表分页结果 */
export interface ScheduleChangesResult {
  items: ScheduleChange[];
  total: number;
  page: number;
  pageSize: number;
}

/** 提交调课申请输入 */
export interface SubmitScheduleChangeInput {
  classId: string;
  originalDate: string;
  originalPeriod: number;
  originalSubject: string;
  adjustedDate: string;
  adjustedPeriod: number;
  adjustedSubject: string;
  substituteTeacherId?: string | null;
  type: ScheduleChangeType;
  reason: string;
}

/** 提交调课申请结果 */
export interface SubmitScheduleChangeResult {
  requestId: string;
  status: ScheduleChangeStatus;
  submittedAt: string;
}

// ============ Queries / Mutations ============

/** 考勤记录列表查询 */
export const AttendanceListQuery = gql`
  query AttendanceList($filter: AttendanceListFilterInput) {
    attendanceList(filter: $filter) {
      items {
        id
        classId
        className
        studentId
        studentName
        studentNo
        date
        status
        note
      }
      total
      page
      pageSize
      totalPages
    }
  }
`;

/** 考勤录入查询（学生列表 + 当天状态） */
export const AttendanceSheetQuery = gql`
  query AttendanceSheet($classId: ID!, $date: String!) {
    attendanceSheet(classId: $classId, date: $date) {
      studentId
      studentName
      studentNo
      date
      status
      note
    }
  }
`;

/** 批量保存考勤 Mutation */
export const SaveAttendanceSheetMutation = gql`
  mutation SaveAttendanceSheet($input: SaveAttendanceSheetInput!) {
    saveAttendanceSheet(input: $input) {
      classId
      date
      savedCount
      savedAt
    }
  }
`;

/** 考勤统计查询 */
export const AttendanceStatsQuery = gql`
  query AttendanceStats($classId: ID!, $startDate: String!, $endDate: String!) {
    attendanceStats(classId: $classId, startDate: $startDate, endDate: $endDate) {
      classId
      className
      startDate
      endDate
      totalRecords
      presentCount
      absentCount
      lateCount
      earlyLeaveCount
      leaveCount
      presentRate
      lateRate
      earlyLeaveRate
      leaveRate
      warningCount
      trend {
        date
        presentRate
        lateRate
        absentRate
      }
    }
  }
`;

/** 班级考勤对比查询 */
export const AttendanceClassComparisonQuery = gql`
  query AttendanceClassComparison($startDate: String!, $endDate: String!) {
    attendanceClassComparison(startDate: $startDate, endDate: $endDate) {
      classId
      className
      presentRate
      lateRate
      absentRate
    }
  }
`;

/** 学生考勤预警查询 */
export const AttendanceWarningsQuery = gql`
  query AttendanceWarnings($classId: ID!, $startDate: String!, $endDate: String!) {
    attendanceWarnings(classId: $classId, startDate: $startDate, endDate: $endDate) {
      studentId
      studentName
      studentNo
      className
      presentRate
      absentCount
      lateCount
    }
  }
`;

/** 考勤报告查询 */
export const AttendanceReportQuery = gql`
  query AttendanceReport(
    $classId: ID!
    $reportType: AttendanceReportType!
    $startDate: String!
    $endDate: String!
  ) {
    attendanceReport(
      classId: $classId
      reportType: $reportType
      startDate: $startDate
      endDate: $endDate
    ) {
      classId
      className
      reportType
      startDate
      endDate
      generatedAt
      summary {
        totalRecords
        presentRate
        lateRate
        earlyLeaveRate
        leaveRate
        warningCount
      }
      details {
        studentId
        studentName
        studentNo
        presentCount
        absentCount
        lateCount
        earlyLeaveCount
        leaveCount
        presentRate
      }
    }
  }
`;

/** 班级详情查询 */
export const ClassDetailQuery = gql`
  query ClassDetail($id: ID!) {
    classDetail(id: $id) {
      class {
        id
        name
        gradeId
        subject
        studentCount
        homeroomTeacher
        room
        schoolName
      }
      students {
        id
        name
        studentNo
        email
      }
      schedule {
        id
        classId
        className
        dayOfWeek
        period
        subject
        teacherName
        room
        startTime
        endTime
      }
      recentHomework {
        id
        title
        dueDate
        submissionRate
        avgScore
      }
      overview {
        attendanceRate
        averageScore
        homeworkCompletionRate
        recentExamTitle
        recentExamAvg
      }
      trend {
        month
        avgScore
      }
    }
  }
`;

/** 班级课表查询 */
export const ClassScheduleQuery = gql`
  query ClassSchedule($classId: ID) {
    classSchedule(classId: $classId) {
      id
      classId
      className
      dayOfWeek
      period
      subject
      teacherName
      room
      startTime
      endTime
    }
  }
`;

/** 请假审批列表查询 */
export const LeaveRequestsQuery = gql`
  query LeaveRequests($filter: LeaveRequestsFilterInput) {
    leaveRequests(filter: $filter) {
      items {
        id
        applicantId
        applicantName
        applicantRole
        type
        startDate
        endDate
        reason
        status
        submittedAt
        reviewedAt
        reviewerId
        reviewerName
        reviewComment
      }
      total
      page
      pageSize
    }
  }
`;

/** 审批请假 Mutation */
export const ApproveLeaveRequestMutation = gql`
  mutation ApproveLeaveRequest($input: ApproveLeaveRequestInput!) {
    approveLeaveRequest(input: $input) {
      requestId
      status
      reviewedAt
      reviewerId
      reviewerName
      reviewComment
    }
  }
`;

/** 提交请假申请 Mutation */
export const SubmitLeaveRequestMutation = gql`
  mutation SubmitLeaveRequest($input: SubmitLeaveRequestInput!) {
    submitLeaveRequest(input: $input) {
      requestId
      status
      submittedAt
    }
  }
`;

/** 调课申请列表查询 */
export const ScheduleChangesQuery = gql`
  query ScheduleChanges($page: Int, $pageSize: Int) {
    scheduleChanges(page: $page, pageSize: $pageSize) {
      items {
        id
        requesterId
        requesterName
        classId
        className
        originalDate
        originalPeriod
        originalSubject
        adjustedDate
        adjustedPeriod
        adjustedSubject
        substituteTeacherId
        substituteTeacherName
        type
        reason
        status
        submittedAt
        reviewedAt
        reviewComment
      }
      total
      page
      pageSize
    }
  }
`;

/** 提交调课申请 Mutation */
export const SubmitScheduleChangeMutation = gql`
  mutation SubmitScheduleChange($input: SubmitScheduleChangeInput!) {
    submitScheduleChange(input: $input) {
      requestId
      status
      submittedAt
    }
  }
`;
