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

<script lang="ts" setup>
import type { GetQuestionMarkingQualityResponse, MarkingQualityResponse, QuestionMarkingQualityTeacher } from '@/service/types'
import { onLoad } from '@dcloudio/uni-app'
import { useQuery } from '@tanstack/vue-query'
import { computed, ref, watch } from 'vue'
import QuestionTabs from '@/components/marking/QuestionTabs.vue'
import { useUserId } from '@/composables/useUserId'
import { markingQualityQuestionUsingGet, markingQualityUsingGet } from '@/service/yuejuanzhiliang'

defineOptions({
  name: 'MarkingQualityPage',
})

// 页面参数
const examSubjectId = ref<number>()
const questionId = ref<number>()

// 当前选中的评选类型（初评/终评）
const activeEvaluateType = ref<'initial' | 'final'>('initial')

// 页面加载时获取参数
onLoad((options) => {
  if (options.examSubjectId) {
    examSubjectId.value = Number(options.examSubjectId)
  }
  if (options.questionId) {
    questionId.value = Number(options.questionId)
  }
})

// 获取所有题目的阅卷质量数据
const {
  data: allQualityData,
  isLoading: isLoadingAll,
  error: errorAll,
  refetch: refetchAll,
} = useQuery({
  queryKey: ['marking-quality', examSubjectId, useUserId()],
  queryFn: () => markingQualityUsingGet({
    params: {
      exam_subject_id: examSubjectId.value!,
    },
  }),
  enabled: computed(() => !!examSubjectId.value),
  staleTime: 1000 * 60 * 5,
  gcTime: 1000 * 60 * 30,
})

// 解析所有题目数据
const allQualityResponse = computed<MarkingQualityResponse>(() => {
  return allQualityData.value
})

// 题目列表
const questionTabs = computed(() => {
  const questions = allQualityResponse.value?.subjective_item?.question_items || []
  return questions.map(question => ({
    id: question.question_id!,
    name: `${question.question_major}${question.question_minor ? `.${question.question_minor}` : ''}`,
    evaluate_method: question.evaluate_method,
    questionMajor: question.question_major,
    questionMinor: question.question_minor,
    averageScore: question.average_score,
    totalScore: question.total_score,
  }))
})

// 监听题目列表变化，设置默认选中第一个题目
watch(questionTabs, (newTabs) => {
  if (newTabs.length > 0 && !questionId.value) {
    questionId.value = newTabs[0].id
  }
}, { immediate: true })

// 获取具体题目的详细阅卷质量数据
const {
  data: questionQualityData,
  isLoading: isLoadingQuestion,
  error: errorQuestion,
  refetch: refetchQuestion,
} = useQuery({
  queryKey: ['question-marking-quality', questionId, useUserId()],
  queryFn: () => markingQualityQuestionUsingGet({
    params: {
      question_id: questionId.value!,
    },
  }),
  enabled: computed(() => !!questionId.value),
  staleTime: 1000 * 60 * 5,
  gcTime: 1000 * 60 * 30,
})

// 解析题目详细质量数据
const questionQualityResponse = computed<GetQuestionMarkingQualityResponse | undefined>(() => {
  return questionQualityData.value
})

// 当前题目信息
const currentQuestion = computed(() => {
  return questionTabs.value.find(q => q.id === questionId.value)
})

// 初评老师列表
const initialTeachers = computed<QuestionMarkingQualityTeacher[]>(() => {
  return questionQualityResponse.value?.initial_teachers || []
})

// 终评老师列表
const finalTeachers = computed<QuestionMarkingQualityTeacher[]>(() => {
  return questionQualityResponse.value?.final_teachers || []
})

// 当前显示的老师列表
const currentTeachers = computed<QuestionMarkingQualityTeacher[]>(() => {
  return activeEvaluateType.value === 'initial' ? initialTeachers.value : finalTeachers.value
})

// 是否有双评（既有初评又有终评）
const hasDoubleEvaluation = computed(() => {
  return initialTeachers.value.length > 0 && finalTeachers.value.length > 0
})

// 切换题目
function handleQuestionChange(newQuestionId: number) {
  questionId.value = newQuestionId
  // useQuery 会自动根据 queryKey 的变化重新获取数据
}

// 切换评选类型
function switchEvaluateType(type: 'initial' | 'final') {
  activeEvaluateType.value = type
}

// 刷新数据
function handleRefresh() {
  refetchAll()
  refetchQuestion()
}

function handleRetry() {
  refetchAll()
}

// 合并加载状态
const isLoading = computed(() => isLoadingAll.value || isLoadingQuestion.value)

// 合并错误状态
const error = computed(() => errorAll.value || errorQuestion.value)

// 获取老师等级标识颜色
function getTeacherLevelColor(score: number = 0, maxScore: number = 100) {
  const percentage = (score / maxScore) * 100
  if (percentage >= 90)
    return 'text-green-600'
  if (percentage >= 80)
    return 'text-blue-600'
  if (percentage >= 70)
    return 'text-orange-600'
  return 'text-red-600'
}

