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

<script lang="ts" setup>
import type * as API from '@/service/types'
import { useQuery, useQueryClient } from '@tanstack/vue-query'
import { whenever } from '@vueuse/core'
import { computed, ref } from 'vue'
import OverviewSettingsDialog from '@/components/score/OverviewSettingsDialog.vue'
import RankSettingsDialog from '@/components/score/RankSettingsDialog.vue'
import { useUserId } from '@/composables/useUserId'
import {
  teacherAnalysisClassExamComparisonHorizontalUsingPost,
  teacherAnalysisClassExamComparisonUsingPost,
  teacherAnalysisKeyStudentUsingPost,
  teacherAnalysisRankStatisticsUsingPost,
  teacherAnalysisRecentExamStatsUsingPost,
} from '@/service/laoshichengjifenxi'
import { useHomeStore } from '@/store/home'

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

defineOptions({
  name: 'ScorePage',
})

// 使用store
const homeStore = useHomeStore()
const queryClient = useQueryClient()

// 选中的科目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名
})

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

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

// 重点学生类型：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 showOverviewSettingsDialog = ref(false)
const showRankSettingsDialog = ref(false)

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

// 考试选择选项
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(), // 转为字符串类型
})))

// 当前选中的考试名称
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.subjectId}`,
      title: subject.label,
      subjectId: subject.subjectId,
    })
  })

  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
    }
  },
})

// 查询启用条件
const isQueryEnabled = computed(() =>
  !!homeStore.selectedClassId && !!homeStore.selectedExamId && !!homeStore.selectedGradeKey,
)

// 使用 TanStack Query 获取整体概况数据
const {
  data: statsData,
  isLoading: isLoadingStats,
  refetch: refetchStats,
} = useQuery({
  queryKey: [
    'overview-stats',
    useUserId(),
    homeStore.selectedClassId,
    homeStore.selectedExamId,
    homeStore.selectedGradeKey,
    selectedSubjectId,
    scoreSettings.value.excellent_scoring_rate,
    scoreSettings.value.good_scoring_rate,
    scoreSettings.value.pass_scoring_rate,
    scoreSettings.value.top_n,
  ],
  queryFn: async () => {
    return 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,
      },
    })
  },
  enabled: isQueryEnabled,
  staleTime: 30000, // 30秒内不重新请求
})

type ExamComparisonItem = API.ExamComparisonItem & API.ExamComparisonItemH

const {
  data: comparisonData,
  isLoading: isLoadingComparison,
} = useQuery({
  queryKey: [
    'comparison-data',
    useUserId(),
    comparisonMode,
    homeStore.selectedClassId,
    homeStore.selectedExamId,
    homeStore.selectedGradeKey,
    selectedSubjectId.value,
  ],
  queryFn: async () => {
    if (comparisonMode.value === 'horizontal') {
      return (await teacherAnalysisClassExamComparisonHorizontalUsingPost({
        body: {
          exam_id: homeStore.selectedExamId,
          class_key: homeStore.selectedClassId,
          grade_key: homeStore.selectedGradeKey,
          subject_id: selectedSubjectId.value || undefined,
        },
      })).exam_list as ExamComparisonItem[] || []
    }
    else {
      return (await teacherAnalysisClassExamComparisonUsingPost({
        body: {
          class_key: homeStore.selectedClassId,
          grade_key: homeStore.selectedGradeKey,
          subject_id: selectedSubjectId.value || undefined,
        },
      })).exam_list as ExamComparisonItem[] || []
    }
  },
  enabled: computed(() => !!homeStore.selectedClassId && !!homeStore.selectedGradeKey),
  staleTime: 30000,
})

// 使用 TanStack Query 获取名次统计数据
const {
  data: rankStatsData,
  isLoading: isLoadingRank,
} = useQuery({
  queryKey: [
    'rank-statistics',
    useUserId(),
    selectedClassIds,
    homeStore.selectedClassId,
    homeStore.selectedExamId,
    selectedSubjectId,
    scoreSettings.value.rank_top_1,
    scoreSettings.value.rank_top_2,
    scoreSettings.value.rank_top_3,
  ],
  queryFn: async () => {
    const classIds = selectedClassIds.value.length > 0
      ? selectedClassIds.value
      : (homeStore.selectedClassId ? [homeStore.selectedClassId.toString()] : [])

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

    return (await teacherAnalysisRankStatisticsUsingPost({
      body: {
        class_ids: classIds,
        exam_id: homeStore.selectedExamId,
        subject_id: selectedSubjectId.value || 0,
        query_mode: 'class',
        statistics_mode: 'cumulative',
        rank_ranges: [
          { name: `前${scoreSettings.value.rank_top_1}名`, start: 1, end: Number(scoreSettings.value.rank_top_1) },
          { name: `前${scoreSettings.value.rank_top_2}名`, start: 1, end: Number(scoreSettings.value.rank_top_2) },
          { name: `前${scoreSettings.value.rank_top_3}名`, start: 1, end: Number(scoreSettings.value.rank_top_3) },
        ],
      },
    })).data as any || []
  },
  enabled: computed(() => !!homeStore.selectedExamId),
  staleTime: 30000,
})

// 获取重点学生数据（分页加载）
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: Number(pageSize),
      },
    }) as any

    if (response?.list) {
      keyStudentsPaging.value?.complete(response.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> }) {
  homeStore.selectedExamId = typeof event.value === 'string' ? Number.parseInt(event.value) : event.value
}

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

// 整体概况设置按钮处理
function handleOverviewSettings() {
  showOverviewSettingsDialog.value = true
}

// 名次分析设置按钮处理
function handleRankSettings() {
  showRankSettingsDialog.value = true
}

// 确认整体概况设置
function confirmOverviewSettings(settings: typeof scoreSettings.value) {
  Object.assign(scoreSettings.value, settings)

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

// 确认名次分析设置
function confirmRankSettings(settings: Pick<typeof scoreSettings.value, 'rank_top_1' | 'rank_top_2' | 'rank_top_3'>) {
  Object.assign(scoreSettings.value, settings)

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

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

// 查看成绩单
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()
  }
}

// 收起更多学生列表
function handleHideMoreKeyStudents() {
  showMoreStudents.value = false
  // 清空列表数据
  keyStudentsList.value = []
}

// 班级选择变化处理
function handleClassChange({ value }: { value: string[] }) {
  selectedClassIds.value = value
}

whenever(() => [selectedSubjectId.value, homeStore.selectedExamId, keyStudentType.value, keyStudentCount.value], () => {
  keyStudentsPaging.value?.reload()
})
</script>

<template>
  <view class="score-page min-h-screen bg-slate-50">
    <!-- z-paging 包裹整个内容 -->
    <z-paging
      ref="keyStudentsPaging"
      v-model="keyStudentsList"
      :default-page-size="keyStudentCount || 5"
      :refresher-enabled="true"
      :auto="true"
      @query="fetchKeyStudentsPaging"
    >
      <template #top>
        <!-- 导航栏 -->
        <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="homeStore.selectedExamId"
                  :options="homeStore.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>
      </template>

      <!-- 主要内容区域 -->
      <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?.class_total_count || 0 }}</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">{{ Math.round(statsData?.class_average_score || 0) }}/{{ statsData?.full_score || 100 }}</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?.class_highest_score || 0 }}/{{ statsData?.class_lowest_score || 0 }}</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">{{ Math.round((statsData?.excellent_class_scoring_rate || 0) * 100) }}%</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">{{ Math.round((statsData?.good_class_scoring_rate || 0) * 100) }}%</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">{{ Math.round((statsData?.pass_class_scoring_rate || 0) * 100) }}%</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">{{ comparisonMode === 'horizontal' ? '年级平均分' : '平均分排名' }}</text>
              <text class="text-sm text-gray-600 font-medium">{{ comparisonMode === 'horizontal' ? '班级排名' : '班级标准分' }}</text>
            </view>
          </view>
          <!-- 对比数据列表 -->
          <!-- 暂无数据提示 -->
          <view v-if="comparisonData.length === 0" class="py-8 text-center">
            <text class="text-sm text-gray-500">暂无对比数据</text>
          </view>

          <view v-else 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-ellipsis text-sm text-gray-800">{{ comparisonMode === 'horizontal' ? item.subject_name : item.exam_name || '-' }}</text>
              <text class="text-ellipsis text-sm text-gray-800 font-medium">{{ item.class_average || '-' }}</text>
              <text class="text-ellipsis text-sm text-gray-600">{{ comparisonMode === 'horizontal' ? item.grade_average || '-' : item.average_rank || '-' }}</text>
              <text class="text-ellipsis text-sm text-gray-600">{{ comparisonMode === 'horizontal' ? item.class_rank || '-' : item.class_standard || '-' }}</text>
            </view>
          </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-ellipsis text-sm text-gray-800 font-medium">{{ item.name || '-' }}</text>
              <text class="text-ellipsis text-sm text-gray-800">
                {{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_1)?.count || 0 }}
              </text>
              <text class="text-ellipsis text-sm text-gray-800">
                {{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_2)?.count || 0 }}
              </text>
              <text class="text-ellipsis 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 || 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 keyStudentsList"
              :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-ellipsis text-sm text-gray-800 font-medium">{{ student.student_name || '-' }}</text>
              <text class="text-ellipsis text-sm text-gray-800">{{ student.class_rank || '-' }}</text>
              <text
                class="text-ellipsis 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="!keyStudentsList || keyStudentsList.length === 0" class="py-8 text-center">
            <text class="text-sm text-gray-500">暂无{{ keyStudentType === 'up' ? '进步' : '退步' }}学生数据</text>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 整体概况设置弹窗 -->
    <OverviewSettingsDialog
      v-model="showOverviewSettingsDialog"
      :settings="scoreSettings"
      @confirm="confirmOverviewSettings"
    />

    <!-- 名次分析设置弹窗 -->
    <RankSettingsDialog
      v-model="showRankSettingsDialog"
      :settings="scoreSettings"
      @confirm="confirmRankSettings"
    />
  </view>
</template>

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

// 防溢出通用类
.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
