<script setup lang="ts">
import type { StudentInfo } from '@/service/types'
import { useQuery } from '@tanstack/vue-query'
import { useDebounceFn, whenever } from '@vueuse/core'
import { computed, onMounted, ref } from 'vue'
import { teacherAnalysisExportStudentListUsingPost, teacherAnalysisStudentListUsingPost } from '@/service/laoshichengjifenxi'
import { useHomeStore } from '@/store/home'

const homeStore = useHomeStore()
const searchQuery = ref('')

// 检查是否可以加载学生数据
const canLoadStudents = computed(() => {
  return homeStore.selectedClassId && homeStore.selectedExamId && homeStore.selectedSubjectId && homeStore.selectedGradeKey
})

// 防抖搜索关键词
const debouncedSearchQuery = ref('')
const updateDebouncedSearch = useDebounceFn((value: string) => {
  debouncedSearchQuery.value = value
}, 300)

// 监听搜索关键词变化
whenever(() => searchQuery.value, (newValue) => {
  updateDebouncedSearch(newValue)
})

// 使用 TanStack Query 获取学生数据
const {
  data: studentsData,
  isLoading: loading,
  error,
  refetch,
} = useQuery({
  queryKey: computed(() => [
    'students',
    homeStore.selectedClassId,
    homeStore.selectedExamId,
    homeStore.selectedSubjectId,
    homeStore.selectedGradeKey,
    debouncedSearchQuery.value,
  ]),
  queryFn: async () => {
    const response = await teacherAnalysisStudentListUsingPost({
      body: {
        class_id: homeStore.selectedClassId!,
        exam_subject_id: homeStore.selectedSubjectId!,
        grade_id: homeStore.selectedGradeKey!,
        keyword: debouncedSearchQuery.value || undefined,
      },
    })
    const responseData = response as any
    return responseData.data || { attentioned_students: [], other_students: [] }
  },
  enabled: computed(() => !!canLoadStudents.value),
  staleTime: 30000, // 30秒内数据保持新鲜
  gcTime: 300000, // 5分钟后清理缓存
})

// 计算学生列表
const attentionedStudents = computed(() => studentsData.value?.attentioned_students || [])
const otherStudents = computed(() => studentsData.value?.other_students || [])

// 获取排名变化图标
function getRankChangeIcon(diff?: number) {
  if (!diff || diff === 0)
    return ''
  return diff > 0 ? 'i-fluent:arrow-up-20-filled' : 'i-fluent:arrow-down-20-filled'
}

// 获取排名变化颜色
function getRankChangeColor(diff?: number) {
  if (!diff || diff === 0)
    return 'text-gray-400'
  return diff > 0 ? 'text-red-500' : 'text-green-500'
}

// 跳转到学生详情
function goToStudentDetail(student: StudentInfo) {
  uni.navigateTo({
    url: `/pages/student/detail?id=${student.info_id}`,
  })
}

// 切换收藏状态
function toggleFavorite(student: StudentInfo) {
  uni.showToast({
    title: '功能开发中',
    icon: 'none',
  })
}

// 下载功能
async function handleDownload() {
  try {
    await teacherAnalysisExportStudentListUsingPost({
      body: {
        class_id: homeStore.selectedClassId!,
        exam_subject_id: homeStore.selectedSubjectId!,
        grade_id: homeStore.selectedGradeKey!,
      },
    })
  }
  catch (error) {
    console.error('下载学生数据失败:', error)
    uni.showToast({
      title: '下载失败',
      icon: 'error',
    })
  }
}

// 分享功能
function handleShare() {
  uni.showToast({
    title: '分享功能开发中',
    icon: 'none',
  })
}

// 处理搜索输入
function handleSearch() {
  // 搜索逻辑已通过 whenever 和防抖处理
}

// 处理查询错误
whenever(() => error.value, (err) => {
  if (err) {
    console.error('加载学生数据失败:', err)
    uni.showToast({
      title: '加载失败',
      icon: 'error',
    })
  }
})

onMounted(async () => {
  // 初始化选项数据
  if (homeStore.examOptions.length === 0) {
    await homeStore.fetchOptions()
  }
})
</script>

