<route lang="jsonc">
{
  "style": {
    "navigationStyle": "custom",
    "navigationBarTitleText": "小题详情"
  }
}
</route>

<script lang="ts" setup>
import type * as API from '@/service/types'
import { useQuery } from '@tanstack/vue-query'
import { computed, onMounted, ref } from 'vue'
import QuestionDetailPopup from '@/components/class-analysis/QuestionDetailPopup.vue'
import QuestionDetailTable from '@/components/class-analysis/QuestionDetailTable.vue'
import { useUserId } from '@/composables/useUserId'
import { teacherAnalysisQuestionDetailUsingPost, teacherAnalysisQuestionScoreDetailUsingPost } from '@/service/laoshixiaotichengjifenxi'
import { useHomeStore } from '@/store/home'

defineOptions({
  name: 'QuestionDetailPage',
})

// 使用store
const homeStore = useHomeStore()

// 选中的考试ID
const selectedExamId = ref<number>()

// 考试选项
const examOptions = computed(() => homeStore.examOptions)

// 使用 TanStack Query 获取小题详情数据
const {
  data: questionDetailData,
  isLoading: loading,
} = useQuery({
  queryKey: [
    'question-detail',
    useUserId(),
    selectedExamId,
    homeStore.selectedGradeKey,
    homeStore.selectedClassId,
    homeStore.selectedSubjectId,
  ],
  queryFn: async () => {
    const response = await teacherAnalysisQuestionDetailUsingPost({
      body: {
        exam_id: selectedExamId.value!,
        grade_key: homeStore.selectedGradeKey!,
        class_key: homeStore.selectedClassId!,
        subject_id: homeStore.selectedSubjectId!,
      },
    })
    return response?.question_detail_list || []
  },
  enabled: computed(() =>
    !!selectedExamId.value
    && !!homeStore.selectedGradeKey
    && !!homeStore.selectedClassId
    && !!homeStore.selectedSubjectId,
  ),
  staleTime: 30000,
})

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

// 当前查看的题目详情（来自表格，用于获取question_id）
const selectedQuestionItem = ref<API.QuestionStatInfo | null>(null)
// 当前题目的完整详情（包含学生得分信息）
const currentQuestion = ref<API.QuestionStatInfo | null>(null)
const showDetailDialog = ref(false)
const loadingDetail = ref(false)

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

// 考试选择变化处理
function handleExamChange(event: { value: string | number, selectedItem: Record<string, any> }) {
  selectedExamId.value = Number(event.value)
}

// 查看详情 - 使用 teacherAnalysisQuestionScoreDetailUsingPost 获取完整数据
async function viewDetail(item: API.QuestionStatInfo) {
  selectedQuestionItem.value = item
  showDetailDialog.value = true
  loadingDetail.value = true

  try {
    const response = await teacherAnalysisQuestionScoreDetailUsingPost({
      body: {
        exam_id: selectedExamId.value!,
        grade_key: homeStore.selectedGradeKey!,
        class_key: homeStore.selectedClassId!,
        subject_id: homeStore.selectedSubjectId!,
      },
    })

    // 从返回的题目列表中找到当前题目（包含完整的学生得分信息）
    const questionList = response?.question_detail_list || []
    const fullQuestion = questionList.find(q => q.question_id === item.question_id)

    if (fullQuestion) {
      currentQuestion.value = fullQuestion
    }
    else {
      // 如果没找到，使用原始数据
      currentQuestion.value = item
    }
  }
  catch (error) {
    console.error('获取题目详情失败:', error)
    // 出错时使用原始数据
    currentQuestion.value = item
  }
  finally {
    loadingDetail.value = false
  }
}

// 查看学生名单 - 跳转到新页面
function handleViewStudentList(question: API.QuestionStatInfo) {
  uni.navigateTo({
    url: `/pages/class-analysis/question-score-detail?exam_id=${selectedExamId.value}&grade_key=${homeStore.selectedGradeKey}&class_key=${homeStore.selectedClassId}&subject_id=${homeStore.selectedSubjectId}&question_id=${question.question_id}`,
  })
}

onLoad((options) => {
  selectedExamId.value = Number(options.examId)
})
</script>

<template>
  <view class="question-detail-page min-h-screen bg-slate-50">
    <!-- 导航栏 -->
    <wd-navbar placeholder fixed>
      <template #left>
        <div class="flex items-center" @tap="goBack">
          <wd-icon name="arrow-left" size="20px" />
        </div>
      </template>
      <template #title>
        <div class="flex items-center justify-center">
          <text class="text-xs">小题详情 ——</text>
          <wd-drop-menu>
            <wd-drop-menu-item
              v-model="selectedExamId"
              :options="examOptions"
              @change="handleExamChange"
            />
          </wd-drop-menu>
        </div>
      </template>
    </wd-navbar>

    <!-- 主要内容区域 -->
    <view class="p-4">
      <!-- 小题详情表格 -->
      <QuestionDetailTable
        :data="questionList"
        :loading="loading"
        @view-detail="viewDetail"
      />
    </view>

    <!-- 题目详情弹窗 -->
    <QuestionDetailPopup
      v-model:visible="showDetailDialog"
      :question="currentQuestion"
      :loading="loadingDetail"
      @view-student-list="handleViewStudentList"
    />
  </view>
</template>
