import request from "@/utils/request";
import type { PaginationParams, PaginationResponse } from "@/types/api";

// ==================== 作业相关类型 ====================
export interface Homework {
  id: number;
  tenantId: number;
  name: string;
  content?: string;
  status: "unpublished" | "published";
  publishTime?: string;
  submitStartTime: string;
  submitEndTime: string;
  attachments?: HomeworkAttachment[];
  publishScope?: number[];
  publishScopeNames?: string[];
  reviewRuleId?: number;
  reviewRule?: HomeworkReviewRule;
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
  validState?: number;
  _count?: {
    submissions: number;
  };
  // 学生端：我的提交记录
  submission?: {
    id: number;
    workName: string;
    submitTime: string;
    totalScore?: number;
  } | null;
}

export interface HomeworkAttachment {
  fileName: string;
  fileUrl: string;
  size?: string;
}

export interface CreateHomeworkForm {
  name: string;
  content?: string;
  submitStartTime: string;
  submitEndTime: string;
  attachments?: HomeworkAttachment[];
  publishScope?: number[];
  reviewRuleId?: number;
}

export interface UpdateHomeworkForm extends Partial<CreateHomeworkForm> {}

export interface QueryHomeworkParams extends PaginationParams {
  name?: string;
  status?: string;
  submitStartTime?: string;
  submitEndTime?: string;
}

// ==================== 提交记录相关类型 ====================
export interface HomeworkSubmission {
  id: number;
  tenantId: number;
  homeworkId: number;
  studentId: number;
  workNo?: string;
  workName: string;
  workDescription?: string;
  files?: any[];
  attachments?: any[];
  submitTime: string;
  status: "pending" | "reviewed" | "rejected";
  totalScore?: number;
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
  validState?: number;
  homework?: {
    id: number;
    name: string;
    reviewRuleId?: number;
    reviewRule?: HomeworkReviewRule;
  };
  student?: {
    id: number;
    username: string;
    nickname: string;
    student?: {
      studentNo?: string;
      class?: {
        id: number;
        name: string;
        grade?: {
          id: number;
          name: string;
        };
      };
    };
  };
  scores?: HomeworkScore[];
  _count?: {
    scores: number;
  };
}

export interface QuerySubmissionParams extends PaginationParams {
  homeworkId?: number;
  workNo?: string;
  workName?: string;
  studentAccount?: string;
  studentName?: string;
  status?: string;
  classIds?: number[];
  gradeId?: number;
}

// ==================== 评审规则相关类型 ====================
export interface HomeworkReviewRule {
  id: number;
  tenantId: number;
  name: string;
  description?: string;
  criteria: ReviewCriterion[];
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
  validState?: number;
  homeworks?: Array<{
    id: number;
    name: string;
  }>;
}

export interface ReviewCriterion {
  name: string;
  maxScore: number;
  description?: string;
}

export interface CreateReviewRuleForm {
  name: string;
  description?: string;
  criteria: ReviewCriterion[];
}

// ==================== 评分相关类型 ====================
export interface HomeworkScore {
  id: number;
  tenantId: number;
  submissionId: number;
  reviewerId: number;
  dimensionScores: DimensionScore[];
  totalScore: number;
  comments?: string;
  scoreTime: string;
  creator?: number;
  modifier?: number;
  createTime?: string;
  modifyTime?: string;
  validState?: number;
  reviewer?: {
    id: number;
    nickname: string;
  };
}

export interface DimensionScore {
  name: string;
  score: number;
  maxScore: number;
}

export interface CreateScoreForm {
  submissionId: number;
  dimensionScores: DimensionScore[];
  comments?: string;
}

// ==================== 班级树相关类型 ====================
export interface ClassTreeNode {
  id: string | number;
  name: string;
  type: "grade" | "class";
  gradeId?: number;
  classId?: number;
  children?: ClassTreeNode[];
}

// ==================== API 函数 ====================

