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

<script lang="ts" setup>
import type { MarkingTaskByQuestionItem } from '@/service/types'
import { useQuery } from '@tanstack/vue-query'
import { computed, ref } from 'vue'
import { markingTasksByQuestionUsingGet, markingTasksTaskIdStartUsingPost } from '@/service'

defineOptions({
  name: 'MarkingDetailPage',
})

// 获取路由参数
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: () => markingTasksByQuestionUsingGet({
    params: {
      exam_id: examId.value!,
      exam_subject_id: subjectId.value!,
    },
  }),
  enabled: enableQuery,
})

// 解析题目列表 - 合并单评和双评任务
const questionsList = computed(() => {
  const data = questionsData.value
  if (!data)
    return []

  // 收集所有题目
  const questionsMap = new Map<number, {
    question_id: number
    question_major: string
    question_minor: string
    marked_quantity: number
    not_mark_quantity: number
    has_single: boolean
    has_double: boolean
    single_task?: MarkingTaskByQuestionItem
    double_task?: MarkingTaskByQuestionItem
  }>()

  // 处理单评任务
  if (data.single_tasks && Array.isArray(data.single_tasks)) {
    data.single_tasks.forEach((task) => {
      if (task.question_id) {
        questionsMap.set(task.question_id, {
          question_id: task.question_id,
          question_major: task.question_major || '',
          question_minor: task.question_minor || '',
          marked_quantity: task.marked_quantity || 0,
          not_mark_quantity: task.not_mark_quantity || 0,
          has_single: true,
          has_double: false,
          single_task: task,
        })
      }
    })
  }

  // 处理双评任务
  if (data.double_tasks && Array.isArray(data.double_tasks)) {
    data.double_tasks.forEach((task) => {
      if (task.question_id) {
        const existing = questionsMap.get(task.question_id)
        if (existing) {
          existing.has_double = true
          existing.double_task = task
          existing.marked_quantity += task.marked_quantity || 0
          existing.not_mark_quantity += task.not_mark_quantity || 0
        }
        else {
          questionsMap.set(task.question_id, {
            question_id: task.question_id,
            question_major: task.question_major || '',
            question_minor: task.question_minor || '',
            marked_quantity: task.marked_quantity || 0,
            not_mark_quantity: task.not_mark_quantity || 0,
            has_single: false,
            has_double: true,
            double_task: task,
          })
        }
      }
    })
  }

  return Array.from(questionsMap.values())
})

// 判断是否显示单评按钮
function shouldShowSingleButton(question: any) {
  return question.has_single
}

// 判断是否显示双评按钮
function shouldShowDoubleButton(question: any) {
  return question.has_double
}

// 判断是否显示回评按钮
function shouldShowRemarkButton(question: any) {
  return question.marked_quantity > 0
}

// 获取单评按钮状态
function getSingleButtonStatus(question: any) {
  if (!question.single_task) {
    return { disabled: true, text: '单评', type: 'default' as const }
  }

  const canStart = (question.single_task.not_mark_quantity || 0) > 0
  return {
    disabled: !canStart,
    text: '单评',
    type: canStart ? 'primary' as const : 'default' as const,
    task: question.single_task,
  }
}

// 获取双评按钮状态
function getDoubleButtonStatus(question: any) {
  if (!question.double_task) {
    return { disabled: true, text: '双评', type: 'default' as const }
  }

  const canStart = (question.double_task.not_mark_quantity || 0) > 0
  return {
    disabled: !canStart,
    text: '双评',
    type: canStart ? 'success' as const : 'default' as const,
    task: question.double_task,
  }
}

// 开始阅卷
async function handleStartMarking(task: MarkingTaskByQuestionItem, evaluationType: 'single' | 'double') {
  try {
    await markingTasksTaskIdStartUsingPost({
      params: {
        task_id: task.question_id,
      },
    })
    // 跳转到阅卷界面
    uni.navigateTo({
      url: `/pages/marking/grading?examId=${examId.value}&subjectId=${subjectId.value}&questionId=${task.question_id}&taskId=${task.question_id}&type=${evaluationType}`,
    })
  }
  catch (error) {
    console.error('开始阅卷失败:', error)
    uni.showToast({
      title: '开始阅卷失败',
      icon: 'none',
    })
  }
}

// 回评
async function handleRemark(question: 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-4">
      <view
        v-for="question in questionsList"
        :key="question.question_id"
        class="relative rounded-3 bg-white p-4 shadow-sm"
      >
        <!-- 左上角类型标签 -->
        <view class="absolute left-0 top-0 rounded-br-2 rounded-tl-3 bg-blue-500 px-2 py-1 text-xs text-white">
          {{ question.has_single && question.has_double ? '双评' : question.has_single ? '单评' : '双评' }}
        </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">{{ question.question_major }}.{{ question.question_minor }}</text>
          </view>
          <view class="flex gap-2">
            <text
              v-if="question.has_single"
              class="rounded-3 bg-blue-50 px-2 py-0.5 text-xs text-blue-600"
            >
              单评
            </text>
            <text
              v-if="question.has_double"
              class="rounded-3 bg-purple-50 px-2 py-0.5 text-xs text-purple-600"
            >
              双评
            </text>
          </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-green-500 font-semibold">{{ question.marked_quantity }}</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">{{ question.not_mark_quantity }}</text>
            </view>
          </view>

          <view class="flex gap-2">
            <!-- 回评按钮 -->
            <wd-button
              v-if="shouldShowRemarkButton(question)"
              size="small"
              type="warning"
              @click="handleRemark(question)"
            >
              回评
            </wd-button>

            <!-- 单评按钮 -->
            <wd-button
              v-if="shouldShowSingleButton(question)"
              size="small"
              :type="getSingleButtonStatus(question).type"
              :disabled="getSingleButtonStatus(question).disabled"
              @click="handleStartMarking(getSingleButtonStatus(question).task!, 'single')"
            >
              {{ getSingleButtonStatus(question).text }}
            </wd-button>

            <!-- 双评按钮 -->
            <wd-button
              v-if="shouldShowDoubleButton(question)"
              size="small"
              :type="getDoubleButtonStatus(question).type"
              :disabled="getDoubleButtonStatus(question).disabled"
              @click="handleStartMarking(getDoubleButtonStatus(question).task!, 'double')"
            >
              {{ getDoubleButtonStatus(question).text }}
            </wd-button>
          </view>
        </view>
      </view>

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