<script setup lang="ts">
import type {
  ClassHomeworkResult,
  ClassItem,
  StudentHomework,
  SubjectItem,
} from '#/api/service/org/teacher-kanban'

import {
  CircleCheck,
  DataAnalysis,
  Document,
  Refresh,
  Search,
  User,
  Warning,
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'

import {
  getClassHomeworkList,
  getClassListByTeacher,
  getSubjectsByClassId,
} from '#/api/service/org/teacher-kanban'

const loading = ref(false)
const classList = ref<ClassItem[]>([])
const subjectList = ref<SubjectItem[]>([])
const selectedClassId = ref('')
const selectedSubjectIds = ref<string[]>([])
const dateRange = ref<[string, string] | undefined>(undefined)
const result = ref<ClassHomeworkResult | null>(null)

const activeShortcut = ref('')
const shortcuts = [
  {
    key: 'today',
    text: '今天',
    action: () => {
      const d = dayjs().format('YYYY-MM-DD')
      dateRange.value = [`${d} 00:00:00`, `${d} 23:59:59`]
    },
  },
  {
    key: '7d',
    text: '近7天',
    action: () => {
      dateRange.value = [
        `${dayjs().subtract(6, 'day').format('YYYY-MM-DD')} 00:00:00`,
        `${dayjs().format('YYYY-MM-DD')} 23:59:59`,
      ]
    },
  },
  {
    key: '30d',
    text: '近30天',
    action: () => {
      dateRange.value = [
        `${dayjs().subtract(29, 'day').format('YYYY-MM-DD')} 00:00:00`,
        `${dayjs().format('YYYY-MM-DD')} 23:59:59`,
      ]
    },
  },
  {
    key: 'semester',
    text: '本学期',
    action: () => {
      const m = dayjs().month()
      const start = (m >= 1 && m <= 6 ? dayjs().month(1) : dayjs().month(7))
        .startOf('month')
        .format('YYYY-MM-DD')
      dateRange.value = [
        `${start} 00:00:00`,
        `${dayjs().format('YYYY-MM-DD')} 23:59:59`,
      ]
    },
  },
]

function applyShortcut(s: (typeof shortcuts)[0]) {
  activeShortcut.value = s.key
  s.action()
}

const displaySubjects = computed(() => {
  if (!result.value?.subjects?.length) return []
  return result.value.subjects
})

const summaryStats = computed(() => {
  const students = result.value?.studentList || []
  const total = students.reduce((sum, s) => sum + (s.totalCount || 0), 0)
  const completed = students.reduce(
    (sum, s) => sum + (s.completedCount || 0),
    0,
  )
  const uncompleted = students.reduce(
    (sum, s) => sum + (s.uncompletedCount || 0),
    0,
  )
  const rate = total > 0 ? ((completed / total) * 100).toFixed(1) : '0.0'
  return {
    studentCount: students.length,
    totalHomework: total,
    completedHomework: completed,
    uncompletedHomework: uncompleted,
    completionRate: rate,
  }
})

function getSubjectStat(student: StudentHomework, subjectId: any) {
  return student.subjectStats?.find(
    (s) => String(s.subjectId) === String(subjectId),
  )
}

function completionRate(completed: number, total: number) {
  if (!total) return '-'
  return `${((completed / total) * 100).toFixed(1)}%`
}

function completionPercent(completed: number, total: number) {
  if (!total) return 0
  return Math.round((completed / total) * 100)
}

function rateClass(completed: number, total: number) {
  if (!total) return ''
  const rate = completed / total
  if (rate >= 0.9) return 'rate-excellent'
  if (rate >= 0.6) return 'rate-good'
  return 'rate-warn'
}

function rateBarColor(completed: number, total: number) {
  if (!total) return '#dcdfe6'
  const rate = completed / total
  if (rate >= 0.9) return '#2cc8a0'
  if (rate >= 0.6) return '#ffa200'
  return '#ff584e'
}

async function loadClasses() {
  classList.value = await getClassListByTeacher()
  if (classList.value.length > 0 && !selectedClassId.value) {
    selectedClassId.value = classList.value[0]!.id
  }
}

async function loadSubjects() {
  if (!selectedClassId.value) {
    subjectList.value = []
    return
  }
  subjectList.value = await getSubjectsByClassId(selectedClassId.value)
}

async function search() {
  if (!selectedClassId.value) return
  loading.value = true
  try {
    const params: any = { classId: selectedClassId.value }
    if (dateRange.value?.[0]) params.startTime = dateRange.value[0]
    if (dateRange.value?.[1]) params.endTime = dateRange.value[1]
    if (selectedSubjectIds.value.length > 0) {
      params.subjectIds = selectedSubjectIds.value
    }
    result.value = await getClassHomeworkList(params)
  } finally {
    loading.value = false
  }
}

function handleReset() {
  selectedSubjectIds.value = []
  dateRange.value = undefined
  activeShortcut.value = ''
  search()
}

function onClassChange() {
  selectedSubjectIds.value = []
  result.value = null
  loadSubjects()
  search()
}

watch(() => selectedClassId.value, onClassChange)

onMounted(async () => {
  await loadClasses()
  if (selectedClassId.value) {
    await loadSubjects()
    await search()
  }
})
</script>

<template>
  <div class="teacher-kanban">
    <!-- 筛选区域 -->
    <div class="filter-card">
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-label">班级</span>
          <el-select
            v-model="selectedClassId"
            placeholder="请选择班级"
            style="width: 200px"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name || ''"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="filter-item">
          <span class="filter-label">学科</span>
          <el-select
            v-model="selectedSubjectIds"
            placeholder="全部学科"
            multiple
            collapse-tags
            collapse-tags-tooltip
            clearable
            style="width: 280px"
          >
            <el-option
              v-for="item in subjectList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
      </div>
      <div class="filter-row">
        <div class="filter-item">
          <span class="filter-label">时间</span>
          <div class="shortcut-btns">
            <button
              v-for="s in shortcuts"
              :key="s.key"
              type="button"
              class="shortcut-btn"
              :class="{ active: activeShortcut === s.key }"
              @click="applyShortcut(s)"
            >
              {{ s.text }}
            </button>
          </div>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[
              new Date(2000, 0, 1, 0, 0, 0),
              new Date(2000, 0, 1, 23, 59, 59),
            ]"
            style="width: 380px"
            clearable
            @change="activeShortcut = ''"
          />
        </div>
        <div class="filter-actions">
          <el-button type="primary" @click="search">
            <el-icon style="margin-right: 4px"><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon style="margin-right: 4px"><Refresh /></el-icon>
            重置
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div v-if="result?.className" class="stats-row">
      <div class="stat-card stat-card--primary">
        <div class="stat-card__icon">
          <el-icon :size="28"><User /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">
            {{ summaryStats.studentCount }}
          </div>
          <div class="stat-card__label">学生总数</div>
        </div>
      </div>
      <div class="stat-card stat-card--info">
        <div class="stat-card__icon">
          <el-icon :size="28"><Document /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">
            {{ summaryStats.totalHomework }}
          </div>
          <div class="stat-card__label">作业总数</div>
        </div>
      </div>
      <div class="stat-card stat-card--success">
        <div class="stat-card__icon">
          <el-icon :size="28"><CircleCheck /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">{{ summaryStats.completionRate }}%</div>
          <div class="stat-card__label">整体完成率</div>
        </div>
        <div class="stat-card__bar">
          <div
            class="stat-card__bar-fill stat-card__bar-fill--success"
            :style="{ width: `${summaryStats.completionRate}%` }"
          ></div>
        </div>
      </div>
      <div class="stat-card stat-card--danger">
        <div class="stat-card__icon">
          <el-icon :size="28"><Warning /></el-icon>
        </div>
        <div class="stat-card__content">
          <div class="stat-card__value">
            {{ summaryStats.uncompletedHomework }}
          </div>
          <div class="stat-card__label">未完成总数</div>
        </div>
      </div>
    </div>

    <!-- 班级信息 + 表格 -->
    <div class="main-card">
      <div v-if="result?.className" class="main-card__header">
        <div class="class-badge">
          {{ result.className?.replace(/[^0-9]/g, '') || 'C' }}
        </div>
        <div class="class-meta">
          <span class="class-name">{{ result.className }}</span>
          <span class="student-count">
            共 {{ result.studentList?.length || 0 }} 名学生 ·
            {{ displaySubjects.length }} 个学科
          </span>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-wrap">
        <el-table
          v-if="result?.studentList && result.studentList.length > 0"
          v-loading="loading"
          :data="result.studentList"
          :fit="true"
          border
          stripe
          style="width: 100%"
          :header-cell-style="{
            background: '#f8fafc',
            color: '#1e293b',
            fontWeight: 600,
            fontSize: '13px',
          }"
          :cell-style="{ fontSize: '13px' }"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
            align="center"
            fixed="left"
          />
          <el-table-column
            prop="userName"
            label="姓名"
            min-width="120"
            align="center"
            fixed="left"
          >
            <template #default="{ row }">
              <span class="student-name">{{ row.userName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="总计" align="center">
            <el-table-column
              prop="totalCount"
              label="作业数"
              min-width="100"
              align="center"
            />
            <el-table-column
              prop="completedCount"
              label="已完成"
              min-width="100"
              align="center"
            >
              <template #default="{ row }">
                <span class="text-success">{{ row.completedCount }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="uncompletedCount"
              label="未完成"
              min-width="100"
              align="center"
            >
              <template #default="{ row }">
                <span :class="row.uncompletedCount > 0 ? 'text-danger' : ''">
                  {{ row.uncompletedCount }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="完成率" min-width="160" align="center">
              <template #default="{ row }">
                <div v-if="row.totalCount" class="rate-cell">
                  <div class="rate-bar">
                    <div
                      class="rate-bar__fill"
                      :style="{
                        width: `${completionPercent(row.completedCount, row.totalCount)}%`,
                        backgroundColor: rateBarColor(
                          row.completedCount,
                          row.totalCount,
                        ),
                      }"
                    ></div>
                  </div>
                  <span
                    :class="rateClass(row.completedCount, row.totalCount)"
                    class="rate-text"
                  >
                    {{ completionRate(row.completedCount, row.totalCount) }}
                  </span>
                </div>
                <span v-else class="rate-text--empty">-</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column
            v-for="subject in displaySubjects"
            :key="subject.id"
            :label="subject.name"
            align="center"
          >
            <el-table-column label="作业数" min-width="100" align="center">
              <template #default="{ row }">
                {{ getSubjectStat(row, subject.id)?.homeworkCount ?? '-' }}
              </template>
            </el-table-column>
            <el-table-column label="已完成" min-width="100" align="center">
              <template #default="{ row }">
                <span class="text-success">
                  {{ getSubjectStat(row, subject.id)?.completedCount ?? '-' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="未完成" min-width="100" align="center">
              <template #default="{ row }">
                <span
                  :class="
                    (getSubjectStat(row, subject.id)?.uncompletedCount ?? 0) > 0
                      ? 'text-danger'
                      : ''
                  "
                >
                  {{ getSubjectStat(row, subject.id)?.uncompletedCount ?? '-' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="完成率" min-width="160" align="center">
              <template #default="{ row }">
                <div v-if="getSubjectStat(row, subject.id)" class="rate-cell">
                  <div class="rate-bar">
                    <div
                      class="rate-bar__fill"
                      :style="{
                        width: `${completionPercent(
                          getSubjectStat(row, subject.id)?.completedCount ?? 0,
                          getSubjectStat(row, subject.id)?.homeworkCount ?? 0,
                        )}%`,
                        backgroundColor: rateBarColor(
                          getSubjectStat(row, subject.id)?.completedCount ?? 0,
                          getSubjectStat(row, subject.id)?.homeworkCount ?? 0,
                        ),
                      }"
                    ></div>
                  </div>
                  <span
                    :class="
                      rateClass(
                        getSubjectStat(row, subject.id)?.completedCount ?? 0,
                        getSubjectStat(row, subject.id)?.homeworkCount ?? 0,
                      )
                    "
                    class="rate-text"
                  >
                    {{
                      completionRate(
                        getSubjectStat(row, subject.id)?.completedCount ?? 0,
                        getSubjectStat(row, subject.id)?.homeworkCount ?? 0,
                      )
                    }}
                  </span>
                </div>
                <span v-else class="rate-text--empty">-</span>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>

        <div
          v-if="loading && !result?.studentList?.length"
          v-loading="true"
          class="empty-state"
          element-loading-text="加载中..."
        ></div>

        <!-- 空状态 -->
        <div
          v-if="
            !loading &&
            (!result?.studentList || result.studentList.length === 0)
          "
          class="empty-state"
        >
          <div class="empty-state__icon-wrap">
            <el-icon :size="56"><DataAnalysis /></el-icon>
          </div>
          <p class="empty-state__text">暂无作业数据</p>
          <p class="empty-state__hint">请选择班级并设置查询条件后点击查询</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.teacher-kanban {
  min-height: 100%;
  padding: 20px;
  background-color: #f7f7f7;
}

// ── 筛选区域 ──
.filter-card {
  position: relative;
  padding: 20px 24px;
  margin-bottom: 20px;
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow:
    0 1px 3px rgb(0 0 0 / 5%),
    0 1px 2px rgb(0 0 0 / 3%);

  &::before {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 3px;
    content: '';
    background: linear-gradient(90deg, #4f87f5, #2cc8a0);
  }
}

.filter-row {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;

  & + & {
    margin-top: 14px;
  }
}

.filter-item {
  display: flex;
  gap: 10px;
  align-items: center;
}

.filter-label {
  min-width: 36px;
  font-size: 14px;
  font-weight: 500;
  color: #475569;
  white-space: nowrap;
}

.filter-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.shortcut-btns {
  display: flex;
  gap: 6px;
  margin-right: 8px;
}

.shortcut-btn {
  padding: 5px 14px;
  font-size: 13px;
  color: #64748b;
  cursor: pointer;
  background: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  transition: all 0.2s ease;

  &:hover {
    color: #4f87f5;
    background: #f6f9ff;
    border-color: #a8c4f5;
  }

  &.active {
    color: #fff;
    background: linear-gradient(135deg, #4f87f5, #3a6fd8);
    border-color: transparent;
    box-shadow: 0 2px 8px rgb(79 135 245 / 30%);
  }
}

// ── 统计卡片 ──
.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 20px 24px;
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow:
    0 1px 3px rgb(0 0 0 / 5%),
    0 1px 2px rgb(0 0 0 / 3%);
  transition: all 0.25s ease;

  &:hover {
    box-shadow: 0 4px 12px rgb(0 0 0 / 8%);
    transform: translateY(-2px);
  }

  &__icon {
    display: flex;
    flex-shrink: 0;
    align-items: center;
    justify-content: center;
    width: 52px;
    height: 52px;
    border-radius: 12px;
  }

  &__content {
    flex: 1;
    min-width: 0;
  }

  &__value {
    font-size: 28px;
    font-weight: 700;
    line-height: 1.2;
    letter-spacing: -0.02em;
  }

  &__label {
    margin-top: 4px;
    font-size: 13px;
    color: #94a3b8;
  }

  &__bar {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 3px;
    background: #f1f5f9;
  }

  &__bar-fill {
    height: 100%;
    border-radius: 0 3px 0 0;
    transition: width 0.6s ease;

    &--success {
      background: linear-gradient(90deg, #2cc8a0, #5dddb8);
    }
  }

  &--primary {
    .stat-card__icon {
      color: #4f87f5;
      background: linear-gradient(135deg, #f0f5ff, #dce8fd);
    }

    .stat-card__value {
      color: #4f87f5;
    }
  }

  &--info {
    .stat-card__icon {
      color: #909399;
      background: linear-gradient(135deg, #f8fafc, #f1f5f9);
    }

    .stat-card__value {
      color: #334155;
    }
  }

  &--success {
    .stat-card__icon {
      color: #2cc8a0;
      background: linear-gradient(135deg, #edfcf7, #d4f5ea);
    }

    .stat-card__value {
      color: #2cc8a0;
    }
  }

  &--danger {
    .stat-card__icon {
      color: #ff584e;
      background: linear-gradient(135deg, #fff2f1, #ffe2e0);
    }

    .stat-card__value {
      color: #ff584e;
    }
  }
}

// ── 主体卡片 ──
.main-card {
  overflow: hidden;
  background: #fff;
  border-radius: 12px;
  box-shadow:
    0 1px 3px rgb(0 0 0 / 5%),
    0 1px 2px rgb(0 0 0 / 3%);

  &__header {
    display: flex;
    gap: 14px;
    align-items: center;
    padding: 18px 24px;
    background: linear-gradient(135deg, #f8fafc 0%, #eef2ff 100%);
    border-bottom: 1px solid #e2e8f0;
  }
}

.class-badge {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  font-size: 16px;
  font-weight: 700;
  color: #fff;
  background: linear-gradient(135deg, #4f87f5, #3a6fd8);
  border-radius: 10px;
  box-shadow: 0 2px 8px rgb(79 135 245 / 25%);
}

.class-meta {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.class-name {
  font-size: 17px;
  font-weight: 700;
  color: #1e293b;
}

.student-count {
  font-size: 13px;
  color: #94a3b8;
}

// ── 表格区域 ──
.table-wrap {
  padding: 20px;
}

// ── 空状态 ──
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 320px;
  padding: 60px 20px;

  &__icon-wrap {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 88px;
    height: 88px;
    color: #c0c4cc;
    background: linear-gradient(135deg, #f8fafc, #eef2ff);
    border-radius: 50%;
  }

  &__text {
    margin-top: 20px;
    font-size: 16px;
    font-weight: 600;
    color: #535353;
  }

  &__hint {
    margin-top: 8px;
    font-size: 13px;
    color: #aaa;
  }
}

// ── 表格样式 ──
:deep(.el-table) {
  overflow: hidden;
  border-radius: 8px;

  th.el-table__cell {
    border-bottom: 2px solid #e2e8f0;
  }

  .el-table__row:hover > td {
    background-color: #f6f9ff !important;
  }

  .student-name {
    font-weight: 600;
    color: #1a1a1a;
  }

  .text-success {
    font-weight: 600;
    color: #2cc8a0;
  }

  .text-danger {
    font-weight: 600;
    color: #ff584e;
  }

  .rate-cell {
    display: flex;
    gap: 8px;
    align-items: center;
  }

  .rate-bar {
    flex: 1;
    min-width: 40px;
    height: 6px;
    overflow: hidden;
    background: #f1f5f9;
    border-radius: 3px;
  }

  .rate-bar__fill {
    height: 100%;
    border-radius: 3px;
    transition: width 0.4s ease;
  }

  .rate-text {
    font-size: 12px;
    font-weight: 600;
    white-space: nowrap;
  }

  .rate-text--empty {
    color: #aaa;
  }

  .rate-excellent {
    color: #2cc8a0;
  }

  .rate-good {
    color: #ffa200;
  }

  .rate-warn {
    color: #ff584e;
  }
}
</style>
