/**
 * 阅卷上下文接口定义
 * 为不同的阅卷场景提供统一的抽象接口
 * 移动端优化版本 - 使用 TanStack Query
 */
import type {
  ExamBatchCreateMarkingTaskRecordRequest,
  ExamStudentMarkingQuestionResponse,
  ExamStudentMarkingQuestionsResponse,
} from '@/api'
import { examMarkingTaskApi } from '@/api'

// 分页响应接口
export interface PaginatedResponse<T> {
  list: T[]
  page: number
  page_size: number
  total: number
  has_more?: boolean
}

// 提交响应接口
export interface SubmitResponse {
  success_count: number
  fail_data?: Array<{ message: string }>
  success_data?: Array<{
    id: number
    question_id: number
    score: number
    remark?: string
    is_excellent: number
    is_model: number
    is_problem: number
  }>
  is_end: boolean
}

// 历史记录项
export interface MarkingHistoryRecord {
  id: number
  task_id: number
  question_id: number
  scan_info_id: number
  score: number
  full_score: number
  question_major: string
  question_minor: string
  image_urls?: string[]
  created_time: string
  is_excellent: number
  is_model: number
  is_problem: number
}

// 阅卷数据提供者接口
export interface MarkingDataProvider {
  /**
   * 获取单题数据
   */
  getSingleQuestion: (taskId: number) => Promise<ExamStudentMarkingQuestionResponse | null>

  /**
   * 获取多题数据
   */
  getMultipleQuestions: (
    taskId: number,
    options: { count: number },
  ) => Promise<{
    questions: ExamStudentMarkingQuestionResponse[]
  } | null>

  /**
   * 提交阅卷记录
   */
  submitRecords: (data: ExamBatchCreateMarkingTaskRecordRequest) => Promise<SubmitResponse | null>

  /**
   * 创建问题卷记录
   */
  createProblemRecord?: (data: {
    id: number
    task_id: number
    problem_type: string
    problem_addition?: string
  }) => Promise<void>
}

// 阅卷历史提供者接口
export interface MarkingHistoryProvider {
  /**
   * 获取历史记录分页数据
   */
  getHistoryPage: (
    taskId: number,
    options: { page: number, page_size: number },
  ) => Promise<PaginatedResponse<MarkingHistoryRecord>>
}

// 完整的阅卷上下文接口
export interface MarkingContext {
  dataProvider: MarkingDataProvider
  historyProvider: MarkingHistoryProvider
  isHistory: boolean
  defaultPosition?: 'first' | 'last' // 默认定位：first-第一个，last-最后一个
}

/**
 * 预加载图片资源（提升用户体验）
 */
async function preloadImages(urls: string[]): Promise<void> {
  if (!urls || urls.length === 0)
    return

  // 移动端使用 uni.getImageInfo 预加载
  const imagePromises = urls.map((url) => {
    return new Promise<void>((resolve) => {
      uni.getImageInfo({
        src: url,
        success: () => resolve(),
        fail: () => resolve(), // 预加载失败不影响主流程
      })
    })
  })

  await Promise.all(imagePromises)
  console.log(`🖼️ 已预加载 ${urls.length} 张图片`)
}

/**
 * 默认的阅卷数据提供者（使用原有的API）
 * 带滑动窗口缓存优化
 */
export class DefaultMarkingDataProvider implements MarkingDataProvider {
  // 滑动窗口缓存
  private cachedQuestion: ExamStudentMarkingQuestionsResponse | null = null
  private lastTaskId: number | null = null
  private hasSubmitted = false
  private fetchingPromise: Promise<ExamStudentMarkingQuestionsResponse | null> | null = null

