<!-- 阅卷详情页面 -->
<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 { markingTasksTaskIdStartUsingPost } from '@/service'

defineOptions({
  name: 'MarkingDetailPage',
})

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

// 获取路由参数
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)
})

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

// 展平所有任务 - 使用flatMap简化
const allTasks = computed(() => {
  const data = questionsData.value
  if (!data || !Array.isArray(data))
    return []

  return data.flatMap((question) => {
    const tasks = Object.values(question.tasks || {})
    return tasks.map(task => ({
      ...task,
      question_major: question.question_major || '',
      question_minor: question.question_minor || '',
      full_score: question.full_score || 0,
      evaluate_method: question.evaluate_method || '',
      // 计算待阅数量
      not_mark_quantity: Math.max(0, (task.task_quantity || 0) - (task.marked_quantity || 0)),
    }))
  })
})

// 获取任务按钮样式
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}`,
    })
  }
  catch (error) {
    console.error('开始阅卷失败:', error)
    uni.showToast({
      title: '开始阅卷失败',
      icon: 'none',
    })
  }
}

// 回评
async function handleRemark(task: any) {
  try {
    await uni.showModal({
      title: '确认回评',
      content: '回评将清除已阅记录，是否继续？',
    })

    uni.showToast({
      title: '回评功能开发中',
      icon: 'none',
    })

    // TODO: 实现回评接口调用
    // 刷新数据
    refetch()
  }
  catch (error: any) {
    if (error.errMsg !== 'showModal:fail cancel') {
      console.error('回评失败:', error)
      uni.showToast({
        title: '回评失败',
        icon: 'none',
      })
    }
  }
}

// 刷新数据
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-3">
      <view
        v-for="task in allTasks"
        :key="task.id"
        class="relative rounded-3 bg-white p-4 shadow-sm"
      >
        <!-- 左上角任务类型标签 -->
        <view
          class="absolute left-0 top-0 rounded-br-2 rounded-tl-3 px-2 py-1 text-xs text-white"
          :class="{
            'bg-blue-500': task.task_type === 'initial',
            'bg-green-500': task.task_type === 'final',
            'bg-orange-500': task.task_type === 'arbitration',
            'bg-gray-500': !['initial', 'final', 'arbitration'].includes(task.task_type),
          }"
        >
          {{ getTaskTypeName(task.task_type) }}
        </view>

        <!-- 题目信息 -->
        <view class="mb-3 mt-2 flex items-start justify-between">
          <view class="flex items-baseline gap-2">
            <text class="text-lg text-gray-800 font-semibold">
              {{ task.question_major }}.{{ task.question_minor }}
            </text>
            <text class="text-sm text-gray-500">满分: {{ task.full_score }}</text>
            <text class="text-xs text-gray-400">{{ task.evaluate_method }}</text>
          </view>
          <view class="text-xs text-gray-500">
            任务ID: {{ task.id }}
          </view>
        </view>

        <!-- 统计信息和操作按钮 -->
        <view class="flex items-center justify-between">
          <view class="flex gap-4">
            <view class="flex flex-col items-center gap-1">
              <text class="text-xs text-gray-500">总任务</text>
              <text class="text-base text-blue-500 font-semibold">{{ task.task_quantity || 0 }}</text>
            </view>
            <view class="flex flex-col items-center gap-1">
              <text class="text-xs text-gray-500">已阅</text>
              <text class="text-base text-green-500 font-semibold">{{ task.marked_quantity || 0 }}</text>
            </view>
            <view class="flex flex-col items-center gap-1">
              <text class="text-xs text-gray-500">待阅</text>
              <text class="text-base text-orange-500 font-semibold">{{ task.not_mark_quantity }}</text>
            </view>
          </view>

          <view class="flex gap-2">
            <!-- 回评按钮 -->
            <wd-button
              v-if="(task.marked_quantity || 0) > 0"
              size="small"
              type="warning"
              @click="handleRemark(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 v-if="allTasks.length === 0" class="h-50 flex items-center justify-center">
        <text class="text-sm text-gray-500">暂无任务数据</text>
      </view>
    </view>
  </view>
</template>