// 格式化分数显示
function formatScore(score: number = 0) {
  return score.toFixed(1)
}

// 格式化时间显示（秒转分钟）
function formatTime(seconds: number = 0) {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}分${remainingSeconds}秒`
}
</script>

<template>
  <view class="marking-quality-page">
    <!-- 题目选择组件 -->
    <QuestionTabs
      :question-tabs="questionTabs"
      :active-question-id="questionId"
      :loading="isLoadingAll"
      :error="errorAll"
      @change="handleQuestionChange"
      @retry="handleRetry"
    />

    <!-- 质量内容区域 -->
    <view class="p-4">
      <!-- 加载状态 -->
      <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 v-else class="space-y-4">
        <!-- 题目详情 -->
        <view class="mb-4 rounded-md bg-white p-4 shadow-sm">
          <text class="mb-2 block text-base font-semibold">题目详情</text>

          <view class="flex items-center justify-between gap-2">
            <view
              class="rounded-full bg-blue-100 px-3 py-1 text-xs"
            >
              总分{{ questionQualityResponse?.total_score || 0 }}
            </view>
            <view
              class="rounded-full bg-orange-100 px-3 py-1 text-xs"
            >
              平均分{{ questionQualityResponse?.average_score || 0 }}
            </view>
            <view
              class="rounded-full bg-red-100 px-3 py-1 text-xs"
            >
              最高分{{ questionQualityResponse?.max_score || 0 }}
            </view>
            <view
              class="rounded-full bg-green-100 px-3 py-1 text-xs"
            >
              最低分{{ questionQualityResponse?.min_score || 0 }}
            </view>
          </view>
        </view>

        <!-- 评选类型切换（仅在有双评时显示） -->
        <view v-if="hasDoubleEvaluation" class="border border-gray-100 rounded-2xl bg-white p-4 shadow-sm">
          <view class="flex space-x-4">
            <view
              class="flex-1 cursor-pointer rounded-lg py-2 text-center transition-colors"
              :class="activeEvaluateType === 'initial' ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-600'"
              @click="switchEvaluateType('initial')"
            >
              <text class="font-medium">初评老师</text>
            </view>
            <view
              class="flex-1 cursor-pointer rounded-lg py-2 text-center transition-colors"
              :class="activeEvaluateType === 'final' ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-600'"
              @click="switchEvaluateType('final')"
            >
              <text class="font-medium">终评老师</text>
            </view>
          </view>
        </view>

        <!-- 老师质量列表 -->
        <view v-if="currentTeachers.length > 0" class="space-y-3">
          <view class="mb-3">
            <text class="text-lg font-semibold">
              {{ hasDoubleEvaluation ? (activeEvaluateType === 'initial' ? '初评老师' : '终评老师') : '阅卷老师' }}
            </text>
          </view>

          <view
            v-for="(teacher, index) in currentTeachers"
            :key="`${teacher.teacher_id}-${index}`"
            class="border border-gray-100 rounded-2xl bg-white p-4 shadow-sm"
          >
            <!-- 老师基本信息 -->
            <view class="mb-3 flex items-center justify-between">
              <view class="flex items-center">
                <view class="mr-3 h-3 w-3 rounded-full" :class="getTeacherLevelColor(teacher.average_score || 0, currentQuestion?.totalScore || 100)" />
                <view>
                  <text class="text-base font-medium">{{ teacher.teacher_name || '未知老师' }}</text>
                  <text v-if="teacher.phone" class="block text-sm text-gray-500">{{ teacher.phone }}</text>
                </view>
              </view>
              <view class="text-right">
                <text class="block text-lg font-bold" :class="getTeacherLevelColor(teacher.average_score || 0, currentQuestion?.totalScore || 100)">
                  {{ formatScore(teacher.average_score || 0) }}分
                </text>
                <text class="text-sm text-gray-500">平均分</text>
              </view>
            </view>

            <!-- 老师详细统计 -->
            <view class="grid grid-cols-3 gap-4 border-t border-gray-100 pt-3">
              <view class="text-center">
                <text class="block text-base text-gray-700 font-semibold">{{ teacher.marking_count || 0 }}</text>
                <text class="text-xs text-gray-500">阅卷数</text>
              </view>
              <view class="text-center">
                <text class="block text-base text-gray-700 font-semibold">{{ formatTime(teacher.average_time || 0) }}</text>
                <text class="text-xs text-gray-500">平均用时</text>
              </view>
              <view class="text-center">
                <text class="block text-base text-red-600 font-semibold">{{ teacher.problem_num || 0 }}</text>
                <text class="text-xs text-gray-500">问题卷</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 暂无数据 -->
        <view v-else class="py-12 text-center">
          <text class="text-sm text-gray-500">
            {{ hasDoubleEvaluation ? `暂无${activeEvaluateType === 'initial' ? '初评' : '终评'}老师数据` : '暂无老师数据' }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.marking-quality-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}
</style>
