<route lang="jsonc">
{
  "style": {
    "navigationStyle": "custom",
    "navigationBarTitleText": "答题学生名单"
  }
}
</route>

<script lang="ts" setup>
import { useQuery } from '@tanstack/vue-query'
import { computed, onMounted, ref, watch } from 'vue'
import { useUserId } from '@/composables/useUserId'
import { teacherAnalysisQuestionScoreDetailUsingPost } from '@/service/laoshixiaotichengjifenxi'

defineOptions({
  name: 'QuestionScoreDetailPage',
})

// 页面参数
interface PageParams {
  exam_id: string
  grade_key: string
  class_key: string
  subject_id: string
}

const params = ref<PageParams>({
  exam_id: '',
  grade_key: '',
  class_key: '',
  subject_id: '',
})

// 使用 TanStack Query 获取所有题目的学生得分详情
const {
  data: questionListData,
  isLoading: loading,
} = useQuery({
  queryKey: [
    'question-score-detail',
    useUserId(),
    params.value.exam_id,
    params.value.grade_key,
    params.value.class_key,
    params.value.subject_id,
  ],
  queryFn: async () => {
    const response = await teacherAnalysisQuestionScoreDetailUsingPost({
      body: {
        exam_id: Number(params.value.exam_id),
        grade_key: Number(params.value.grade_key),
        class_key: Number(params.value.class_key),
        subject_id: Number(params.value.subject_id),
      },
    })
    return response?.question_detail_list || []
  },
  enabled: computed(() =>
    !!params.value.exam_id
    && !!params.value.grade_key
    && !!params.value.class_key
    && !!params.value.subject_id,
  ),
  staleTime: 30000,
})

// 题目列表
const questionList = computed(() => questionListData.value || [])

// 当前选中的题目索引
const currentQuestionIndex = ref(0)

// 当前题目
const currentQuestion = computed(() => {
  return questionList.value[currentQuestionIndex.value] || null
})

// 当前题目的学生得分列表
const scoreList = computed(() => {
  return currentQuestion.value?.student_score_list || []
})

// 题号选项（用于下拉选择）
const questionOptions = computed(() => {
  return questionList.value.map((q, index) => ({
    label: q.question_name || `题目${index + 1}`,
    value: index,
  }))
})

// 排序方式：题号、按分数
type SortType = 'number' | 'score'
const sortType = ref<SortType>('score')

// 切换题目
function handleQuestionChange(event: { value: string | number, selectedItem: Record<string, any> }) {
  currentQuestionIndex.value = Number(event.value)
}

// 返回上一页
function goBack() {
  uni.navigateBack()
}

// 初始题目ID（用于加载完成后定位）
const initialQuestionId = ref<number | null>(null)

// 监听数据加载完成，设置初始题目
watch(
  () => questionList.value,
  (list) => {
    if (list.length > 0 && initialQuestionId.value) {
      const index = list.findIndex(q => q.question_id === initialQuestionId.value)
      if (index !== -1) {
        currentQuestionIndex.value = index
        initialQuestionId.value = null // 只设置一次
      }
    }
  },
  { immediate: true },
)

// 页面初始化
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1] as any
  if (currentPage?.options) {
    params.value = {
      exam_id: currentPage.options.exam_id || '',
      grade_key: currentPage.options.grade_key || '',
      class_key: currentPage.options.class_key || '',
      subject_id: currentPage.options.subject_id || '',
    }
    // 保存初始题目ID
    if (currentPage.options.question_id) {
      initialQuestionId.value = Number(currentPage.options.question_id)
    }
  }
})
</script>

<template>
  <view class="question-score-detail-page min-h-screen bg-slate-50">
    <!-- 导航栏 -->
    <wd-navbar title="查看答题学生名单" placeholder fixed>
      <template #left>
        <div class="flex items-center" @tap="goBack">
          <wd-icon name="arrow-left" size="20px" />
        </div>
      </template>
    </wd-navbar>

    <!-- 主要内容区域 -->
    <view class="p-4">
      <!-- 题目选择器 -->
      <view class="mb-4 rounded-xl bg-white p-4 shadow-sm">
        <view class="flex items-center justify-between">
          <text class="text-sm text-slate-600">答题详情</text>
          <wd-drop-menu>
            <wd-drop-menu-item
              v-model="currentQuestionIndex"
              :options="questionOptions"
              @change="handleQuestionChange"
            />
          </wd-drop-menu>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="flex items-center justify-center py-20">
        <wd-loading size="24" />
      </view>

      <!-- 学生得分列表 -->
      <view v-else-if="scoreList.length > 0" class="space-y-3">
        <view
          v-for="(item, index) in scoreList"
          :key="index"
          class="rounded-xl bg-white shadow-sm"
        >
          <!-- 得分标题 -->
          <view class="border-b border-slate-100 px-4 py-3">
            <view class="flex items-center justify-between">
              <text class="text-base text-orange-500 font-medium">得分 {{ item.score }}分</text>
              <text class="text-sm text-slate-500">
                {{ item.student_count }}人，占比{{ item.student_rate ? `${(item.student_rate * 100).toFixed(2)}%` : '0%' }}
              </text>
            </view>
          </view>

          <!-- 学生名单 -->
          <view v-if="item.student_list && item.student_list.length > 0" class="p-4">
            <view class="flex flex-wrap gap-2">
              <view
                v-for="(student, sIndex) in item.student_list"
                :key="sIndex"
                class="inline-flex items-center rounded-md bg-blue-50 px-3 py-1"
              >
                <text class="text-sm text-blue-600">{{ student.student_name }}</text>
              </view>
            </view>
          </view>
          <view v-else class="py-4 text-center">
            <text class="text-sm text-gray-400">暂无学生</text>
          </view>
        </view>
      </view>

      <!-- 暂无数据 -->
      <view v-else class="py-20 text-center">
        <text class="text-sm text-gray-500">暂无数据</text>
      </view>
    </view>
  </view>
</template>

<style scoped>
.space-y-3 > view + view {
  margin-top: 12px;
}
</style>
