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

<script lang="ts" setup>
import type { MarkingProgressResponse, QuestionMarkingProgressResponse, TaskTypeProgressDetail } 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 { DictCode, useDict } from '@/composables/useDict'
import { useUserId } from '@/composables/useUserId'
import { markingProgressQuestionUsingGet, markingProgressUsingGet } from '@/service/yuejuanjindu'

defineOptions({
  name: 'MarkingProgressPage',
})

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

// 展开的学校ID集合
const expandedSchools = ref<Set<number>>(new Set())

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

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

// 解析所有题目数据
const allProgressResponse = computed<MarkingProgressResponse | undefined>(() => {
  return allProgressData.value
})

// 题目列表
const questionTabs = computed(() => {
  const questions = allProgressResponse.value?.questions || []
  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,
  }))
})

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

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

// 解析题目详细进度数据
const questionProgressResponse = computed<QuestionMarkingProgressResponse | undefined>(() => {
  return questionProgressData.value
})

// 进度列表
const progressList = computed<TaskTypeProgressDetail[]>(() => {
  return questionProgressResponse.value?.progress_list || []
})

// 切换题目
function handleQuestionChange(newQuestionId: number) {
  questionId.value = newQuestionId
  // 重新获取题目详细数据
  refetchQuestion()
}

// 切换学校展开状态
function toggleSchoolExpand(schoolId: number) {
  const newExpanded = new Set(expandedSchools.value)
  if (newExpanded.has(schoolId)) {
    newExpanded.delete(schoolId)
  }
  else {
    newExpanded.add(schoolId)
  }
  expandedSchools.value = newExpanded
}

// 计算进度百分比
function getProgressPercentage(marked: number = 0, total: number = 0) {
  if (total === 0)
    return 0
  return Math.round((marked / total) * 100)
}

// 获取任务类型显示名称
function getTaskTypeDisplayName(taskType: string) {
  switch (taskType) {
    case 'first': return '初评进度'
    case 'final': return '终评进度'
    default: return taskType
  }
}

const { getDictOptionsAndGetLabel } = useDict()
const [, getTaskTypeLabel] = getDictOptionsAndGetLabel(DictCode.TASK_TYPE)

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

function handleRetry() {
  refetchAll()
}

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

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

<template>
  <view class="marking-progress-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
          v-for="taskProgress in progressList"
          :key="taskProgress.task_type"
          class="space-y-3"
        >
          <!-- 任务类型标题 -->
          <view class="mb-4 rounded-md bg-white p-4 shadow-sm">
            <view class="mb-4 flex items-center justify-between">
              <text class="block text-base font-semibold">
                {{ `${getTaskTypeLabel(taskProgress.task_type || '')}进度` }}
              </text>
              <view class="flex items-center gap-2">
                <view
                  class="rounded-full bg-blue-100 px-2 py-1 text-xs"
                >
                  已阅{{ taskProgress.marked_quantity || 0 }}
                </view>
                <view
                  class="rounded-full bg-orange-100 px-2 py-1 text-xs"
                >
                  待阅{{ (taskProgress.total_quantity || 0) - (taskProgress.marked_quantity || 0) }}
                </view>
              </view>
            </view>

            <!-- 进度条 -->
            <view class="flex items-center justify-between gap-2">
              <view class="w-full flex items-center justify-between rounded-full bg-gray-200">
                <view
                  class="h-4 rounded-full bg-blue-500 transition-all duration-300"
                  :style="{ width: `${getProgressPercentage(taskProgress.marked_quantity, taskProgress.total_quantity)}%` }"
                />
              </view>
              <text class="text-sm text-blue-600 font-medium">
                {{ getProgressPercentage(taskProgress.marked_quantity, taskProgress.total_quantity) }}%
              </text>
            </view>
          </view>

          <!-- 学校列表 -->
          <view class="space-y-3">
            <view
              v-for="school in taskProgress.school_list"
              :key="`${taskProgress.task_type}-${school.school_id}`"
              class="border border-gray-100 rounded-2xl bg-white p-4 shadow-sm"
            >
              <!-- 学校头部信息 -->
              <view
                class="flex cursor-pointer items-center justify-between"
                @click="toggleSchoolExpand(school.school_id!)"
              >
                <view class="flex-1">
                  <text class="mb-1 block text-base font-medium">{{ school.school_name }}</text>
                  <text class="text-sm text-gray-600">
                    进度{{ school.marking_list?.reduce((sum, t) => sum + (t.marked_quantity || 0), 0) || 0 }}/{{ school.marking_list?.reduce((sum, t) => sum + (t.total_quantity || 0), 0) || 0 }}
                  </text>
                </view>

                <view class="flex items-center space-x-2">
                  <text class="text-sm text-blue-600 font-medium">
                    {{ getProgressPercentage(
                      school.marking_list?.reduce((sum, t) => sum + (t.marked_quantity || 0), 0),
                      school.marking_list?.reduce((sum, t) => sum + (t.total_quantity || 0), 0),
                    ) }}%
                  </text>
                  <view
                    class="transition-transform duration-200"
                    :class="{ 'rotate-180': expandedSchools.has(school.school_id!) }"
                  >
                    <view class="i-carbon-chevron-down text-lg text-gray-400" />
                  </view>
                </view>
              </view>

              <!-- 老师列表（可展开） -->
              <view
                v-if="expandedSchools.has(school.school_id!) && school.marking_list?.length"
                class="mt-4 space-y-2"
              >
                <view
                  v-for="teacher in school.marking_list"
                  :key="teacher.teacher_id"
                  class="flex items-center justify-between rounded-lg bg-gray-50 p-3"
                >
                  <!-- 老师信息 -->
                  <view class="flex items-center">
                    <view class="mr-3 h-2 w-2 rounded-full bg-green-500" />
                    <text class="text-sm">{{ teacher.teacher_name }}</text>
                  </view>

                  <!-- 老师进度 -->
                  <view class="flex items-center space-x-2">
                    <view class="min-w-20 flex-1">
                      <view class="h-1.5 w-full rounded-full bg-gray-200">
                        <view
                          class="h-1.5 rounded-full bg-green-500 transition-all duration-300"
                          :style="{ width: `${getProgressPercentage(teacher.marked_quantity, teacher.total_quantity)}%` }"
                        />
                      </view>
                    </view>
                    <text class="min-w-12 text-right text-xs text-gray-600">
                      {{ teacher.marked_quantity || 0 }}/{{ teacher.total_quantity || 0 }}
                    </text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 暂无数据 -->
        <view v-if="progressList.length === 0" class="py-12 text-center">
          <text class="text-sm text-gray-500">暂无进度数据</text>
        </view>
      </view>
    </view>
  </view>
</template>

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

.question-tabs {
  :deep(.wd-tab) {
    font-size: 14px;
    white-space: nowrap;
  }
}
</style>