<template>
  <view class="min-h-screen bg-gray-50">
    <!-- 标题栏 -->
    <view class="relative flex items-center justify-between border-b border-gray-100 bg-white px-4 py-3">
      <view class="flex-1 text-center">
        <text class="text-lg text-gray-800 font-semibold">学生名单</text>
      </view>
      <view class="absolute right-4 flex items-center gap-3">
        <wd-button
          type="icon"
          size="small"
          @click="handleDownload"
        >
          <view class="i-fluent:arrow-download-20-regular text-lg" />
        </wd-button>
        <wd-button
          type="icon"
          size="small"
          @click="handleShare"
        >
          <view class="i-fluent:share-20-regular text-lg" />
        </wd-button>
      </view>
    </view>

    <!-- 选择器区域 -->
    <view class="border-b border-gray-100 bg-white px-4 py-3">
      <wd-drop-menu>
        <!-- 班级选择 -->
        <wd-drop-menu-item
          v-model="homeStore.selectedClassId"
          :options="homeStore.classOptions"
        />
        <!-- 考试选择 -->
        <wd-drop-menu-item
          v-model="homeStore.selectedExamId"
          :options="homeStore.examOptions"
        />
        <!-- 科目选择 -->
        <wd-drop-menu-item
          v-model="homeStore.selectedSubjectId"
          :options="homeStore.subjectOptions"
        />
      </wd-drop-menu>
    </view>

    <!-- 搜索框 -->
    <view class="border-b border-gray-100 bg-white px-4 py-3">
      <wd-search
        v-model="searchQuery"
        placeholder="请输入学生姓名"
        hide-cancel
        @input="handleSearch"
      />
    </view>

    <!-- 重点关注的学生 -->
    <view v-if="attentionedStudents.length > 0" class="mt-4">
      <view class="flex items-center px-4 py-2">
        <view class="i-fluent:star-20-filled mr-2 text-yellow-500" />
        <text class="text-sm text-gray-700 font-medium">重点关注的学生</text>
      </view>

      <wd-cell-group border custom-class="mx-4 rounded-lg overflow-hidden">
        <wd-cell
          v-for="(student, index) in attentionedStudents"
          :key="student.info_id"
          :is-link="true"
          @click="goToStudentDetail(student)"
        >
          <template #icon>
            <view class="mr-3 h-8 w-8 flex items-center justify-center rounded-full bg-red-100">
              <text class="text-sm text-red-600 font-semibold">{{ index + 1 }}</text>
            </view>
          </template>

          <template #title>
            <text class="text-base text-gray-800 font-medium">
              {{ student.student_name }}
            </text>
          </template>

          <template #value>
            <view class="flex items-center gap-3">
              <!-- 分数 -->
              <text class="text-base text-gray-800 font-semibold">
                {{ student.full_score || '--' }}分
              </text>

              <!-- 排名变化 -->
              <view class="flex items-center">
                <view
                  v-if="getRankChangeIcon(student.class_diff_rank)"
                  :class="[getRankChangeIcon(student.class_diff_rank), getRankChangeColor(student.class_diff_rank)]"
                  class="mr-1 h-4 w-4"
                />
                <text :class="getRankChangeColor(student.class_diff_rank)" class="text-sm">
                  {{ Math.abs(student.class_diff_rank || 0) }}名
                </text>
              </view>

              <!-- 收藏按钮 -->
              <wd-button
                type="icon"
                size="small"
                @click.stop="toggleFavorite(student)"
              >
                <view class="i-fluent:star-20-filled text-yellow-500" />
              </wd-button>
            </view>
          </template>
        </wd-cell>
      </wd-cell-group>
    </view>

    <!-- 学生列表 -->
    <view v-if="otherStudents.length > 0" class="mt-4">
      <view class="px-4 py-2">
        <text class="text-sm text-gray-700 font-medium">学生列表</text>
      </view>

      <wd-cell-group border custom-class="mx-4 rounded-lg overflow-hidden">
        <wd-cell
          v-for="(student, index) in otherStudents"
          :key="student.info_id"
          :is-link="true"
          @click="goToStudentDetail(student)"
        >
          <template #icon>
            <view class="mr-3 h-8 w-8 flex items-center justify-center rounded-full bg-gray-100">
              <text class="text-sm text-gray-600 font-semibold">
                {{ (attentionedStudents.length + index + 1) }}
              </text>
            </view>
          </template>

          <template #title>
            <text class="text-base text-gray-800 font-medium">
              {{ student.student_name }}
            </text>
          </template>

          <template #value>
            <view class="flex items-center gap-3">
              <!-- 分数 -->
              <text class="text-base text-gray-800 font-semibold">
                {{ student.full_score || '--' }}分
              </text>

              <!-- 排名变化 -->
              <view class="flex items-center">
                <view
                  v-if="getRankChangeIcon(student.class_diff_rank)"
                  :class="[getRankChangeIcon(student.class_diff_rank), getRankChangeColor(student.class_diff_rank)]"
                  class="mr-1 h-4 w-4"
                />
                <text :class="getRankChangeColor(student.class_diff_rank)" class="text-sm">
                  {{ Math.abs(student.class_diff_rank || 0) }}名
                </text>
              </view>

              <!-- 收藏按钮 -->
              <wd-button
                type="icon"
                size="small"
                @click.stop="toggleFavorite(student)"
              >
                <view class="i-fluent:star-20-regular text-gray-400" />
              </wd-button>
            </view>
          </template>
        </wd-cell>
      </wd-cell-group>
    </view>

    <!-- 空状态 -->
    <wd-status-tip
      v-if="!loading && !canLoadStudents"
      image="search"
      tip="请选择班级、考试和科目"
    />

    <wd-status-tip
      v-else-if="!loading && canLoadStudents && attentionedStudents.length === 0 && otherStudents.length === 0"
      image="search"
      tip="暂无学生数据"
    />

    <!-- 加载状态 -->
    <view v-if="loading" class="flex items-center justify-center py-20">
      <wd-loading />
      <text class="ml-2 text-gray-500">加载中...</text>
    </view>
  </view>
</template>

<route lang="jsonc" type="home">
    {
      "layout": "tabbar",
      "style": {
        // 'custom' 表示开启自定义导航栏，默认 'default'
        "navigationStyle": "custom",
        "navigationBarTitleText": "学生名单"
      }
    }
</route>
