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

<script lang="ts" setup>
import { useQuery } from '@tanstack/vue-query'
import { computed, ref } from 'vue'
import { examMarkingTaskApi } from '@/api'
import { DictCode, useDict } from '@/composables/useDict'
import { useUserId } from '@/composables/useUserId'
import { markingTasksTaskIdStartUsingPost } from '@/service'

defineOptions({
  name: 'MarkingDetailPage',
})

// 字典功能
const { getDictOptionsAndGetLabel } = useDict()
const [, getTaskTypeName] = getDictOptionsAndGetLabel(DictCode.TASK_TYPE)
const [, getEvaluateMethodName] = getDictOptionsAndGetLabel(DictCode.EVALUATE_METHOD)

// 获取路由参数
const examId = ref<number>()
const subjectId = ref<number>()
const enableQuery = computed(() => !!examId.value && !!subjectId.value)

// 页面加载时获取参数
onLoad((options) => {
  examId.value = Number(options.examId)
  subjectId.value = Number(options.subjectId)
  console.log(examId.value, subjectId.value)
})

// 页面显示时重新加载数据
onShow(() => {
  if (enableQuery.value) {
    refetch()
  }
})

// 获取题目列表数据
const {
  data: questionsData,
  isLoading,
  error,
  refetch,
} = useQuery({
  queryKey: ['marking-questions', examId, subjectId, useUserId()],
  queryFn: () => examMarkingTaskApi.byQuestionList(
    {
      exam_id: examId.value!,
      exam_subject_id: subjectId.value!,
    },
  ),
  enabled: enableQuery,
})

// 按评价类型和题目分组任务
interface GroupedQuestion {
  questionKey: string
  questionInfo: {
    question_major: string
    question_minor: string
    full_score: number
    evaluate_method: string
    question_id: number
  }
  tasks: Array<{
    id: number
    question_id: number
    task_type: string
    task_quantity: number
    marked_quantity: number
    not_mark_quantity: number
    [key: string]: any
  }>
}

const groupedTasks = computed(() => {
  const data = questionsData.value
  if (!data || !Array.isArray(data))
    return {}

  // 按 evaluate_method 分组
  const groups: Record<string, Record<string, GroupedQuestion>> = {}

  data.forEach((question) => {
    const evaluateMethod = Object.values(question.tasks || {})[0]?.evaluate_method || 'other'
    const questionKey = `${question.question_major || ''}.${question.question_minor || ''}`

    // 初始化分组
    if (!groups[evaluateMethod]) {
      groups[evaluateMethod] = {}
    }

    // 初始化题目组
    if (!groups[evaluateMethod][questionKey]) {
      groups[evaluateMethod][questionKey] = {
        questionKey,
        questionInfo: {
          question_major: question.question_major || '',
          question_minor: question.question_minor || '',
          full_score: question.full_score || 0,
          evaluate_method: evaluateMethod,
          question_id: question.question_id || 0,
        },
        tasks: [],
      }
    }

    // 添加该题目的所有任务
    const tasks = Object.values(question.tasks || {})
    tasks.forEach((task) => {
      groups[evaluateMethod][questionKey].tasks.push({
        ...task,
        question_id: question.question_id || 0,
        not_mark_quantity: Math.max(0, (task.task_quantity || 0) - (task.marked_quantity || 0)),
      })
    })
  })

  return groups
})

// 获取分组后的数组（用于模板渲染）
const groupedTasksList = computed(() => {
  return Object.entries(groupedTasks.value).map(([evaluateMethod, questions]) => ({
    evaluateMethod,
    evaluateMethodName: getEvaluateMethodName(evaluateMethod),
    questions: Object.values(questions),
  }))
})

// 获取任务按钮样式
function getTaskButtonType(task: any) {
  const canStart = task.not_mark_quantity > 0
  if (!canStart)
    return 'default'

  switch (task.task_type) {
    case 'initial':
      return 'primary'
    case 'final':
      return 'success'
    case 'arbitration':
      return 'warning'
    default:
      return 'primary'
  }
}

