import type {
  MarkingDataProvider,
  MarkingHistoryProvider,
  MarkingHistoryRecord,
  PaginatedResponse,
  SubmitResponse,
} from './MarkingContext'
import type {
  ExamBatchCreateMarkingTaskRecordRequest,
  ExamStudentMarkingQuestionResponse,
} from '@/api'
import { ref } from 'vue'
import { examMarkingTaskApi } from '@/api'
import { provideMarkingContext } from './MarkingContext'

// Store for the question to be reviewed
const currentReviewQuestion = ref<ExamStudentMarkingQuestionResponse | null>(null)

/**
 * 设置当前回评的题目
 */
export function setReviewQuestion(question: ExamStudentMarkingQuestionResponse) {
  currentReviewQuestion.value = question
}

/**
 * 回评数据提供者
 * 直接返回预设的题目数据
 */
export class ReviewMarkingDataProvider implements MarkingDataProvider {
  async getSingleQuestion(_taskId: number): Promise<ExamStudentMarkingQuestionResponse | null> {
    return currentReviewQuestion.value
  }

  async getMultipleQuestions(
    taskId: number,
    _options: { count: number },
  ): Promise<{ questions: ExamStudentMarkingQuestionResponse[] } | null> {
    const question = await this.getSingleQuestion(taskId)
    return question ? { questions: [question] } : null
  }

  async submitRecords(data: ExamBatchCreateMarkingTaskRecordRequest): Promise<SubmitResponse | null> {
    // 允许提交（重新打分）
    const response = await examMarkingTaskApi.batchCreate({ ...data, is_review: true })
    if (!response)
      return null

    return {
      success_count: response.success_count || 0,
      fail_data: response.fail_data?.map(item => ({ message: item.message || '' })),
      success_data: response.success_data?.map(item => ({
        id: item.id || 0,
        question_id: item.question_id || 0,
        score: item.score || 0,
        remark: item.remark,
        is_excellent: item.is_excellent || 0,
        is_model: item.is_model || 0,
        is_problem: item.is_problem || 0,
      })),
      is_end: response.is_end || false,
    }
  }

  async createProblemRecord(data: any): Promise<void> {
    await examMarkingTaskApi.problemRecordCreate(data)
  }
}

/**
 * 回评历史提供者
 * 返回空历史，禁用历史功能
 */
export class ReviewMarkingHistoryProvider implements MarkingHistoryProvider {
  async getHistoryPage(
    _taskId: number,
    _options: { page: number, page_size: number },
  ): Promise<PaginatedResponse<MarkingHistoryRecord>> {
    return {
      list: [],
      page: 1,
      page_size: 20,
      total: 0,
      has_more: false,
    }
  }
}

/**
 * 提供回评上下文
 */
export function provideReviewMarkingContext() {
  provideMarkingContext({
    dataProvider: new ReviewMarkingDataProvider(),
    historyProvider: new ReviewMarkingHistoryProvider(),
    isHistory: false,
    defaultPosition: 'last',
  })
}
