<route lang="jsonc">
{
  "style": {
    "navigationStyle": "custom",
    "navigationBarTitleText": "成绩单"
  }
}
</route>

<script lang="ts" setup>
import type { ScoreSheetInfo } from '@/service/types'
import { computed, ref } from 'vue'
import { teacherAnalysisScoreSheetUsingPost } from '@/service/laoshichengjifenxi'
import { useHomeStore } from '@/store/home'

defineOptions({
  name: 'ScoreListPage',
})

// 使用store
const homeStore = useHomeStore()

// z-paging 引用
const pagingRef = ref<ZPagingRef>()

// 成绩单数据
const scoreList = ref<ScoreSheetInfo[]>([])

// 班级选项
const classOptions = computed(() => homeStore.classOptions)

// 科目选项
const subjectOptions = computed(() => homeStore.subjectOptions)

// 当前选中的班级ID
const selectedClassId = ref<number | null>(homeStore.selectedClassId)

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

// 班级选择变化处理
function handleClassChange(event: { value: string | number, selectedItem: Record<string, any> }) {
  selectedClassId.value = Number(event.value)
  homeStore.selectedClassId = selectedClassId.value
  // 重新加载数据
  pagingRef.value?.reload()
}

// 查询成绩单数据
async function queryScoreList(pageNo: number, pageSize: number) {
  if (!homeStore.selectedClassId || !homeStore.selectedExamId || !homeStore.selectedGradeKey) {
    pagingRef.value?.complete([])
    return
  }

  try {
    const response = await teacherAnalysisScoreSheetUsingPost({
      body: {
        class_key: homeStore.selectedClassId,
        exam_id: homeStore.selectedExamId,
        grade_key: homeStore.selectedGradeKey,
        page: pageNo,
        page_size: pageSize,
      },
    })

    pagingRef.value?.complete(response?.list || [])
  }
  catch (error) {
    console.error('获取成绩单数据失败:', error)
    pagingRef.value?.complete(false)
  }
}

// 获取学生的某科成绩
function getSubjectScore(student: ScoreSheetInfo, subjectId: number) {
  const subjectScore = student.single_subject_score_list?.find(
    item => item.subject_id === subjectId,
  )
  return subjectScore?.subject_score ?? '--'
}

// 跳转到学生成绩报告
function viewStudentReport(student: ScoreSheetInfo) {
  uni.navigateTo({
    url: `/pages/student/detail?student_number=${student.student_exam_number}&student_name=${student.student_name}`,
  })
}

// 跳转到科目答题卡
function viewSubjectAnswerSheet(student: ScoreSheetInfo, subjectId: number) {
  const subjectScore = student.single_subject_score_list?.find(
    item => item.subject_id === subjectId,
  )
  uni.navigateTo({
    url: `/pages/student/answer-sheet?info_id=${subjectScore?.info_id}&subject_id=${subjectId}`,
  })
}
</script>

<template>
  <view class="score-list-page min-h-screen bg-slate-50">
    <!-- 主要内容区域 - z-paging 包裹 -->
    <z-paging
      ref="pagingRef"
      v-model="scoreList"
      :refresher-enabled="true"
      :auto="true"
      :default-page-size="20"
      @query="queryScoreList"
    >
      <template #top>
        <!-- 导航栏 -->
        <wd-navbar placeholder fixed right-text="成绩单">
          <template #left>
            <div class="flex items-center" @tap="goBack">
              <wd-icon name="arrow-left" size="20px" />
            </div>
          </template>
          <template #title>
            <wd-drop-menu>
              <wd-drop-menu-item
                v-model="selectedClassId"
                :options="classOptions"
                @change="handleClassChange"
              />
            </wd-drop-menu>
          </template>
        </wd-navbar>
      </template>

      <!-- 成绩单表格 -->
      <view class="p-4">
        <wd-table :data="scoreList" :height="600">
          <!-- 学生姓名列 -->
          <wd-table-col prop="student_name" label="考生姓名" :width="`${20}%`" fixed>
            <template #value="{ row }">
              <text class="cursor-pointer text-blue-500" @tap="viewStudentReport(row)">
                {{ row.student_name }}
              </text>
            </template>
          </wd-table-col>

          <!-- 总分列 -->
          <wd-table-col prop="all_score" label="总分" :width="`${20}%`">
            <template #value="{ row }">
              <text class="cursor-pointer text-blue-500" @tap="viewStudentReport(row)">
                {{ row.all_score || '--' }}
              </text>
            </template>
          </wd-table-col>

          <!-- 班次/校次列 -->
          <wd-table-col prop="rank" label="班次/校次" :width="`${40}%`">
            <template #value="{ row }">
              <view class="flex gap-2 text-xs">
                <view>{{ row.class_rank || '--' }}</view>
                /
                <view class="text-gray-500">
                  {{ row.grade_rank || '--' }}
                </view>
              </view>
            </template>
          </wd-table-col>

          <!-- 动态生成科目列 -->
          <wd-table-col
            v-for="subject in subjectOptions"
            :key="subject.value"
            :prop="`subject_${subject.value}`"
            :label="subject.label"
            :width="`${20}%`"
          >
            <template #value="{ row }">
              <text
                class="cursor-pointer text-blue-500"
                @tap="viewSubjectAnswerSheet(row, subject.subjectId)"
              >
                {{ getSubjectScore(row, subject.subjectId) }}
              </text>
            </template>
          </wd-table-col>
        </wd-table>
      </view>
    </z-paging>
  </view>
</template>
