<script setup lang="ts">
import type {
  ClassMonitorSessionDetail,
  ClassMonitorSessionDetailStudent,
  ClassMonitorSnapshot,
  ClassMonitorStudentSnapshot,
} from '../../../api/service/org/classroom-monitor'

import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { classroomMonitorService } from '../../../api/service/org/classroom-monitor'
import hud from '../../../utils/hud'

const route = useRoute()
const router = useRouter()

const detailLoading = ref(false)
const studentSnapshotLoading = ref(false)
const snapshots = ref<ClassMonitorSnapshot[]>([])
const selectedSnapshotStudent = ref<ClassMonitorSnapshot>()
const studentSnapshots = ref<ClassMonitorStudentSnapshot[]>([])
const studentSnapshotDialogVisible = ref(false)
const sessionMeta = ref<ClassMonitorSessionDetail | null>(null)

const sessionId = computed(() => String(route.params.sessionId || ''))
const classId = computed(() => {
  const q = route.query.classId
  if (typeof q === 'string' && q) return q
  if (Array.isArray(q) && q[0]) return String(q[0])
  return ''
})
const classDisplayName = computed(() => {
  const q = route.query.className
  if (typeof q === 'string' && q) return q
  const fromApi = sessionMeta.value?.className
  return typeof fromApi === 'string' && fromApi ? fromApi : ''
})

const studentSnapshotPreviewList = computed(() => {
  return studentSnapshots.value.map((item) => item.url).filter(Boolean)
})

watch(
  () => [sessionId.value, classId.value] as const,
  ([id]) => {
    if (id) loadSessionDetail()
  },
  { immediate: true },
)

function isValidSessionStudent(
  row: unknown,
): row is ClassMonitorSessionDetailStudent {
  if (row == null || typeof row !== 'object') return false
  const r = row as ClassMonitorSessionDetailStudent
  return r.studentId != null && r.studentId !== ''
}

function mapSessionStudentToSnapshot(
  s: ClassMonitorSessionDetailStudent,
): ClassMonitorSnapshot {
  return {
    avatar: s.avatar ?? '',
    latestTs: s.latestTs,
    latestUrl: s.latestUrl ?? '',
    staleSeconds: s.staleSeconds ?? 0,
    studentId: s.studentId,
    studentName: s.studentName ?? '',
  }
}

async function loadSessionDetail() {
  const sid = sessionId.value
  if (!sid) return
  detailLoading.value = true
  try {
    const cid = classId.value
    const detail = await classroomMonitorService.getSessionDetail(
      sid,
      cid || undefined,
    )
    sessionMeta.value = detail ?? null
    const students = detail?.students ?? []
    snapshots.value = students
      .filter(isValidSessionStudent)
      .map(mapSessionStudentToSnapshot)
  } finally {
    detailLoading.value = false
  }
}

async function openStudentSnapshots(item: ClassMonitorSnapshot) {
  const sid = sessionId.value
  if (!sid) {
    hud.error('暂无会话')
    return
  }
  if (item?.studentId == null || item.studentId === '') {
    hud.error('学生信息不完整')
    return
  }
  selectedSnapshotStudent.value = item
  studentSnapshots.value = []
  studentSnapshotDialogVisible.value = true
  studentSnapshotLoading.value = true
  try {
    studentSnapshots.value = await classroomMonitorService.getStudentSnapshots(
      sid,
      item.studentId,
    )
  } finally {
    studentSnapshotLoading.value = false
  }
}

function formatTime(time?: number | string) {
  if (!time) return '-'
  const timestamp = Number(time)
  if (Number.isNaN(timestamp)) return String(time)
  const date = new Date(String(timestamp).length === 10 ? timestamp * 1000 : timestamp)
  if (Number.isNaN(date.getTime())) return String(time)
  return date.toLocaleString()
}
</script>

