<!-- 答题卡查看器页面 -->
<script setup lang="ts">
import { useQuery } from '@tanstack/vue-query'
import { teacherScoreAnalysisApi } from '@/api'
import { AnswerSheetWithMarking, useDataParser } from '@/components/answer-sheet-viewer'
import { useHomeStore } from '@/store/home'

defineOptions({
  name: 'StudentAnswerSheet',
})

const homeStore = useHomeStore()

// 获取页面参数
const infoId = ref(0)

// 选中的科目ID，0表示全科
const selectedSubjectId = ref(0)

// 获取答题卡数据
const {
  data: apiData,
  isLoading,
  error,
} = useQuery({
  queryKey: ['studentAnswerSheet', infoId.value, selectedSubjectId.value],
  queryFn: async () => {
    return await teacherScoreAnalysisApi.teacherAnalysisDetail(infoId.value)
  },
  enabled: computed(() => infoId.value > 0),
})

// 解析为组件需要的格式
const { parseAnswerSheetData } = useDataParser()
const answerSheetData = computed(() => {
  return parseAnswerSheetData(apiData.value) || null
})

// 科目选项（不包含全科）
const subjectTabs = computed(() => {
  const tabs: Array<{ name: string, title: string, subjectId: number }> = []

  homeStore.subjectOptions.forEach((subject) => {
    tabs.push({
      name: `subject-${subject.subjectId}`,
      title: subject.label,
      subjectId: subject.subjectId,
    })
  })

  return tabs
})

// 当前选中的科目标签
const activeTab = computed({
  get: () => `subject-${selectedSubjectId.value}`,
  set: (value) => {
    const subjectId = Number.parseInt(value.replace('subject-', ''))
    selectedSubjectId.value = subjectId
  },
})

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

// 科目切换处理
function handleTabClick({ name }: { name: string }) {
  activeTab.value = name
}

// 页面初始化
onLoad((options) => {
  infoId.value = Number(options.info_id || 0)
  selectedSubjectId.value = Number(options.subject_id || 0)
})
</script>

<template>
  <view class="min-h-screen from-gray-50 to-gray-100 bg-gradient-to-b">
    <!-- 导航栏 -->
    <wd-navbar placeholder fixed>
      <template #left>
        <view class="flex items-center" @click="goBack">
          <wd-icon name="arrow-left" size="20px" />
        </view>
      </template>
      <template #title>
        <text class="text-lg font-semibold">{{ apiData.student_name }}-答题卡</text>
      </template>
    </wd-navbar>

    <!-- 科目选择标签栏 -->
    <wd-tabs
      v-model="activeTab"
      sticky
      class="bg-white shadow-sm"
      @click="handleTabClick"
    >
      <wd-tab
        v-for="tab in subjectTabs"
        :key="tab.name"
        :name="tab.name"
        :title="tab.title"
      />
    </wd-tabs>

    <!-- 答题卡内容区 -->
    <view class="h-[calc(100vh-88px)]">
      <AnswerSheetWithMarking :data="answerSheetData" :loading="isLoading" :error="!!error" />
    </view>
  </view>
</template>

<route lang="jsonc">
{
  "style": {
    "navigationStyle": "custom",
    "navigationBarTitleText": "答题卡"
  }
}
</route>
