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

<script lang="ts" setup>
import type * as API from '@/service/types'
import { computed, onMounted, ref, watch } from 'vue'
import {
  teacherAnalysisClassExamComparisonUsingPost,
  teacherAnalysisKeyStudentUsingPost,
  teacherAnalysisRankStatisticsUsingPost,
  teacherAnalysisRecentExamStatsUsingPost,
} from '@/service/laoshichengjifenxi'
import { useHomeStore } from '@/store/home'

// 类型别名
type ExamComparisonItem = API.ExamComparisonItem
type RankStatisticsItem = API.RankStatisticsItem
type KeyStudentInfo = API.KeyStudentInfo

defineOptions({
  name: 'ScorePage',
})

// 使用store
const homeStore = useHomeStore()

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

// 分数线设置
const scoreSettings = ref({
  excellent_scoring_rate: 85,
  good_scoring_rate: 75,
  pass_scoring_rate: 60,
  top_n: 50,
  // 名次分析的三个前xx名配置
  rank_top_1: 10, // 前10名
  rank_top_2: 20, // 前20名
  rank_top_3: 50, // 前50名
})

// 统计数据
const statsData = ref({
  examCount: 0,
  averageScore: 0,
  totalScore: 100,
  highestScore: 0,
  lowestScore: 0,
  excellentRate: 0,
  goodRate: 0,
  passRate: 0,
})

// 对比数据
const comparisonData = ref<ExamComparisonItem[]>([])

// 对比模式：horizontal-横向，vertical-纵向
const comparisonMode = ref('horizontal')

// 名次统计数据
const rankStatsData = ref<RankStatisticsItem[]>([])

// 名次分析选中的班级列表
const selectedClassIds = ref<string[]>([])

// 重点学生数据（进步/退步）
const keyStudentsData = ref<KeyStudentInfo[]>([])

// 重点学生类型：up-进步，down-退步
const keyStudentType = ref<'up' | 'down'>('up')

// 是否展开显示更多学生
const showMoreStudents = ref(false)

// z-paging引用
const keyStudentsPaging = ref(null)

// 学生列表数据（用于z-paging）
const keyStudentsList = ref<KeyStudentInfo[]>([])

// 加载状态
const loading = ref(false)

// 设置弹窗状态
const showOverviewSettingsDialog = ref(false) // 整体概况设置弹窗
const showRankSettingsDialog = ref(false) // 名次分析设置弹窗

const tempOverviewSettings = ref({
  excellent_scoring_rate: scoreSettings.value.excellent_scoring_rate,
  good_scoring_rate: scoreSettings.value.good_scoring_rate,
  pass_scoring_rate: scoreSettings.value.pass_scoring_rate,
  top_n: scoreSettings.value.top_n,
})

const tempRankSettings = ref({
  rank_top_1: scoreSettings.value.rank_top_1,
  rank_top_2: scoreSettings.value.rank_top_2,
  rank_top_3: scoreSettings.value.rank_top_3,
})

// 进步/退步学生显示数量（基础显示）
const keyStudentCount = ref(5)

// 分页大小（展开后使用）
const pageSize = ref(20)

// 考试选择选项
const examOptions = computed(() => homeStore.examOptions.map(exam => ({
  label: exam.label,
  value: exam.value,
})))

// 班级多选选项（用于wd-select-picker）
const classColumns = computed(() => homeStore.classOptions.map(cls => ({
  label: cls.label,
  value: cls.value.toString(), // 转为字符串类型
})))

// 当前选中的考试ID
const selectedExamId = computed({
  get: () => homeStore.selectedExamId,
  set: (value) => {
    homeStore.onExamChange(value)
  },
})

// 当前选中的考试名称
const selectedExamName = computed(() => {
  if (!homeStore.selectedExamId) {
    return '请选择考试'
  }
  const exam = homeStore.examOptions.find(item => item.value === homeStore.selectedExamId)
  return exam?.label || '请选择考试'
})

// 科目选项（包含全科）
const subjectTabs = computed(() => {
  const tabs = [
    { name: 'all', title: '全科', subjectId: 0 },
  ]

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

  return tabs
})

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