  async getSingleQuestion(taskId: number): Promise<ExamStudentMarkingQuestionResponse | null> {
    // 如果任务ID变化，清空缓存
    if (this.lastTaskId !== taskId) {
      this.cachedQuestion = null
      this.lastTaskId = taskId
      this.hasSubmitted = false
      this.fetchingPromise = null
    }

    // 如果有缓存且已提交过，快速返回缓存并立即预加载下一批数据
    if (this.cachedQuestion && this.hasSubmitted) {
      const result = this.cachedQuestion
      this.cachedQuestion = null // 使用后清空缓存
      this.hasSubmitted = false // 重置提交标记

      // 立即预加载下一批数据（不等待）
      this.fetchingPromise = this.fetchAndCacheQuestions(taskId)

      return result?.questions?.[0] || null
    }

    // 如果正在预加载，等待预加载完成
    if (this.fetchingPromise) {
      await this.fetchingPromise
      this.fetchingPromise = null

      // 预加载完成后，返回缓存的数据
      if (this.cachedQuestion) {
        const result = this.cachedQuestion
        this.cachedQuestion = null
        return result?.questions?.[0] || null
      }
    }

    // 否则调用接口获取数据
    const result = await this.fetchAndCacheQuestions(taskId)
    return result?.questions?.[0] || null
  }

  private async fetchAndCacheQuestions(
    taskId: number,
  ): Promise<ExamStudentMarkingQuestionsResponse | null> {
    const response = await examMarkingTaskApi.questionsDetail(taskId, {
      count: 2,
    })

    if (!response) {
      return null
    }

    // 如果有多个问题，缓存第二个作为滑动窗口
    if (response.questions && response.questions.length > 1) {
      this.cachedQuestion = {
        ...response,
        questions: [response.questions[1]],
      }

      // 预加载图片资源
      if (this.cachedQuestion.questions?.[0]?.image_urls) {
        preloadImages(this.cachedQuestion.questions[0].image_urls)
      }
    }
    else {
      this.cachedQuestion = null
    }

    // 返回第一个问题
    return {
      ...response,
      questions: response.questions ? [response.questions[0]] : [],
    }
  }

  async getMultipleQuestions(
    taskId: number,
    _options: { count: number },
  ): Promise<{ questions: ExamStudentMarkingQuestionResponse[] } | null> {
    // 移动端暂不支持多题模式
    const response = await this.getSingleQuestion(taskId)
    return response ? { questions: [response] } : null
  }

  async submitRecords(data: ExamBatchCreateMarkingTaskRecordRequest): Promise<SubmitResponse | null> {
    const response = await examMarkingTaskApi.batchCreate(data)

    // 标记已提交，下次获取时可以使用缓存
    this.hasSubmitted = true

    return response
      ? {
          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,
        }
      : null
  }

  async createProblemRecord(data: {
    id: number
    task_id: number
    problem_type: string
    problem_addition?: string
  }): Promise<void> {
    await examMarkingTaskApi.problemRecordCreate(data as any)
  }
}

/**
 * 默认的阅卷历史提供者（使用原有的API）
 */
export class DefaultMarkingHistoryProvider implements MarkingHistoryProvider {
  async getHistoryPage(
    taskId: number,
    options: { page: number, page_size: number },
  ): Promise<PaginatedResponse<MarkingHistoryRecord>> {
    return await examMarkingTaskApi.historyDetail(taskId, options)
  }
}

/**
 * 默认阅卷上下文
 */
export const defaultMarkingContext: MarkingContext = {
  dataProvider: new DefaultMarkingDataProvider(),
  historyProvider: new DefaultMarkingHistoryProvider(),
  isHistory: false,
  defaultPosition: 'last', // 默认定位到最后一个
}

/**
 * 阅卷上下文 Symbol
 */
export const MarkingContextSymbol = Symbol('MarkingContext')

/**
 * 提供阅卷上下文
 */
export function provideMarkingContext(context: MarkingContext) {
  provide(MarkingContextSymbol, context)
}

/**
 * 使用阅卷上下文
 */
export function useMarkingContext(): MarkingContext | null {
  return inject<MarkingContext>(MarkingContextSymbol) || null
}

/**
 * 获取阅卷上下文（带默认值）
 */
export function getMarkingContext(): MarkingContext {
  return useMarkingContext() || defaultMarkingContext
}
