<script lang="ts" setup>
import type { ClassAiHomeworkDataItem } from '#/api/service/school/school-board'

import { useRoute } from 'vue-router'

import { getClassOverview } from '#/api/service/school/school-board'
import { formatNumber, formatMinutes } from '#/utils/format'
import hud from '#/utils/hud'
import { router } from '#/router'

import DateFilter from './components/DateFilter.vue'

const route = useRoute()

const gradeId = ref(String(route.query.gradeId ?? ''))
const gradeName = ref(String(route.query.gradeName ?? ''))
const startTime = ref(String(route.query.startTime ?? ''))
const endTime = ref(String(route.query.endTime ?? ''))
const classList = ref<ClassAiHomeworkDataItem[]>([])

function toPercent(rate: number) {
  return +(rate * 100).toFixed(2)
}

async function fetchData() {
  if (!gradeId.value) {
    hud.warning('缺少年级参数')
    return
  }
  hud.load({
    task: async () => {
      const params: Record<string, string> = { gradeId: gradeId.value }
      if (startTime.value) params.startTime = `${startTime.value} 00:00:00`
      if (endTime.value) params.endTime = `${endTime.value} 23:59:59`
      classList.value = await getClassOverview(params)
    },
  })
}

function goBack() {
  router.back()
}

const classColors = [
  '#3B82F6',
  '#059669',
  '#7C3AED',
  '#DB2777',
  '#EA580C',
  '#0891B2',
  '#1E40AF',
  '#CA8A04',
]

function getColor(idx: number) {
  return classColors[idx % classColors.length]!
}

function goToSubject(cls: ClassAiHomeworkDataItem) {
  router.push({
    path: '/dashboard/analytics/subject-dashboard',
    query: {
      gradeId: gradeId.value,
      gradeName: gradeName.value,
      classId: cls.classId,
      className: cls.className,
      startTime: startTime.value,
      endTime: endTime.value,
    },
  })
}

onMounted(fetchData)
</script>

<template>
  <div class="p-5">
    <div class="mb-4 flex items-center gap-3">
      <button
        class="flex h-8 w-8 items-center justify-center rounded-lg border border-gray-200 text-gray-500 transition-colors hover:bg-gray-50"
        @click="goBack"
      >
        <svg
          width="18"
          height="18"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
        >
          <path d="M15 18l-6-6 6-6" />
        </svg>
      </button>
      <h2 class="text-base font-bold text-gray-900">
        {{ gradeName }} · 班级看板
      </h2>
    </div>

    <div class="mb-5 rounded-xl border border-gray-200 bg-white p-4 shadow-sm">
      <DateFilter
        v-model:start-time="startTime"
        v-model:end-time="endTime"
        @search="fetchData"
      />
    </div>

    <div
      v-if="classList.length"
      class="grid gap-5 md:grid-cols-2 xl:grid-cols-3"
    >
      <div
        v-for="(cls, idx) in classList"
        :key="cls.classId"
        class="rounded-xl border border-gray-200 bg-white shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md"
      >
        <div
          class="flex items-center justify-between rounded-t-xl px-5 py-4"
          :style="{
            background: `linear-gradient(135deg, ${getColor(idx)}12, ${getColor(idx)}06)`,
          }"
        >
          <div class="flex items-center gap-3">
            <div
              class="flex h-9 w-9 items-center justify-center rounded-lg text-sm font-bold text-white"
              :style="{ backgroundColor: getColor(idx) }"
            >
              {{ cls.className?.replace(/[^0-9]/g, '') || 'C' }}
            </div>
            <div>
              <h3 class="text-[15px] font-semibold text-gray-900">
                {{ cls.className }}
              </h3>
              <p class="text-xs text-gray-400">
                AI批改 {{ formatNumber(cls.aiCorrectedTitleCount) }} 题 · 节省
                {{ formatMinutes(cls.teacherTimeSavedMinutes) }}
              </p>
            </div>
          </div>
          <button
            class="inline-flex items-center gap-1 rounded-md border border-purple-200 bg-purple-50 px-2.5 py-1 text-xs text-purple-600 transition-colors hover:bg-purple-100"
            @click="goToSubject(cls)"
          >
            <svg
              width="12"
              height="12"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
            >
              <path
                d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"
              />
            </svg>
            查看学科
          </button>
        </div>

        <div class="px-5 py-4">
          <div class="mb-3 grid grid-cols-3 gap-2">
            <div class="text-center">
              <div class="text-xl font-bold text-gray-900">
                {{ formatNumber(cls.assignedHomeworkCount) }}
              </div>
              <div class="text-[11px] text-gray-400">布置</div>
            </div>
            <div class="text-center">
              <div class="text-xl font-bold text-gray-900">
                {{ formatNumber(cls.submittedHomeworkCount) }}
              </div>
              <div class="text-[11px] text-gray-400">提交</div>
            </div>
            <div class="text-center">
              <div class="text-xl font-bold text-gray-900">
                {{ formatNumber(cls.unsubmittedHomeworkCount) }}
              </div>
              <div class="text-[11px] text-gray-400">未提交</div>
            </div>
          </div>

          <div class="mb-3">
            <div class="mb-1 flex items-center justify-between text-xs">
              <span class="text-gray-500">完成率</span>
              <span
                class="font-semibold"
                :class="
                  toPercent(cls.completionRate) >= 80
                    ? 'text-green-600'
                    : toPercent(cls.completionRate) >= 50
                      ? 'text-amber-600'
                      : 'text-red-500'
                "
              >
                {{ toPercent(cls.completionRate) }}%
              </span>
            </div>
            <div class="h-2 overflow-hidden rounded-full bg-gray-100">
              <div
                class="h-full rounded-full transition-all duration-700"
                :style="{
                  width: `${Math.min(toPercent(cls.completionRate), 100)}%`,
                  backgroundColor: getColor(idx),
                }"
              />
            </div>
          </div>

          <div class="grid grid-cols-4 gap-1.5">
            <div class="rounded-md bg-blue-50 px-2 py-1.5 text-center">
              <div class="text-sm font-semibold text-blue-700">
                {{ toPercent(cls.excellentRate) }}%
              </div>
              <div class="text-[10px] text-blue-400">优秀</div>
            </div>
            <div class="rounded-md bg-sky-50 px-2 py-1.5 text-center">
              <div class="text-sm font-semibold text-sky-700">
                {{ toPercent(cls.goodRate) }}%
              </div>
              <div class="text-[10px] text-sky-400">良好</div>
            </div>
            <div class="rounded-md bg-cyan-50 px-2 py-1.5 text-center">
              <div class="text-sm font-semibold text-cyan-700">
                {{ toPercent(cls.passRate) }}%
              </div>
              <div class="text-[10px] text-cyan-400">合格</div>
            </div>
            <div class="rounded-md bg-red-50 px-2 py-1.5 text-center">
              <div class="text-sm font-semibold text-red-600">
                {{ toPercent(cls.unqualifiedRate) }}%
              </div>
              <div class="text-[10px] text-red-400">不及格</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="py-20 text-center">
      <p class="text-gray-500">暂无数据，请调整筛选条件后重试</p>
    </div>
  </div>
</template>
