<!-- 阅卷页面 -->
<route lang="jsonc">
{
  "style": {
    "navigationBarTitleText": "阅卷"
  }
}
</route>

<script lang="ts" setup>
import type { TeacherMarkingTasksResponse } from '@/service/types'
import { useQuery } from '@tanstack/vue-query'
import { computed, ref } from 'vue'
import TaskCard from '@/components/marking/TaskCard.vue'
import { useUserId } from '@/composables/useUserId'
import { markingTasksUsingGet } from '@/service'

defineOptions({
  name: 'MarkingPage',
})

// 主要Tab：阅卷任务 | 阅卷监控
const activeTab = ref<'tasks' | 'monitoring'>('tasks')

// 历次任务学年筛选
const historyAcademicYear = ref<string>('') // 空字符串表示全部

// 获取阅卷任务数据
const {
  data: tasksData,
  isLoading,
  error,
  refetch,
} = useQuery({
  queryKey: ['marking-tasks', useUserId()],
  queryFn: () => markingTasksUsingGet({
    params: {
      page: 1,
      page_size: 50,
    },
  }),
  staleTime: 1000 * 60 * 5,
  gcTime: 1000 * 60 * 30,
})

// 解析API响应数据
const responseData = computed<TeacherMarkingTasksResponse | undefined>(() => {
  return tasksData.value
})

// 当前任务
const currentTask = computed(() => {
  return responseData.value?.current_task ? [responseData.value?.current_task] : []
})

// 历史任务（支持学年筛选）
const historyTasks = computed(() => {
  const historyList = responseData.value?.history_tasks?.list || []

  if (!historyAcademicYear.value) {
    return historyList
  }

  // 根据学年筛选
  return historyList.filter((task) => {
    // 这里需要根据实际的学年字段进行筛选
    // 假设考试日期可以推断学年
    if (!task.exam_date)
      return false

    const examYear = new Date(task.exam_date).getFullYear()
    const [startYear] = historyAcademicYear.value.split('-').map(Number)

    return examYear >= startYear && examYear <= startYear + 1
  })
})

// 学年选项
const academicYearOptions = computed(() => {
  const currentYear = new Date().getFullYear()
  const options = [
    { label: '全部', value: '' },
  ]

  // 生成最近5年的学年选项
  for (let i = 0; i < 5; i++) {
    const year = currentYear - i
    options.push({
      label: `${year}-${year + 1}`,
      value: `${year}-${year + 1}`,
    })
  }

  return options
})

// 进入阅卷
function handleEnterMarking(examId: number, subjectId: number) {
  uni.navigateTo({
    url: `/pages/marking/detail?examId=${examId}&subjectId=${subjectId}`,
  })
}

// 查看进度
function handleViewProgress(examId: number, subjectId: number) {
  uni.navigateTo({
    url: `/pages/marking/progress?examId=${examId}&subjectId=${subjectId}`,
  })
}

// 查看质量
function handleViewQuality(examId: number, examSubjectId: number) {
  uni.navigateTo({
    url: `/pages/marking/quality?examSubjectId=${examSubjectId}`,
  })
}

// 刷新数据
function handleRefresh() {
  refetch()
}
</script>

<template>
  <view>
    <view>
      <!-- 主Tab切换：阅卷任务 | 阅卷监控 -->
      <wd-tabs v-model:active="activeTab" class="mb-4 px-4">
        <wd-tab name="tasks" title="阅卷任务">
          <view class="p-2 space-y-4">
            <!-- 当前任务区域 -->
            <view>
              <view class="mb-3 flex items-center">
                <text class="text-base font-semibold">当前任务</text>
              </view>

              <!-- 当前任务卡片 -->
              <view v-if="!currentTask" class="py-8 text-center">
                <text class="text-sm text-gray-500">暂无当前任务</text>
              </view>
              <view v-for="task in currentTask" :key="task.exam_id">
                <TaskCard
                  :task="task"
                  :is-current="true"
                  :is-monitor="false"
                  @enter-marking="handleEnterMarking"
                  @view-progress="handleViewProgress"
                  @view-quality="handleViewQuality"
                />
              </view>
            </view>

            <!-- 历次任务区域 -->
            <view>
              <view class="mb-3 flex items-center justify-between">
                <text class="text-base font-semibold">历次任务</text>
                <!-- 学年筛选 -->
                <wd-picker
                  v-model="historyAcademicYear"
                  :columns="academicYearOptions"
                  placeholder="选择学年"
                  size="small"
                  style="width: 120px"
                />
              </view>

              <!-- 历次任务列表 -->
              <view v-if="historyTasks.length === 0" class="py-8 text-center">
                <text class="text-sm text-gray-500">暂无历次任务</text>
              </view>
              <view v-else class="space-y-3">
                <TaskCard
                  v-for="task in historyTasks"
                  :key="`${task.exam_id}-history`"
                  :is-monitor="false"
                  :task="task"
                  :is-current="false"
                  @enter-marking="handleEnterMarking"
                  @view-progress="handleViewProgress"
                  @view-quality="handleViewQuality"
                />
              </view>
            </view>
          </view>
        </wd-tab>

        <wd-tab name="monitoring" title="阅卷监控">
          <view class="p-2 space-y-4">
            <!-- 当前任务区域 -->
            <view>
              <view class="mb-3 flex items-center">
                <text class="text-base font-semibold">当前任务</text>
              </view>

              <!-- 当前任务卡片 -->
              <view v-if="!currentTask" class="py-8 text-center">
                <text class="text-sm text-gray-500">暂无当前任务</text>
              </view>
              <view v-for="task in currentTask" :key="task.exam_id">
                <TaskCard
                  :task="task"
                  :is-current="true"
                  :is-monitor="true"
                />
              </view>
            </view>
          </view>
        </wd-tab>
      </wd-tabs>

      <!-- 加载状态 -->
      <view v-if="isLoading" class="py-12 text-center">
        <wd-loading size="24" />
        <text class="mt-2 block text-sm text-gray-500">加载中...</text>
      </view>

      <!-- 错误状态 -->
      <view v-else-if="error" class="py-12 text-center">
        <text class="mb-4 block text-sm text-red-500">加载失败</text>
        <wd-button type="primary" size="small" @click="handleRefresh">
          重试
        </wd-button>
      </view>
    </view>
  </view>
</template>