// 作业管理
export const homeworksApi = {
  // 获取作业列表（教师端）
  getList: async (
    params: QueryHomeworkParams
  ): Promise<PaginationResponse<Homework>> => {
    const response = await request.get<any, PaginationResponse<Homework>>(
      "/homework/homeworks",
      { params }
    );
    return response;
  },

  // 获取我的作业列表（学生端）
  getMyList: async (
    params: QueryHomeworkParams
  ): Promise<PaginationResponse<Homework>> => {
    const response = await request.get<any, PaginationResponse<Homework>>(
      "/homework/homeworks/my",
      { params }
    );
    return response;
  },

  // 获取作业详情
  getDetail: async (id: number): Promise<Homework> => {
    const response = await request.get<any, Homework>(
      `/homework/homeworks/${id}`
    );
    return response;
  },

  // 创建作业
  create: async (data: CreateHomeworkForm): Promise<Homework> => {
    const response = await request.post<any, Homework>(
      "/homework/homeworks",
      data
    );
    return response;
  },

  // 更新作业
  update: async (id: number, data: UpdateHomeworkForm): Promise<Homework> => {
    const response = await request.patch<any, Homework>(
      `/homework/homeworks/${id}`,
      data
    );
    return response;
  },

  // 发布作业
  publish: async (id: number, publishScope: number[]): Promise<Homework> => {
    const response = await request.post<any, Homework>(
      `/homework/homeworks/${id}/publish`,
      { publishScope }
    );
    return response;
  },

  // 取消发布作业
  unpublish: async (id: number): Promise<Homework> => {
    const response = await request.post<any, Homework>(
      `/homework/homeworks/${id}/unpublish`
    );
    return response;
  },

  // 删除作业
  delete: async (id: number): Promise<void> => {
    return await request.delete<any, void>(`/homework/homeworks/${id}`);
  },
};

// 学生提交作业表单
export interface SubmitHomeworkForm {
  homeworkId: number;
  workName: string;
  workDescription?: string;
  files?: HomeworkAttachment[];
}

// 提交记录管理
export const submissionsApi = {
  // 获取提交记录列表
  getList: async (
    params: QuerySubmissionParams
  ): Promise<PaginationResponse<HomeworkSubmission>> => {
    const response = await request.get<
      any,
      PaginationResponse<HomeworkSubmission>
    >("/homework/submissions", { params });
    return response;
  },

  // 获取提交记录详情
  getDetail: async (id: number): Promise<HomeworkSubmission> => {
    const response = await request.get<any, HomeworkSubmission>(
      `/homework/submissions/${id}`
    );
    return response;
  },

  // 获取班级树结构
  getClassTree: async (): Promise<ClassTreeNode[]> => {
    const response = await request.get<any, ClassTreeNode[]>(
      "/homework/submissions/class-tree"
    );
    return response;
  },

  // 获取当前用户对某作业的提交记录
  getMySubmission: async (homeworkId: number): Promise<HomeworkSubmission> => {
    const response = await request.get<any, HomeworkSubmission>(
      `/homework/submissions/my/${homeworkId}`
    );
    return response;
  },

  // 提交作业
  submit: async (data: SubmitHomeworkForm): Promise<HomeworkSubmission> => {
    const response = await request.post<any, HomeworkSubmission>(
      "/homework/submissions",
      data
    );
    return response;
  },
};

// 评审规则管理
export const reviewRulesApi = {
  // 获取评审规则列表
  getList: async (params?: {
    name?: string;
    page?: number;
    pageSize?: number;
  }): Promise<{
    list: HomeworkReviewRule[];
    total: number;
    page: number;
    pageSize: number;
  }> => {
    const response = await request.get<
      any,
      {
        list: HomeworkReviewRule[];
        total: number;
        page: number;
        pageSize: number;
      }
    >("/homework/review-rules", { params });
    return response;
  },

  // 获取所有可用的评审规则（用于选择）
  getForSelect: async (): Promise<HomeworkReviewRule[]> => {
    const response = await request.get<any, HomeworkReviewRule[]>(
      "/homework/review-rules/select"
    );
    return response;
  },

  // 获取评审规则详情
  getDetail: async (id: number): Promise<HomeworkReviewRule> => {
    const response = await request.get<any, HomeworkReviewRule>(
      `/homework/review-rules/${id}`
    );
    return response;
  },

  // 创建评审规则
  create: async (data: CreateReviewRuleForm): Promise<HomeworkReviewRule> => {
    const response = await request.post<any, HomeworkReviewRule>(
      "/homework/review-rules",
      data
    );
    return response;
  },

  // 更新评审规则
  update: async (
    id: number,
    data: Partial<CreateReviewRuleForm>
  ): Promise<HomeworkReviewRule> => {
    const response = await request.patch<any, HomeworkReviewRule>(
      `/homework/review-rules/${id}`,
      data
    );
    return response;
  },

  // 删除评审规则
  delete: async (id: number): Promise<void> => {
    await request.delete(`/homework/review-rules/${id}`);
  },
};

// 评分管理
export const scoresApi = {
  // 提交评分
  create: async (data: CreateScoreForm): Promise<HomeworkScore> => {
    const response = await request.post<any, HomeworkScore>(
      "/homework/scores",
      data
    );
    return response;
  },

  // 标记作品违规
  markViolation: async (
    submissionId: number,
    reason?: string
  ): Promise<void> => {
    await request.post(`/homework/scores/${submissionId}/violation`, {
      reason,
    });
  },

  // 重置评分
  resetScore: async (submissionId: number): Promise<void> => {
    await request.post(`/homework/scores/${submissionId}/reset`);
  },
};