// 开始阅卷
async function handleStartMarking(task: any) {
  try {
    await markingTasksTaskIdStartUsingPost({
      params: {
        task_id: task.id,
      },
    })

    // 确定评价类型
    const evaluationType = task.evaluate_method === 'double' ? 'double' : 'single'

    // 跳转到阅卷界面
    uni.navigateTo({
      url: `/pages/marking/grading?examId=${examId.value}&subjectId=${subjectId.value}&questionId=${task.question_id}&taskId=${task.id}&type=${evaluationType}&taskType=${task.task_type}`,
    })
  }
  catch (error) {
    console.error('开始阅卷失败:', error)
    uni.showToast({
      title: '开始阅卷失败',
      icon: 'none',
    })
  }
}

// 查看回评
async function handleViewReview(task: any) {
  uni.navigateTo({
    url: `/pages/marking/review?examId=${examId.value}&subjectId=${subjectId.value}&questionId=${task.question_id}&taskId=${task.id}`,
  })
}

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

<template>
  <view class="bg-gray-50 p-4">
    <!-- 加载状态 -->
    <view v-if="isLoading" class="h-50 flex flex-col items-center justify-center gap-3">
      <wd-loading size="24" />
      <text class="text-sm text-gray-600">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="h-50 flex flex-col items-center justify-center gap-3">
      <text class="text-sm text-gray-600">加载失败</text>
      <wd-button type="primary" size="small" @click="handleRefresh">
        重试
      </wd-button>
    </view>

    <!-- 任务列表 - 按类型分组 -->
    <view v-else class="flex flex-col gap-4">
      <view
        v-for="group in groupedTasksList"
        :key="group.evaluateMethod"
        class="flex flex-col gap-3"
      >
        <!-- 分组标题 -->
        <view class="flex items-center gap-2">
          <text class="text-base text-gray-800 font-semibold">{{ group.evaluateMethodName }}</text>
        </view>

        <!-- 该组下的题目卡片 -->
        <view
          v-for="questionGroup in group.questions"
          :key="questionGroup.questionKey"
          class="relative rounded-3 bg-white p-4 shadow-sm"
        >
          <!-- 题目信息 -->
          <view class="mb-3 flex items-start justify-between">
            <view class="flex items-baseline gap-2">
              <text class="text-lg text-gray-800 font-semibold">
                {{ questionGroup.questionInfo.question_major }}.{{ questionGroup.questionInfo.question_minor }}
              </text>
              <!-- <text class="text-sm text-blue-500">效率优先</text> -->
              <text class="text-xs text-gray-500">满分: {{ questionGroup.questionInfo.full_score }}</text>
            </view>
          </view>

          <!-- 该题目的多个任务 - 竖着展示 -->
          <view class="flex flex-col gap-3">
            <view
              v-for="(task, index) in questionGroup.tasks.slice().sort((a, b) => {
                const order = { initial: 1, final: 2, arbitration: 3 }
                return (order[a.task_type] || 999) - (order[b.task_type] || 999)
              })"
              :key="task.id"
              class="flex items-center justify-between pt-3"
              :class="{ 'border-t border-gray-100': index > 0 }"
            >
              <!-- 任务统计信息 -->
              <view class="flex gap-4">
                <text class="text-sm text-gray-600">
                  已阅<text class="text-gray-800 font-semibold">{{ task.marked_quantity || 0 }}</text>
                </text>
                <text class="text-sm text-gray-600">
                  待阅<text class="text-orange-500 font-semibold">{{ task.not_mark_quantity }}</text>
                </text>
              </view>

              <!-- 操作按钮 -->
              <view class="flex gap-2">
                <!-- 查看回评按钮 -->
                <wd-button
                  v-if="(task.marked_quantity || 0) > 0"
                  size="small"
                  type="info"
                  @click="handleViewReview(task)"
                >
                  回评
                </wd-button>

                <!-- 开始阅卷按钮 -->
                <wd-button
                  size="small"
                  :type="getTaskButtonType(task)"
                  :disabled="task.not_mark_quantity <= 0"
                  @click="handleStartMarking(task)"
                >
                  {{ task.not_mark_quantity > 0 ? getTaskTypeName(task.task_type) : '已完成' }}
                </wd-button>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="groupedTasksList.length === 0" class="h-50 flex items-center justify-center">
        <text class="text-sm text-gray-500">暂无任务数据</text>
      </view>
    </view>
  </view>
</template>
