<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)
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="h-screen flex flex-col bg-gray-100">
    <wd-navbar
      placeholder
      fixed
      custom-class="bg-white"
    >
      <template #left>
        <view class="h-8 w-8 flex items-center justify-center" @click="goBack">
          <wd-icon name="arrow-left" size="20px" color="#333" />
        </view>
      </template>
      <template #title>
        <text class="text-base text-gray-800 font-bold">{{ apiData?.student_name || '学生' }} - 答题卡</text>
      </template>
    </wd-navbar>

    <view class="relative z-10 bg-white shadow-sm">
      <wd-tabs
        v-model="activeTab"
        sticky
        line-width="20"
        line-height="3"
        color="#2563EB"
        inactive-color="#64748B"
        @click="handleTabClick"
      >
        <wd-tab
          v-for="tab in subjectTabs"
          :key="tab.name"
          :name="tab.name"
          :title="tab.title"
        />
      </wd-tabs>
    </view>

    <view class="relative w-full flex-1 overflow-hidden">
      <AnswerSheetWithMarking
        :data="answerSheetData"
        :loading="isLoading"
        :error="!!error"
      />
    </view>
  </view>
</template>

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