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

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

defineOptions({
  name: 'ScoreListPage',
})

// 成绩单数据扩展类型
interface ScoreSheetItemExtended extends ScoreSheetInfo {
  subjectScores: Record<number, number> // 各科成绩映射
}

// 使用store
const homeStore = useHomeStore()

// 页面参数
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const loading = ref(false)

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

// 班级选项
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
  // 重新获取数据
  currentPage.value = 1
  fetchScoreList()
}

// 分页变化处理
function handlePageChange(page: number) {
  currentPage.value = page
  fetchScoreList()
}

// 获取成绩单数据
async function fetchScoreList() {
  if (!selectedClassId.value || !homeStore.selectedExamId || !homeStore.selectedGradeKey) {
    return
  }

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

    if (response) {
      const responseData = response as GetScoreSheetResponse
      total.value = responseData.total || 0
      // 处理成绩数据，添加各科成绩映射
      scoreList.value = (responseData.list || []).map(item => ({
        ...item,
        subjectScores: {}, // TODO: 根据实际API返回的数据结构来填充各科成绩
      }))
    }
  }
  catch (error) {
    console.error('获取成绩单数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 跳转到学生成绩报告
function viewStudentReport(student: ScoreSheetItemExtended) {
  // TODO: 跳转到学生成绩报告页面
  console.log('查看学生成绩报告:', student)
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  })
}

// 跳转到科目答题卡
function viewSubjectAnswerSheet(student: ScoreSheetItemExtended, subjectId: number) {
  // TODO: 跳转到科目答题卡页面
  console.log('查看科目答题卡:', student, subjectId)
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  })
}

// 页面初始化
onMounted(async () => {
  try {
    // 如果store中没有数据，先获取选项数据
    if (homeStore.classOptions.length === 0) {
      await homeStore.fetchOptions()
    }

    // 获取成绩单数据
    if (homeStore.selectedClassId && homeStore.selectedExamId) {
      selectedClassId.value = homeStore.selectedClassId
      await fetchScoreList()
    }
  }
  catch (error) {
    console.error('初始化数据失败:', error)
  }
})
</script>

<template>
  <view class="score-list-page min-h-screen bg-slate-50">
    <!-- 导航栏 -->
    <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>

    <!-- 主要内容区域 -->
    <view class="p-4">
      <!-- 成绩单表格 -->
      <wd-table :data="scoreList" :height="600" :loading="loading">
        <!-- 学生姓名列 -->
        <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="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.value)"
            >
              {{ row.subjectScores[subject.value] || '--' }}
            </text>
          </template>
        </wd-table-col>
      </wd-table>

      <!-- 分页组件 -->
      <view v-if="total > 0" class="mt-4 flex justify-center">
        <wd-pagination
          v-model="currentPage"
          :total="total"
          :page-size="pageSize"
          show-icon
          show-message
          @change="handlePageChange"
        />
      </view>

      <!-- 空状态 -->
      <view v-if="!loading && scoreList.length === 0" class="py-8 text-center text-gray-500">
        暂无成绩数据
      </view>
    </view>
  </view>
</template>