// 获取整体概况数据
async function fetchOverviewStats() {
  if (!homeStore.selectedClassId || !homeStore.selectedExamId || !homeStore.selectedGradeKey) {
    return
  }

  try {
    loading.value = true
    const response = await teacherAnalysisRecentExamStatsUsingPost({
      body: {
        class_key: homeStore.selectedClassId,
        exam_id: homeStore.selectedExamId,
        grade_key: homeStore.selectedGradeKey,
        subject_id: selectedSubjectId.value || undefined,
        excellent_scoring_rate: scoreSettings.value.excellent_scoring_rate,
        good_scoring_rate: scoreSettings.value.good_scoring_rate,
        pass_scoring_rate: scoreSettings.value.pass_scoring_rate,
        top_n: scoreSettings.value.top_n,
      },
    }) as any

    if (response?.data) {
      const data = response.data
      statsData.value = {
        examCount: data.class_total_count || 0,
        averageScore: Math.round(data.class_average_score || 0),
        totalScore: data.full_score || 100,
        highestScore: data.class_highest_score || 0,
        lowestScore: data.class_lowest_score || 0,
        excellentRate: Math.round((data.excellent_class_scoring_rate || 0) * 100),
        goodRate: Math.round((data.good_class_scoring_rate || 0) * 100),
        passRate: Math.round((data.pass_class_scoring_rate || 0) * 100),
      }
    }
  }
  catch (error) {
    console.error('获取整体概况数据失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 获取对比数据
async function fetchComparisonData() {
  if (!homeStore.selectedClassId || !homeStore.selectedGradeKey) {
    return
  }

  try {
    if (comparisonMode.value === 'horizontal') {
      // 横向对比暂时返回空数据
      comparisonData.value = []
    }
    else {
      // 纵向对比 - 获取班级考试对比数据
      const response = await teacherAnalysisClassExamComparisonUsingPost({
        body: {
          class_key: homeStore.selectedClassId,
          grade_key: homeStore.selectedGradeKey,
          subject_id: selectedSubjectId.value || undefined,
        },
      }) as any

      if (response?.data?.exam_list) {
        comparisonData.value = response.data.exam_list
      }
    }
  }
  catch (error) {
    console.error('获取对比数据失败:', error)
    comparisonData.value = []
  }
}

// 获取名次统计数据
async function fetchRankStatistics() {
  if (!homeStore.selectedExamId) {
    return
  }

  try {
    // 如果没有选中班级，使用当前选中的班级
    const classIds = selectedClassIds.value.length > 0 ? selectedClassIds.value.map(id => Number.parseInt(id)) : (homeStore.selectedClassId ? [homeStore.selectedClassId] : [])

    if (classIds.length === 0) {
      rankStatsData.value = []
      return
    }

    const response = await teacherAnalysisRankStatisticsUsingPost({
      body: {
        class_id: classIds[0], // 暂时使用第一个班级，后续可改为数组
        exam_id: homeStore.selectedExamId,
        subject_id: selectedSubjectId.value || undefined,
      },
    }) as any

    if (response?.data?.data) {
      rankStatsData.value = response.data.data
    }
  }
  catch (error) {
    console.error('获取名次统计数据失败:', error)
    rankStatsData.value = []
  }
}

// 获取重点学生数据（基础显示）
async function fetchKeyStudents() {
  if (!homeStore.selectedClassId || !homeStore.selectedExamId || !homeStore.selectedGradeKey) {
    return
  }

  try {
    const response = await teacherAnalysisKeyStudentUsingPost({
      body: {
        class_key: homeStore.selectedClassId,
        exam_id: homeStore.selectedExamId,
        grade_key: homeStore.selectedGradeKey,
        subject_id: selectedSubjectId.value || undefined,
        emphasis_type: keyStudentType.value,
        page: 1,
        page_size: keyStudentCount.value, // 使用动态数量
      },
    }) as any

    if (response?.data?.list) {
      keyStudentsData.value = response.data.list
    }
  }
  catch (error) {
    console.error('获取重点学生数据失败:', error)
    keyStudentsData.value = []
  }
}

// 获取重点学生数据（分页加载）
async function fetchKeyStudentsPaging(pageNo: number, pageSize: number) {
  if (!homeStore.selectedClassId || !homeStore.selectedExamId || !homeStore.selectedGradeKey) {
    keyStudentsPaging.value?.complete(false)
    return
  }

  try {
    const response = await teacherAnalysisKeyStudentUsingPost({
      body: {
        class_key: homeStore.selectedClassId,
        exam_id: homeStore.selectedExamId,
        grade_key: homeStore.selectedGradeKey,
        subject_id: selectedSubjectId.value || undefined,
        emphasis_type: keyStudentType.value,
        page: pageNo,
        page_size: pageSize,
      },
    }) as any

    if (response?.data?.list) {
      keyStudentsPaging.value?.complete(response.data.list)
    }
    else {
      keyStudentsPaging.value?.complete([])
    }
  }
  catch (error) {
    console.error('获取重点学生数据失败:', error)
    keyStudentsPaging.value?.complete(false)
  }
}

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

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

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

// 整体概况设置按钮处理
function handleOverviewSettings() {
  tempOverviewSettings.value = {
    excellent_scoring_rate: scoreSettings.value.excellent_scoring_rate,
    good_scoring_rate: scoreSettings.value.good_scoring_rate,
    pass_scoring_rate: scoreSettings.value.pass_scoring_rate,
    top_n: scoreSettings.value.top_n,
  }
  showOverviewSettingsDialog.value = true
}

// 名次分析设置按钮处理
function handleRankSettings() {
  tempRankSettings.value = {
    rank_top_1: scoreSettings.value.rank_top_1,
    rank_top_2: scoreSettings.value.rank_top_2,
    rank_top_3: scoreSettings.value.rank_top_3,
  }
  showRankSettingsDialog.value = true
}

// 确认整体概况设置
function confirmOverviewSettings() {
  const validations = [
    {
      condition: tempOverviewSettings.value.excellent_scoring_rate <= 0 || tempOverviewSettings.value.excellent_scoring_rate > 100,
      message: '优秀分数线应在1-100之间',
    },
    {
      condition: tempOverviewSettings.value.good_scoring_rate <= 0 || tempOverviewSettings.value.good_scoring_rate > 100,
      message: '良好分数线应在1-100之间',
    },
    {
      condition: tempOverviewSettings.value.pass_scoring_rate <= 0 || tempOverviewSettings.value.pass_scoring_rate > 100,
      message: '及格分数线应在1-100之间',
    },
    {
      condition: tempOverviewSettings.value.top_n <= 0 || tempOverviewSettings.value.top_n > 1000,
      message: '前N名应在1-1000之间',
    },
  ]

  const failedValidation = validations.find(v => v.condition)
  if (failedValidation) {
    uni.showToast({
      title: failedValidation.message,
      icon: 'none',
    })
    return
  }

  // 更新设置
  scoreSettings.value.excellent_scoring_rate = tempOverviewSettings.value.excellent_scoring_rate
  scoreSettings.value.good_scoring_rate = tempOverviewSettings.value.good_scoring_rate
  scoreSettings.value.pass_scoring_rate = tempOverviewSettings.value.pass_scoring_rate
  scoreSettings.value.top_n = tempOverviewSettings.value.top_n

  showOverviewSettingsDialog.value = false

  // 重新获取数据
  fetchOverviewStats()

  uni.showToast({
    title: '设置已保存',
    icon: 'success',
  })
}

// 确认名次分析设置
function confirmRankSettings() {
  const validations = [
    {
      condition: tempRankSettings.value.rank_top_1 <= 0 || tempRankSettings.value.rank_top_1 > 500,
      message: '前xx名(1)应在1-500之间',
    },
    {
      condition: tempRankSettings.value.rank_top_2 <= 0 || tempRankSettings.value.rank_top_2 > 500,
      message: '前xx名(2)应在1-500之间',
    },
    {
      condition: tempRankSettings.value.rank_top_3 <= 0 || tempRankSettings.value.rank_top_3 > 500,
      message: '前xx名(3)应在1-500之间',
    },
  ]

  const failedValidation = validations.find(v => v.condition)
  if (failedValidation) {
    uni.showToast({
      title: failedValidation.message,
      icon: 'none',
    })
    return
  }

  // 更新设置
  scoreSettings.value.rank_top_1 = tempRankSettings.value.rank_top_1
  scoreSettings.value.rank_top_2 = tempRankSettings.value.rank_top_2
  scoreSettings.value.rank_top_3 = tempRankSettings.value.rank_top_3

  showRankSettingsDialog.value = false

  // 重新获取数据
  fetchRankStatistics()

  uni.showToast({
    title: '设置已保存',
    icon: 'success',
  })
}

// 取消整体概况设置
function cancelOverviewSettings() {
  showOverviewSettingsDialog.value = false
}

// 取消名次分析设置
function cancelRankSettings() {
  showRankSettingsDialog.value = false
}

// 切换对比模式
function toggleComparisonMode(mode: 'horizontal' | 'vertical') {
  comparisonMode.value = mode
  fetchComparisonData()
}

// 查看成绩单
function handleViewScoreList() {
  if (!homeStore.selectedClassId || !homeStore.selectedExamId) {
    uni.showToast({
      title: '请先选择班级和考试',
      icon: 'none',
    })
    return
  }

  uni.navigateTo({
    url: `/pages/index/score-list`,
  })
}

// 切换重点学生类型（进步/退步）
function toggleKeyStudentType(type: 'up' | 'down') {
  keyStudentType.value = type
  if (showMoreStudents.value) {
    // 如果已展开，刷新分页数据
    keyStudentsPaging.value?.reload()
  }
  else {
    // 否则刷新基础数据
    fetchKeyStudents()
  }
}

// 显示更多进步/退步学生
function handleShowMoreKeyStudents() {
  if (!homeStore.selectedClassId || !homeStore.selectedExamId || !homeStore.selectedGradeKey) {
    uni.showToast({
      title: '请先选择班级和考试',
      icon: 'none',
    })
    return
  }

  showMoreStudents.value = true
  // 初始化分页数据
  setTimeout(() => {
    keyStudentsPaging.value?.reload()
  }, 100)
}

// 收起更多学生列表
function handleHideMoreKeyStudents() {
  showMoreStudents.value = false
  // 重新获取基础数据
  fetchKeyStudents()
}

// 班级选择变化处理
function handleClassChange({ value }: { value: string[] }) {
  selectedClassIds.value = value
  // 重新获取数据
  fetchRankStatistics()
}

// 监听考试和科目变化
watch([() => homeStore.selectedExamId, selectedSubjectId], () => {
  if (homeStore.selectedExamId && homeStore.selectedClassId && homeStore.selectedGradeKey) {
    fetchOverviewStats()
    fetchComparisonData()
    fetchRankStatistics()
    if (!showMoreStudents.value) {
      fetchKeyStudents()
    }
    else {
      keyStudentsPaging.value?.reload()
    }
  }
}, { immediate: false })

// 监听选中班级变化
watch(selectedClassIds, () => {
  if (homeStore.selectedExamId) {
    fetchRankStatistics()
  }
}, { deep: true })

// 监听重点学生数量变化
watch(keyStudentCount, () => {
  if (homeStore.selectedExamId && homeStore.selectedClassId && homeStore.selectedGradeKey && !showMoreStudents.value) {
    fetchKeyStudents()
  }
})

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

    // 获取数据
    if (homeStore.selectedExamId && homeStore.selectedClassId && homeStore.selectedGradeKey) {
      await fetchOverviewStats()
      await fetchComparisonData()
      await fetchRankStatistics()
      await fetchKeyStudents()
    }
  }
  catch (error) {
    console.error('初始化数据失败:', error)
  }
})
</script>

