<route lang="jsonc">
  {
    "style": {
      "navigationStyle": "custom",
      "navigationBarTitleText": "成绩分析",
      "navigationBarBackgroundColor": "#f8fafc"
    }
  }
  </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,
  rank_top_1: 10,
  rank_top_2: 20,
  rank_top_3: 50,
})

// 对比模式
const comparisonMode = ref('horizontal')
const selectedClassIds = ref<string[]>([])
const keyStudentType = ref<'up' | 'down'>('up')
const showMoreStudents = ref(false)
const keyStudentsPaging = ref(null)
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,
})))

const classColumns = computed(() => homeStore.classOptions.map(cls => ({
  label: cls.label,
  value: cls.value.toString(),
})))

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

// --- API Hooks (保持逻辑不变) ---

const { data: statsData } = 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,
})

type ExamComparisonItem = API.ExamComparisonItem & API.ExamComparisonItemH

const { data: comparisonData } = 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,
})

const { data: rankStatsData } = 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,
})

// --- Methods ---

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
    keyStudentsPaging.value?.complete(response?.list || [])
  }
  catch (error) {
    keyStudentsPaging.value?.complete(false)
  }
}

function goBack() {
  uni.navigateBack()
}

function handleExamChange(event: { value: string | number }) {
  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 handleClassChange({ value }: { value: string[] }) {
  selectedClassIds.value = value
}

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

<template>
  <view class="page-container bg-slate-50">
    <z-paging
      ref="keyStudentsPaging"
      v-model="keyStudentsList"
      :default-page-size="keyStudentCount || 5"
      :refresher-enabled="true"
      :auto="true"
      bg-color="#f8fafc"
      @query="fetchKeyStudentsPaging"
    >
      <template #top>
        <wd-navbar

          placeholder safe-area-inset-top fixed
          custom-class="nav-bar-custom"
        >
          <template #left>
            <view class="flex items-center p-2" @tap="goBack">
              <wd-icon name="arrow-left" size="24px" color="#334155" />
            </view>
          </template>
          <template #title>
            <view class="w-48 flex justify-center">
              <wd-drop-menu custom-class="w-full">
                <wd-drop-menu-item
                  v-model="homeStore.selectedExamId"
                  :options="homeStore.examOptions"
                  custom-class="font-bold text-slate-800"
                  @change="handleExamChange"
                />
              </wd-drop-menu>
            </view>
          </template>
        </wd-navbar>

        <view class="relative z-10 bg-white shadow-sm">
          <wd-tabs
            v-model="activeTab"
            custom-class="w-full"
            line-width="20"
            line-height="3"
            color="#3b82f6"
            active-color="#3b82f6"
            inactive-color="#64748b"
            @click="handleTabClick"
          >
            <wd-tab
              v-for="tab in subjectTabs"
              :key="tab.name"
              :name="tab.name"
              :title="tab.title"
            />
          </wd-tabs>
        </view>
      </template>

      <view class="p-4 pb-8 space-y-4">
        <view class="overflow-hidden rounded-lg bg-white shadow-sm">
          <view class="flex items-center justify-between border-b border-slate-100 px-4 py-3">
            <view class="flex items-center gap-2">
              <view class="h-4 w-1 rounded-full bg-blue-500" />
              <text class="text-base text-slate-800 font-bold">整体概况</text>
            </view>
            <view
              class="rounded-full p-2 transition-colors active:bg-slate-100"
              @tap="handleOverviewSettings"
            >
              <view class="i-mingcute:settings-3-line text-xl text-slate-400" />
            </view>
          </view>

          <view class="p-4">
            <view class="grid grid-cols-3 mb-4 gap-3">
              <view class="flex flex-col items-center justify-center border border-blue-100 rounded-lg bg-blue-50 p-3">
                <text class="mb-1 text-xs text-blue-500">考试人数</text>
                <text class="text-xl text-blue-700 font-bold">{{ statsData?.class_total_count || 0 }}</text>
              </view>
              <view class="flex flex-col items-center justify-center border border-blue-100 rounded-lg bg-blue-50 p-3">
                <text class="mb-1 text-xs text-blue-500">平均分</text>
                <text class="text-xl text-blue-700 font-bold">{{ Math.round(statsData?.class_average_score || 0) }}</text>
                <text class="mt-1 scale-90 text-xs text-blue-300">满分{{ statsData?.full_score || 100 }}</text>
              </view>
              <view class="flex flex-col items-center justify-center border border-cyan-100 rounded-lg bg-cyan-50 p-3">
                <text class="mb-1 text-xs text-cyan-600">最高/最低</text>
                <view class="flex items-baseline gap-1">
                  <text class="text-lg text-cyan-700 font-bold">{{ statsData?.class_highest_score || 0 }}</text>
                  <text class="text-xs text-cyan-400">/</text>
                  <text class="text-sm text-cyan-600 font-medium">{{ statsData?.class_lowest_score || 0 }}</text>
                </view>
              </view>
            </view>

            <view class="grid grid-cols-3 gap-4 pt-2">
              <view class="flex flex-col items-center">
                <text class="font-din text-2xl text-emerald-500 font-bold">{{ Math.round((statsData?.excellent_class_scoring_rate || 0) * 100) }}<text class="text-sm text-emerald-400">%</text></text>
                <text class="mt-1 text-xs text-slate-500">优秀率</text>
              </view>
              <view class="flex flex-col items-center border-l border-slate-100">
                <text class="font-din text-2xl text-sky-500 font-bold">{{ Math.round((statsData?.good_class_scoring_rate || 0) * 100) }}<text class="text-sm text-sky-400">%</text></text>
                <text class="mt-1 text-xs text-slate-500">良好率</text>
              </view>
              <view class="flex flex-col items-center border-l border-slate-100">
                <text class="font-din text-2xl text-indigo-500 font-bold">{{ Math.round((statsData?.pass_class_scoring_rate || 0) * 100) }}<text class="text-sm text-indigo-400">%</text></text>
                <text class="mt-1 text-xs text-slate-500">及格率</text>
              </view>
            </view>

            <view class="mt-5">
              <wd-button type="primary" block custom-class="rounded-full shadow-md shadow-blue-100" @click="handleViewScoreList">
                查看完整成绩单
              </wd-button>
            </view>
          </view>
        </view>

        <view class="overflow-hidden rounded-lg bg-white shadow-sm">
          <view class="flex items-center justify-between border-b border-slate-100 px-4 py-3">
            <view class="flex items-center gap-2">
              <view class="h-4 w-1 rounded-full bg-orange-400" />
              <text class="text-base text-slate-800 font-bold">学科均分对比</text>
            </view>
            <view class="flex rounded-lg bg-slate-100 p-0.5">
              <view
                class="rounded-md px-3 py-1 text-xs transition-all"
                :class="comparisonMode === 'horizontal' ? 'bg-white text-blue-600 shadow-sm font-medium' : 'text-slate-500'"
                @tap="toggleComparisonMode('horizontal')"
              >
                横向
              </view>
              <view
                class="rounded-md px-3 py-1 text-xs transition-all"
                :class="comparisonMode === 'vertical' ? 'bg-white text-blue-600 shadow-sm font-medium' : 'text-slate-500'"
                @tap="toggleComparisonMode('vertical')"
              >
                纵向
              </view>
            </view>
          </view>

          <view class="p-2">
            <view class="grid grid-cols-4 mb-2 rounded-md bg-slate-50 py-2 text-center">
              <text class="text-xs text-slate-500">{{ comparisonMode === 'horizontal' ? '学科' : '考试' }}</text>
              <text class="text-xs text-slate-500">班级均分</text>
              <text class="text-xs text-slate-500">{{ comparisonMode === 'horizontal' ? '年级均分' : '均分排名' }}</text>
              <text class="text-xs text-slate-500">{{ comparisonMode === 'horizontal' ? '班级排名' : '标准分' }}</text>
            </view>

            <template v-if="comparisonData && comparisonData.length > 0">
              <view
                v-for="(item, index) in comparisonData"
                :key="index"
                class="grid grid-cols-4 border-b border-slate-50 py-3 text-center last:border-none"
              >
                <text class="truncate px-1 text-sm text-slate-700">{{ comparisonMode === 'horizontal' ? item.subject_name : item.exam_name || '-' }}</text>
                <text class="text-sm text-slate-800 font-bold">{{ item.class_average || '-' }}</text>
                <text class="text-sm text-slate-500">{{ comparisonMode === 'horizontal' ? item.grade_average || '-' : item.average_rank || '-' }}</text>
                <text class="text-sm text-slate-500">{{ comparisonMode === 'horizontal' ? item.class_rank || '-' : item.class_standard || '-' }}</text>
              </view>
            </template>
            <view v-else class="flex flex-col items-center justify-center py-8">
              <wd-icon name="content" size="40px" color="#cbd5e1" />
              <text class="mt-2 text-xs text-slate-400">暂无对比数据</text>
            </view>
          </view>
        </view>

        <view class="overflow-hidden rounded-lg bg-white shadow-sm">
          <view class="flex items-center justify-between border-b border-slate-100 px-4 py-3">
            <view class="flex flex-shrink-0 items-center gap-2">
              <view class="h-4 w-1 rounded-full bg-purple-500" />
              <text class="text-base text-slate-800 font-bold">名次分析</text>
            </view>

            <view class="flex flex-grow items-center justify-end gap-2">
              <view class="w-24">
                <!-- 班级多选 -->
                <wd-select-picker
                  v-model="selectedClassIds"
                  class="classes-picker flex-grow"
                  :columns="classColumns"
                  :show-confirm="false"
                  @confirm="handleClassChange"
                />
              </view>
              <view
                class="rounded-full p-1.5 active:bg-slate-100"
                @tap="handleRankSettings"
              >
                <view class="i-mingcute:settings-3-line text-lg text-slate-400" />
              </view>
            </view>
          </view>

          <view class="p-2">
            <view class="grid grid-cols-4 mb-2 rounded-md bg-slate-50 py-2 text-center">
              <text class="text-xs text-slate-500">班级</text>
              <text class="text-xs text-slate-500">前{{ scoreSettings.rank_top_1 }}</text>
              <text class="text-xs text-slate-500">前{{ scoreSettings.rank_top_2 }}</text>
              <text class="text-xs text-slate-500">前{{ scoreSettings.rank_top_3 }}</text>
            </view>

            <template v-if="rankStatsData && rankStatsData.length > 0">
              <view
                v-for="(item, index) in rankStatsData"
                :key="index"
                class="grid grid-cols-4 items-center border-b border-slate-50 py-3 text-center last:border-none"
              >
                <view class="flex justify-center">
                  <text class="rounded bg-slate-100 px-1.5 py-0.5 text-xs text-slate-600">{{ item.name || '-' }}</text>
                </view>
                <text class="text-sm text-slate-700 font-medium">{{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_1)?.count || 0 }}</text>
                <text class="text-sm text-slate-700 font-medium">{{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_2)?.count || 0 }}</text>
                <text class="text-sm text-slate-700 font-medium">{{ item.rank_stats?.find(r => r.end === scoreSettings.rank_top_3)?.count || 0 }}</text>
              </view>
            </template>
            <view v-else class="flex flex-col items-center justify-center py-8">
              <wd-icon name="chart-bar" size="40px" color="#cbd5e1" />
              <text class="mt-2 text-xs text-slate-400">暂无名次数据</text>
            </view>
          </view>
        </view>

        <view class="overflow-hidden rounded-lg bg-white shadow-sm">
          <view class="flex flex-col border-b border-slate-100 px-4 py-3">
            <view class="mb-2 flex items-center justify-between">
              <view class="flex items-center gap-2">
                <view
                  class="h-4 w-1 rounded-full"
                  :class="keyStudentType === 'up' ? 'bg-emerald-500' : 'bg-rose-500'"
                />
                <text class="text-base text-slate-800 font-bold">重点关注</text>
              </view>

              <view class="flex rounded-lg bg-slate-100 p-0.5">
                <view
                  class="flex items-center gap-1 rounded-md px-3 py-1 text-xs transition-all"
                  :class="keyStudentType === 'up' ? 'bg-white text-emerald-600 shadow-sm' : 'text-slate-500'"
                  @tap="toggleKeyStudentType('up')"
                >
                  <view class="i-mingcute:arrow-up-line text-xs" />
                  进步
                </view>
                <view
                  class="flex items-center gap-1 rounded-md px-3 py-1 text-xs transition-all"
                  :class="keyStudentType === 'down' ? 'bg-white text-rose-600 shadow-sm' : 'text-slate-500'"
                  @tap="toggleKeyStudentType('down')"
                >
                  <view class="i-mingcute:arrow-down-line text-xs" />
                  退步
                </view>
              </view>
            </view>

            <view class="flex items-center justify-between rounded bg-slate-50 px-3 py-2">
              <text class="text-xs text-slate-500">显示排名前/后变化最大的学生</text>
              <view class="flex items-center gap-1">
                <text class="text-xs text-slate-500">显示</text>
                <input
                  v-model.number="keyStudentCount"
                  type="number"
                  class="h-6 w-8 border border-slate-200 rounded bg-white text-center text-xs"
                >
                <text class="text-xs text-slate-500">名</text>
              </view>
            </view>
          </view>

          <view class="p-2">
            <view class="grid grid-cols-3 mb-2 rounded-md bg-slate-50 py-2 text-center">
              <text class="text-xs text-slate-500">姓名</text>
              <text class="text-xs text-slate-500">本次排名</text>
              <text class="text-xs text-slate-500">变化幅度</text>
            </view>

            <template v-if="keyStudentsList && keyStudentsList.length > 0">
              <view
                v-for="(student, index) in keyStudentsList"
                :key="index"
                class="grid grid-cols-3 items-center border-b border-slate-50 py-3 text-center last:border-none"
              >
                <text class="text-sm text-slate-700 font-bold">{{ student.student_name || '-' }}</text>
                <text class="text-sm text-slate-500">{{ student.class_rank || '-' }}</text>
                <view class="flex items-center justify-center gap-0.5">
                  <view
                    class="i-mingcute:trend-arrow-up-line text-sm"
                    :class="keyStudentType === 'up' ? 'text-emerald-500' : 'text-rose-500 rotate-180'"
                  />
                  <text
                    class="font-din text-sm font-bold"
                    :class="keyStudentType === 'up' ? 'text-emerald-500' : 'text-rose-500'"
                  >
                    {{ Math.abs(student.class_diff_rank || 0) }}
                  </text>
                </view>
              </view>
            </template>
            <view v-else class="flex flex-col items-center justify-center py-8">
              <wd-icon name="user" size="40px" color="#cbd5e1" />
              <text class="mt-2 text-xs text-slate-400">暂无相关学生</text>
            </view>
          </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" scoped>
  /* 确保覆盖 Wot Design 的默认变量或增加自定义辅助类 */
:deep(.wd-drop-menu__item) {
  justify-content: center;
}

/* 字体优化：数字使用等宽字体更美观 */
.font-din {
  font-family: 'DIN Alternate', 'Roboto', sans-serif;
}

/* 针对小程序/App的样式穿透 */
:deep(.wd-tabs__nav) {
  background-color: transparent !important;
}

/* 按钮阴影 */
:deep(.wd-button) {
  box-shadow: 0 4px 6px -1px rgba(59, 130, 246, 0.2);
}

/* 解决 Picker 在 header 中的样式问题 */
:deep(.wd-picker__cell) {
  padding: 10px 0;
}
</style>