<template>
  <div class="classroom-monitor-session g-container">
    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-header">
          <div>
            <div class="page-title">
              {{ classDisplayName ? `${classDisplayName} · ` : '' }}历史会话
            </div>
            <div class="page-desc">
              会话 ID：{{ sessionId || '-' }}
            </div>
          </div>
          <div class="header-actions">
            <el-button @click="router.back()">返回</el-button>
            <el-button :loading="detailLoading" type="primary" @click="loadSessionDetail()">
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div v-loading="detailLoading" class="snapshot-section">
        <div class="snapshot-header">
          <div class="section-title">学生监控信息</div>
        </div>

        <div class="snapshot-grid">
          <el-card
            v-for="(item, idx) in snapshots"
            :key="`${item.studentId}-${idx}`"
            class="snapshot-card"
            shadow="hover"
            @click="openStudentSnapshots(item)"
          >
            <el-image
              v-if="item.latestUrl"
              class="snapshot-image"
              fit="cover"
              :src="item.latestUrl"
            />
            <div v-else class="snapshot-empty">暂无截图</div>

            <div class="student-info">
              <el-avatar :size="36" :src="item.avatar">
                {{ item.studentName?.slice(0, 1) || '学' }}
              </el-avatar>
              <div>
                <div class="student-name">{{ item.studentName || '-' }}</div>
                <div class="student-meta">
                  最新时间：{{ formatTime(item.latestTs) }}
                </div>
                <div class="student-meta">
                  延迟：{{ item.staleSeconds ?? 0 }}秒
                </div>
              </div>
            </div>
          </el-card>

          <el-empty
            v-if="!detailLoading && snapshots.length === 0"
            description="暂无学生监控信息"
          />
        </div>
      </div>
    </el-card>

    <el-dialog
      v-model="studentSnapshotDialogVisible"
      :title="`${selectedSnapshotStudent?.studentName || '-'}的全部截图`"
      width="900px"
      align-center
      destroy-on-close
    >
      <div v-loading="studentSnapshotLoading" class="student-snapshot-dialog">
        <div class="student-snapshot-summary">
          <el-avatar :size="40" :src="selectedSnapshotStudent?.avatar">
            {{ selectedSnapshotStudent?.studentName?.slice(0, 1) || '学' }}
          </el-avatar>
          <div>
            <div class="student-name">
              {{ selectedSnapshotStudent?.studentName || '-' }}
            </div>
            <div class="student-meta">
              共 {{ studentSnapshots.length }} 张截图
            </div>
          </div>
        </div>

        <div v-if="studentSnapshots.length" class="student-snapshot-list">
          <div
            v-for="item in studentSnapshots"
            :key="`${item.ts}-${item.url}`"
            class="student-snapshot-item"
          >
            <el-image
              class="student-snapshot-image"
              fit="cover"
              :preview-src-list="studentSnapshotPreviewList"
              :src="item.url"
            />
            <div class="student-meta">
              截图时间：{{ formatTime(item.ts) }}
            </div>
          </div>
        </div>

        <el-empty
          v-else-if="!studentSnapshotLoading"
          description="暂无截图"
        />
      </div>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.classroom-monitor-session {
  .content-card {
    min-height: 360px;
    border: 1px solid #edf0f5;
  }

  .card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 16px;
  }

  .page-title {
    color: #1f2937;
    font-size: 20px;
    font-weight: 600;
  }

  .page-desc {
    margin-top: 6px;
    color: #6b7280;
    font-size: 14px;
  }

  .header-actions {
    display: flex;
    gap: 12px;
  }

  .snapshot-section {
    min-height: 260px;
  }

  .snapshot-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
  }

  .section-title {
    color: #111827;
    font-size: 16px;
    font-weight: 600;
  }

  .snapshot-grid {
    display: grid;
    min-height: 220px;
    grid-template-columns: repeat(4, minmax(0, 1fr));
    gap: 16px;
  }

  .snapshot-card {
    cursor: pointer;
    overflow: hidden;
    transition:
      border-color 0.2s,
      box-shadow 0.2s;

    &:hover {
      border-color: #409eff;
    }
  }

  .snapshot-image,
  .snapshot-empty {
    width: 100%;
    height: 180px;
    border-radius: 8px;
  }

  .snapshot-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #9ca3af;
    background: #f3f4f6;
  }

  .student-info {
    display: flex;
    gap: 10px;
    margin-top: 12px;
  }

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

  .student-meta {
    margin-top: 4px;
    color: #6b7280;
    font-size: 12px;
  }

  .student-snapshot-dialog {
    min-height: 240px;
  }

  .student-snapshot-summary {
    display: flex;
    align-items: center;
    gap: 12px;
    padding-bottom: 16px;
    margin-bottom: 16px;
    border-bottom: 1px solid #edf0f5;
  }

  .student-snapshot-list {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 16px;
    max-height: 620px;
    overflow-y: auto;
  }

  .student-snapshot-item {
    padding: 12px;
    border: 1px solid #edf0f5;
    border-radius: 8px;
  }

  .student-snapshot-image {
    width: 100%;
    height: 180px;
    border-radius: 8px;
  }
}

@media (max-width: 1400px) {
  .classroom-monitor-session {
    .snapshot-grid {
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }

    .student-snapshot-list {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }
}

@media (max-width: 1080px) {
  .classroom-monitor-session {
    .snapshot-grid {
      grid-template-columns: repeat(2, minmax(0, 1fr));
    }
  }
}

@media (max-width: 768px) {
  .classroom-monitor-session {
    .card-header,
    .snapshot-header {
      align-items: stretch;
      flex-direction: column;
    }

    .header-actions {
      flex-direction: column;
    }

    .snapshot-grid {
      grid-template-columns: 1fr;
    }

    .student-snapshot-list {
      grid-template-columns: 1fr;
    }
  }
}
</style>