<template>
  <view class="score-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="title items-center">
          <wd-drop-menu>
            <wd-drop-menu-item
              v-model="selectedExamId"
              :options="examOptions"
              @change="handleExamChange"
            />
          </wd-drop-menu>
        </div>
      </template>
    </wd-navbar>

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

    <!-- 主要内容区域 -->
    <view class="p-4 space-y-4">
      <!-- 整体概况卡片 -->
      <view class="rounded-xl bg-white p-3 shadow-sm">
        <view class="mb-4 flex items-center justify-between">
          <text class="text-lg text-slate-800 font-semibold">整体概况</text>
          <view class="i-mingcute:filter-line text-lg text-cyan-500" @tap="handleOverviewSettings" />
        </view>

        <!-- 统计数据网格 - 2行3列 -->
        <view class="grid grid-cols-3 gap-1">
          <!-- 考试人数 -->
          <view class="border border-blue-100 rounded-xl from-white to-blue-50 bg-gradient-to-br p-3">
            <view class="mb-2 flex items-center">
              <text class="text-xs text-slate-600">考试人数</text>
            </view>
            <text class="text-lg text-slate-800 font-bold">{{ statsData.examCount }}</text>
          </view>

          <!-- 平均分/满分 -->
          <view class="border border-blue-100 rounded-xl from-white to-blue-50 bg-gradient-to-br p-3">
            <view class="mb-2 flex items-center">
              <text class="text-xs text-slate-600">平均分/满分</text>
            </view>
            <text class="text-lg text-slate-800 font-bold">{{ statsData.averageScore }}/{{ statsData.totalScore }}</text>
          </view>

          <!-- 最高分/最低分 -->
          <view class="border border-cyan-100 rounded-xl from-white to-cyan-50 bg-gradient-to-br p-3">
            <view class="mb-2 flex items-center">
              <text class="text-xs text-slate-600">最高分/最低分</text>
            </view>
            <text class="text-lg text-slate-800 font-bold">{{ statsData.highestScore }}/{{ statsData.lowestScore }}</text>
          </view>

          <!-- 优秀率 -->
          <view class="border border-sky-100 rounded-xl from-white to-sky-50 bg-gradient-to-br p-3">
            <view class="mb-2 flex items-center">
              <text class="text-xs text-slate-600">优秀率</text>
            </view>
            <text class="text-lg text-slate-800 font-bold">{{ statsData.excellentRate }}%</text>
          </view>

          <!-- 良好率 -->
          <view class="border border-sky-100 rounded-xl from-white to-sky-50 bg-gradient-to-br p-3">
            <view class="mb-2 flex items-center">
              <text class="text-xs text-slate-600">良好率</text>
            </view>
            <text class="text-lg text-slate-800 font-bold">{{ statsData.goodRate }}%</text>
          </view>

          <!-- 及格率 -->
          <view class="border border-blue-100 rounded-xl from-white to-blue-50 bg-gradient-to-br p-3">
            <view class="mb-2 flex items-center">
              <text class="text-xs text-slate-600">及格率</text>
            </view>
            <text class="text-lg text-slate-800 font-bold">{{ statsData.passRate }}%</text>
          </view>
        </view>

        <!-- 查看成绩单按钮 -->
        <view class="mt-6">
          <wd-button
            type="primary"
            size="medium"
            class="w-full"
            @click="handleViewScoreList"
          >
            查看成绩单
          </wd-button>
        </view>
      </view>

      <!-- 学科均分对比卡片 -->
      <view class="rounded-xl bg-white p-4 shadow-sm">
        <view class="mb-4 flex items-center justify-between">
          <text class="text-lg text-slate-800 font-semibold">学科均分对比</text>
          <view class="flex items-center gap-2">
            <text
              class="rounded px-2 py-1 text-sm"
              :class="comparisonMode === 'horizontal' ? 'bg-blue-100 text-blue-600' : 'text-gray-500'"
              @tap="toggleComparisonMode('horizontal')"
            >
              横向
            </text>
            <text
              class="rounded px-2 py-1 text-sm"
              :class="comparisonMode === 'vertical' ? 'bg-blue-100 text-blue-600' : 'text-gray-500'"
              @tap="toggleComparisonMode('vertical')"
            >
              纵向
            </text>
          </view>
        </view>

        <!-- 对比数据表头 -->
        <view class="mb-2 border-b border-gray-200 pb-2">
          <view class="grid grid-cols-4 gap-2 text-center">
            <text class="text-sm text-gray-600 font-medium">
              {{ comparisonMode === 'horizontal' ? '学科' : '考试' }}
            </text>
            <text class="text-sm text-gray-600 font-medium">班级平均分</text>
            <text class="text-sm text-gray-600 font-medium">年级平均分</text>
            <text class="text-sm text-gray-600 font-medium">班级排名</text>
          </view>
        </view>

        <!-- 对比数据列表 -->
        <view class="space-y-2">
          <view
            v-for="(item, index) in comparisonData"
            :key="index"
            class="grid grid-cols-4 gap-2 border-b border-gray-100 py-2 text-center last:border-b-0"
          >
            <text class="text-sm text-gray-800">{{ item.exam_name || '-' }}</text>
            <text class="text-sm text-gray-800 font-medium">{{ item.class_average || '-' }}</text>
            <text class="text-sm text-gray-600">{{ item.class_standard || '-' }}</text>
            <text class="text-sm text-gray-600">{{ item.average_rank || '-' }}</text>
          </view>
        </view>

        <!-- 暂无数据提示 -->
        <view v-if="comparisonData.length === 0" class="py-8 text-center">
          <text class="text-sm text-gray-500">暂无对比数据</text>
        </view>
      </view>

      <!-- 名次分析卡片 -->
      <view class="rounded-xl bg-white p-4 shadow-sm">
        <view class="mb-4 flex items-center justify-between">
          <text class="no-wrap w-fit flex-shrink-0 text-lg text-slate-800 font-semibold">名次分析</text>
          <!-- 班级多选 -->
          <wd-select-picker
            v-model="selectedClassIds"
            class="classes-picker flex-grow"
            :columns="classColumns"
            :show-confirm="false"
            @confirm="handleClassChange"
          />
          <view class="i-mingcute:filter-line text-lg text-cyan-500" @tap="handleRankSettings" />
        </view>

        <!-- 名次统计表头 -->
        <view class="mb-2 border-b border-gray-200 pb-2">
          <view class="grid grid-cols-4 gap-2 text-center">
            <text class="text-sm text-gray-600 font-medium">班级</text>
            <text class="text-sm text-gray-600 font-medium">前{{ scoreSettings.rank_top_1 }}名</text>
            <text class="text-sm text-gray-600 font-medium">前{{ scoreSettings.rank_top_2 }}名</text>
            <text class="text-sm text-gray-600 font-medium">前{{ scoreSettings.rank_top_3 }}名</text>
          </view>
        </view>

        <!-- 名次统计数据 -->
        <view class="space-y-2">
          <view
            v-for="(item, index) in rankStatsData"
            :key="index"
            class="grid grid-cols-4 gap-2 border-b border-gray-100 py-2 text-center last:border-b-0"
          >
            <text class="text-sm text-gray-800 font-medium">{{ item.name || '-' }}</text>
            <text class="text-sm text-gray-800">
              {{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_1)?.count || 0 }}
            </text>
            <text class="text-sm text-gray-800">
              {{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_2)?.count || 0 }}
            </text>
            <text class="text-sm text-gray-800">
              {{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_3)?.count || 0 }}
            </text>
          </view>
        </view>

        <!-- 暂无数据提示 -->
        <view v-if="rankStatsData.length === 0" class="py-8 text-center">
          <text class="text-sm text-gray-500">暂无名次数据</text>
        </view>
      </view>

      <!-- 进步/退步学生卡片 -->
      <view class="rounded-xl bg-white p-4 shadow-sm">
        <view class="mb-4 flex items-center justify-between">
          <view class="flex items-center gap-2">
            <text class="text-lg text-slate-800 font-semibold">
              班级{{ keyStudentType === 'up' ? '进步' : '退步' }}前
            </text>
            <wd-input
              v-model="keyStudentCount"
              type="number"
              placeholder="5"
              class="w-12 text-center"
              :border="true"
            />
            <text class="text-lg text-slate-800 font-semibold">名</text>
          </view>
          <view class="flex items-center gap-2">
            <text
              class="rounded px-2 py-1 text-sm"
              :class="keyStudentType === 'up' ? 'bg-green-100 text-green-600' : 'text-gray-500'"
              @tap="toggleKeyStudentType('up')"
            >
              进步
            </text>
            <text
              class="rounded px-2 py-1 text-sm"
              :class="keyStudentType === 'down' ? 'bg-red-100 text-red-600' : 'text-gray-500'"
              @tap="toggleKeyStudentType('down')"
            >
              退步
            </text>
          </view>
        </view>

        <!-- 学生表头 -->
        <view class="mb-2 border-b border-gray-200 pb-2">
          <view class="grid grid-cols-3 gap-2 text-center">
            <text class="text-sm text-gray-600 font-medium">姓名</text>
            <text class="text-sm text-gray-600 font-medium">本次排名</text>
            <text class="text-sm text-gray-600 font-medium">
              {{ keyStudentType === 'up' ? '进步' : '退步' }}名次
            </text>
          </view>
        </view>

        <!-- 学生数据列表 -->
        <view class="space-y-2">
          <view
            v-for="(student, index) in keyStudentsData"
            :key="index"
            class="grid grid-cols-3 gap-2 border-b border-gray-100 py-2 text-center last:border-b-0"
          >
            <text class="text-sm text-gray-800 font-medium">{{ student.student_name || '-' }}</text>
            <text class="text-sm text-gray-800">{{ student.class_rank || '-' }}</text>
            <text
              class="text-sm font-medium"
              :class="keyStudentType === 'up' ? 'text-green-600' : 'text-red-600'"
            >
              {{ keyStudentType === 'up' ? '+' : '-' }}{{ student.class_diff_rank || 0 }}
            </text>
          </view>
        </view>

        <!-- 暂无数据提示 -->
        <view v-if="keyStudentsData.length === 0" class="py-8 text-center">
          <text class="text-sm text-gray-500">暂无{{ keyStudentType === 'up' ? '进步' : '退步' }}学生数据</text>
        </view>

        <!-- 显示更多按钮 -->
        <view v-if="keyStudentsData.length > 0 && !showMoreStudents" class="mt-4">
          <wd-button
            type="info"
            size="medium"
            class="w-full"
            @click="handleShowMoreKeyStudents"
          >
            显示更多{{ keyStudentType === 'up' ? '进步' : '退步' }}学生
          </wd-button>
        </view>

        <!-- 收起按钮 -->
        <view v-if="showMoreStudents" class="mt-4">
          <wd-button
            type="info"
            size="medium"
            class="w-full"
            @click="handleHideMoreKeyStudents"
          >
            收起列表
          </wd-button>
        </view>
      </view>

      <!-- 更多学生列表（z-paging） -->
      <view v-if="showMoreStudents" class="rounded-xl bg-white shadow-sm">
        <view class="border-b border-gray-100 p-4">
          <text class="text-lg text-slate-800 font-semibold">
            {{ keyStudentType === 'up' ? '进步' : '退步' }}学生详细列表
          </text>
        </view>

        <z-paging
          ref="keyStudentsPaging"
          v-model="keyStudentsList"
          :default-page-size="pageSize"
          :auto="false"
          @query="fetchKeyStudentsPaging"
        >
          <!-- 表头 -->
          <view class="border-b border-gray-200 p-4">
            <view class="grid grid-cols-3 gap-2 text-center">
              <text class="text-sm text-gray-600 font-medium">姓名</text>
              <text class="text-sm text-gray-600 font-medium">本次排名</text>
              <text class="text-sm text-gray-600 font-medium">
                {{ keyStudentType === 'up' ? '进步' : '退步' }}名次
              </text>
            </view>
          </view>

          <!-- 学生数据列表 -->
          <view class="divide-y divide-gray-100">
            <view
              v-for="(student, index) in keyStudentsList"
              :key="index"
              class="grid grid-cols-3 gap-2 p-4 text-center"
            >
              <text class="text-sm text-gray-800 font-medium">{{ student.student_name || '-' }}</text>
              <text class="text-sm text-gray-800">{{ student.class_rank || '-' }}</text>
              <text
                class="text-sm font-medium"
                :class="keyStudentType === 'up' ? 'text-green-600' : 'text-red-600'"
              >
                {{ keyStudentType === 'up' ? '+' : '-' }}{{ student.class_diff_rank || 0 }}
              </text>
            </view>
          </view>
        </z-paging>
      </view>
    </view>

    <!-- 整体概况设置弹窗 -->
    <wd-popup
      v-model="showOverviewSettingsDialog"
      position="center"
      custom-style="border-radius: 16px; width: 80%; max-width: 400px;"
      :close-on-click-modal="false"
    >
      <view class="p-6">
        <!-- 标题 -->
        <view class="mb-6 text-center">
          <text class="text-lg text-gray-800 font-semibold">整体概况设置</text>
        </view>

        <!-- 表单内容 -->
        <view class="space-y-4">
          <!-- 优秀得分率 -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">优秀得分率</text>
            <text class="text-sm text-gray-500">≥</text>
            <wd-input
              v-model="tempOverviewSettings.excellent_scoring_rate"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">%</text>
          </view>

          <!-- 良好得分率 -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">良好得分率</text>
            <text class="text-sm text-gray-500">≥</text>
            <wd-input
              v-model="tempOverviewSettings.good_scoring_rate"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">%</text>
          </view>

          <!-- 及格得分率 -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">及格得分率</text>
            <text class="text-sm text-gray-500">≥</text>
            <wd-input
              v-model="tempOverviewSettings.pass_scoring_rate"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">%</text>
          </view>

          <!-- 年级前N名 -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">年级前N名</text>
            <text class="text-sm text-gray-500">-</text>
            <wd-input
              v-model="tempOverviewSettings.top_n"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">名</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="mt-6 flex gap-3">
          <wd-button type="info" class="flex-1" @click="cancelOverviewSettings">
            取消
          </wd-button>
          <wd-button type="primary" class="flex-1" @click="confirmOverviewSettings">
            确定
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 名次分析设置弹窗 -->
    <wd-popup
      v-model="showRankSettingsDialog"
      position="center"
      custom-style="border-radius: 16px; width: 80%; max-width: 400px;"
      :close-on-click-modal="false"
    >
      <view class="p-6">
        <!-- 标题 -->
        <view class="mb-6 text-center">
          <text class="text-lg text-gray-800 font-semibold">名次分析设置</text>
        </view>

        <!-- 表单内容 -->
        <view class="space-y-4">
          <!-- 前xx名(1) -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">前xx名(1)</text>
            <text class="text-sm text-gray-500">-</text>
            <wd-input
              v-model="tempRankSettings.rank_top_1"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">名</text>
          </view>

          <!-- 前xx名(2) -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">前xx名(2)</text>
            <text class="text-sm text-gray-500">-</text>
            <wd-input
              v-model="tempRankSettings.rank_top_2"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">名</text>
          </view>

          <!-- 前xx名(3) -->
          <view class="flex items-center justify-center gap-4">
            <text class="text-sm text-gray-700 font-medium">前xx名(3)</text>
            <text class="text-sm text-gray-500">-</text>
            <wd-input
              v-model="tempRankSettings.rank_top_3"
              type="number"
              placeholder="请输入"
              class="w-20 text-center"
              :border="true"
            />
            <text class="text-sm text-gray-700">名</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="mt-6 flex gap-3">
          <wd-button type="info" class="flex-1" @click="cancelRankSettings">
            取消
          </wd-button>
          <wd-button type="primary" class="flex-1" @click="confirmRankSettings">
            确定
          </wd-button>
        </view>
      </view>
    </wd-popup>

    <!-- 加载状态 -->
    <view v-if="loading" class="fixed inset-0 z-50 flex items-center justify-center bg-black/20">
      <view class="rounded-xl bg-white p-4">
        <wd-loading size="24" />
        <text class="mt-2 block text-sm text-gray-600">加载中...</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.classes-picker {
  .wd-cell__value--left {
    width: 0;
    flex-grow: 1;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
  }
}
</style>
