elearning/Frontend-Learner/pages/classroom/learning.vue

653 lines
26 KiB
Vue

<script setup lang="ts">
/**
* @file learning.vue
* @description หน้าเรียนออนไลน์ (Classroom Interface)
* จัดการแสดงผลวิดีโอรายการบทเรียน และติดตามความคืบหน้า
* ออกแบบให้เหมือนระบบ LMS มาตรฐาน
*/
definePageMeta({
layout: false, // Custom layout defined within this component
middleware: 'auth'
})
useHead({
title: 'ห้องเรียนออนไลน์ - e-Learning'
})
const route = useRoute()
const { t } = useI18n()
const { user } = useAuth()
const { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, markLessonComplete, checkLessonAccess, fetchVideoProgress } = useCourse()
// Media Prefs (Global Volume)
const { volume, muted: isMuted, setVolume, setMuted, applyTo } = useMediaPrefs()
// State
const sidebarOpen = ref(false)
const courseId = computed(() => Number(route.query.course_id))
// ==========================================
// 1. ตัวแปร State (สถานะของ UI)
// ==========================================
// courseData: เก็บข้อมูลโครงสร้างคอร์ส (บทเรียนต่างๆ)
const courseData = ref<any>(null)
// currentLesson: บทเรียนที่กำลังเรียนอยู่ปัจจุบัน
const currentLesson = ref<any>(null)
const isLoading = ref(true) // โหลดข้อมูลคอร์ส
const isLessonLoading = ref(false) // โหลดเนื้อหาบทเรียน
// Video Player State (สถานะวิดีโอ)
const videoRef = ref<HTMLVideoElement | null>(null)
const isPlaying = ref(false)
const videoProgress = ref(0)
const currentTime = ref(0)
const duration = ref(0)
const saveProgressInterval = ref<any>(null) // ตัวแปรเก็บ setInterval สำหรับบันทึกความคืบหน้าอัตโนมัติ
// Helper for localization
const getLocalizedText = (text: any) => {
if (!text) return ''
if (typeof text === 'string') return text
return text.th || text.en || ''
}
const toggleSidebar = () => {
sidebarOpen.value = !sidebarOpen.value
}
// Logic loadLesson แยกออกมา
const handleLessonSelect = (lessonId: number) => {
loadLesson(lessonId)
// Close sidebar on mobile when selecting a lesson
if (import.meta.client && window.innerWidth <= 1024) {
sidebarOpen.value = false
}
}
// Data Fetching
// ==========================================
// 2. ฟังก์ชันโหลดข้อมูล (Data Fetching)
// ==========================================
// โหลดโครงสร้างคอร์สและบทเรียนทั้งหมด
const loadCourseData = async () => {
if (!courseId.value) return
isLoading.value = true
try {
const res = await fetchCourseLearningInfo(courseId.value)
if (res.success) {
courseData.value = res.data
// Auto-load logic: ถ้ายังไม่ได้เลือกบทเรียน ให้โหลดบทแรกที่ไม่ล็อคมาแสดง
if (!currentLesson.value) {
const firstChapter = res.data.chapters[0]
if (firstChapter && firstChapter.lessons.length > 0) {
// Find first unlocked or just first
const availableLesson = firstChapter.lessons.find((l: any) => !l.is_locked) || firstChapter.lessons[0]
loadLesson(availableLesson.id)
}
}
}
} catch (error) {
console.error('Error loading course:', error)
} finally {
isLoading.value = false
}
}
const loadLesson = async (lessonId: number) => {
if (currentLesson.value?.id === lessonId) return
// Clear previous video state
isPlaying.value = false
videoProgress.value = 0
currentTime.value = 0
if (videoRef.value) {
videoRef.value.pause()
videoRef.value.currentTime = 0
}
isLessonLoading.value = true
try {
// Optional: Check access first
const accessRes = await checkLessonAccess(courseId.value, lessonId)
if (accessRes.success && !accessRes.data.is_accessible) {
let msg = t('classroom.notAvailable')
// Handle specific lock reasons
if (accessRes.data.lock_reason) {
msg = accessRes.data.lock_reason
} else if (accessRes.data.required_quiz_pass && !accessRes.data.required_quiz_pass.is_passed) {
const quizTitle = getLocalizedText(accessRes.data.required_quiz_pass.title)
msg = `กรุณาทำแบบทดสอบ "${quizTitle}" ให้ผ่านก่อน`
} else if (accessRes.data.required_lessons && accessRes.data.required_lessons.length > 0) {
const reqLesson = accessRes.data.required_lessons.find((l: any) => !l.is_completed)
if (reqLesson) {
msg = `กรุณาเรียนบทเรียน "${getLocalizedText(reqLesson.title)}" ให้จบก่อน`
}
} else if (accessRes.data.is_enrolled === false) {
msg = 'คุณยังไม่ได้ลงทะเบียนในคอร์สนี้'
}
alert(msg)
isLessonLoading.value = false
return
}
// 1. Fetch content
const res = await fetchLessonContent(courseId.value, lessonId)
if (res.success) {
currentLesson.value = res.data
// Update Lesson Completion UI status safely
if (currentLesson.value?.progress?.is_completed && courseData.value) {
for (const chapter of courseData.value.chapters) {
const lesson = chapter.lessons.find((l: any) => l.id === lessonId)
if (lesson) {
if (!lesson.progress) lesson.progress = {}
lesson.progress.is_completed = true
break
}
}
}
// 2. Fetch Initial Progress (Resume Playback)
if (currentLesson.value.type === 'VIDEO') {
// A. Server Progress
const progressRes = await fetchVideoProgress(lessonId)
let serverProgress = 0
if (progressRes.success && progressRes.data?.video_progress_seconds) {
serverProgress = progressRes.data.video_progress_seconds
}
// B. Local Progress (Buffer)
const localProgress = getLocalProgress(lessonId)
// C. Hybrid Resume (Max Wins)
const resumeTime = Math.max(serverProgress, localProgress)
if (resumeTime > 0) {
console.log(`Resuming at: ${resumeTime}s (Server: ${serverProgress}, Local: ${localProgress})`)
initialSeekTime.value = resumeTime
maxWatchedTime.value = resumeTime
currentTime.value = resumeTime
} else {
initialSeekTime.value = 0
maxWatchedTime.value = 0
}
}
}
} catch (error) {
console.error('Error loading lesson:', error)
} finally {
isLessonLoading.value = false
}
}
// Video & Progress State
const initialSeekTime = ref(0)
const maxWatchedTime = ref(0) // Anti-rewind monotonic tracking
const lastSavedTime = ref(-1)
const lastSavedTimestamp = ref(0) // Server throttle timestamp
const lastLocalSaveTimestamp = ref(0) // Local throttle timestamp
// Helper: Get Local Storage Key
const getLocalProgressKey = (lessonId: number) => {
if (!user.value?.id) return null
return `progress:${user.value.id}:${lessonId}`
}
// Helper: Get Local Progress
const getLocalProgress = (lessonId: number): number => {
try {
const key = getLocalProgressKey(lessonId)
if (!key) return 0
const stored = localStorage.getItem(key)
return stored ? parseFloat(stored) : 0
} catch (e) {
return 0
}
}
// Helper: Save to Local Storage
const saveLocalProgress = (lessonId: number, time: number) => {
try {
const key = getLocalProgressKey(lessonId)
if (key) {
localStorage.setItem(key, time.toString())
}
} catch (e) {
// Ignore storage errors
}
}
const onVideoMetadataLoaded = () => {
if (videoRef.value) {
// Bind Media Preferences (Volume/Mute)
applyTo(videoRef.value)
// Resume playback if we have a saved position
if (initialSeekTime.value > 0) {
// Ensure we don't seek past duration
const seekTo = Math.min(initialSeekTime.value, videoRef.value.duration || Infinity)
videoRef.value.currentTime = seekTo
}
}
}
const togglePlay = () => {
if (!videoRef.value) return
if (isPlaying.value) videoRef.value.pause()
else videoRef.value.play()
isPlaying.value = !isPlaying.value
}
// -----------------------------------------------------
// ROBUST PROGRESS SAVING SYSTEM (Hybrid: Local + Server)
// -----------------------------------------------------
// Main Server Save Function
const performSaveProgress = async (force: boolean = false, keepalive: boolean = false) => {
if (!videoRef.value || !currentLesson.value || currentLesson.value.type !== 'VIDEO') return
const now = Date.now()
const maxSec = Math.floor(maxWatchedTime.value) // Use max watched time
const durationSec = Math.floor(videoRef.value.duration || 0)
// 1. Validation: Don't save if progress hasn't increased (Monotonic Check)
if (!force && maxSec <= lastSavedTime.value) return
// 2. Validation: Server Throttle (15 seconds)
if (!force && (now - lastSavedTimestamp.value < 15000)) return
// Save
lastSavedTime.value = maxSec
lastSavedTimestamp.value = now
console.log(`Saving Server: ${maxSec}/${durationSec} (KeepAlive: ${keepalive})`)
const res = await saveVideoProgress(currentLesson.value.id, maxSec, durationSec, keepalive)
// Check completion
if (res.success && res.data?.is_completed) {
markLessonAsCompletedLocally(currentLesson.value.id)
}
}
// Helper to update Sidebar UI
const markLessonAsCompletedLocally = (lessonId: number) => {
if (courseData.value) {
for (const chapter of courseData.value.chapters) {
const lesson = chapter.lessons.find((l: any) => l.id === lessonId)
if (lesson) {
if (!lesson.progress) lesson.progress = {}
lesson.progress.is_completed = true
break
}
}
}
}
const updateProgress = () => {
if (!videoRef.value) return
// UI Update
currentTime.value = videoRef.value.currentTime
duration.value = videoRef.value.duration
videoProgress.value = (currentTime.value / duration.value) * 100
// Update Monotonic Progress
if (currentTime.value > maxWatchedTime.value) {
maxWatchedTime.value = currentTime.value
}
// Logic: Periodic Save
if (isPlaying.value && currentLesson.value?.id) {
const now = Date.now()
// 1. Local Save Throttle (5 seconds)
if (now - lastLocalSaveTimestamp.value > 5000) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
lastLocalSaveTimestamp.value = now
}
// 2. Server Save Throttle (15 seconds) checked inside function
performSaveProgress(false, false)
}
}
// Volume Controls Logic replaced by useMediaPrefs
const volumeIcon = computed(() => {
if (isMuted.value || volume.value === 0) return 'volume_off'
if (volume.value < 0.5) return 'volume_down'
return 'volume_up'
})
const handleToggleMute = () => {
setMuted(!isMuted.value)
}
const handleVolumeChange = (val: any) => {
const newVol = typeof val === 'number' ? val : Number(val.target.value)
setVolume(newVol)
}
const videoSrc = computed(() => {
if (!currentLesson.value) return ''
// Use explicit video_url from API first
if (currentLesson.value.video_url) return currentLesson.value.video_url
// Fallback (deprecated logic, but keeping just in case)
const content = getLocalizedText(currentLesson.value.content)
if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) {
return content
}
return ''
})
// ==========================================
// 3. ระบบบันทึกความคืบหน้า (Progress Tracking)
// ==========================================
// บันทึกอัตโนมัติทุกๆ 10 วินาทีเมื่อเล่นวิดีโอ
// บันทึกอัตโนมัติทุกๆ 10 วินาทีเมื่อเล่นวิดีโอ
// Event Listeners for Robustness
onMounted(() => {
// Page/Tab Visibility Logic
if (import.meta.client) {
document.addEventListener('visibilitychange', handleVisibilityChange)
window.addEventListener('pagehide', handlePageHide)
}
})
onBeforeUnmount(() => {
if (import.meta.client) {
document.removeEventListener('visibilitychange', handleVisibilityChange)
window.removeEventListener('pagehide', handlePageHide)
}
// Final save attempt when component destroys
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, true)
})
const handleVisibilityChange = () => {
if (document.hidden) {
console.log('Tab hidden, saving progress...')
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, true) // Force save with keepalive
}
}
const handlePageHide = () => {
// Triggered on page refresh, close tab, or navigation
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, true)
}
// Watch Video Events
watch(isPlaying, (playing) => {
if (!playing) {
// Paused: Save immediately
if (currentLesson.value?.id) {
saveLocalProgress(currentLesson.value.id, maxWatchedTime.value)
}
performSaveProgress(true, false)
}
})
// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)
// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)
const onVideoEnded = async () => {
isPlaying.value = false
console.log('Video Ended')
// Force save progress at 100%
await performSaveProgress(true, false)
// Call explicit complete endpoint if exists
if (currentLesson.value) {
const res = await markLessonComplete(courseId.value, currentLesson.value.id)
if (res.success) {
markLessonAsCompletedLocally(currentLesson.value.id)
if (res.data.is_course_completed) {
alert("ยินดีด้วย! คุณเรียนจบหลักสูตรแล้ว")
}
}
}
}
const formatTime = (time: number) => {
const m = Math.floor(time / 60)
const s = Math.floor(time % 60)
return `${m}:${s.toString().padStart(2, '0')}`
}
const currentTimeDisplay = computed(() => formatTime(currentTime.value))
const durationDisplay = computed(() => formatTime(duration.value || 0))
const seek = (e: MouseEvent) => {
if (!videoRef.value) return
const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()
const percent = (e.clientX - rect.left) / rect.width
videoRef.value.currentTime = percent * videoRef.value.duration
}
onMounted(() => {
loadCourseData()
})
onBeforeUnmount(() => {
clearInterval(saveProgressInterval.value)
})
</script>
<template>
<q-layout view="hHh LpR lFf" class="bg-[var(--bg-body)] text-[var(--text-main)]">
<!-- Header -->
<q-header bordered class="bg-[var(--bg-surface)] border-b border-gray-200 dark:border-white/5 text-[var(--text-main)] h-14">
<q-toolbar>
<q-btn flat round dense icon="menu" class="lg:hidden mr-2" @click="toggleSidebar" />
<NuxtLink
to="/dashboard/my-courses"
class="inline-flex items-center gap-2 text-slate-900 dark:text-white hover:text-blue-600 dark:hover:text-blue-300 transition-all font-black text-sm md:text-base group mr-4"
>
<q-icon name="arrow_back" size="24px" class="transition-transform group-hover:-translate-x-1" />
<span>{{ $t('classroom.backToDashboard') }}</span>
</NuxtLink>
<q-toolbar-title class="text-base font-bold text-center lg:text-left truncate text-slate-900 dark:text-white">
{{ courseData ? getLocalizedText(courseData.course.title) : $t('classroom.loadingTitle') }}
</q-toolbar-title>
<div class="flex items-center gap-2">
<!-- Right actions -->
</div>
</q-toolbar>
</q-header>
<!-- Sidebar (Curriculum) -->
<q-drawer
v-model="sidebarOpen"
show-if-above
bordered
side="left"
:width="320"
:breakpoint="1024"
class="bg-[var(--bg-surface)]"
content-class="bg-[var(--bg-surface)]"
>
<div v-if="courseData" class="h-full scroll">
<q-list class="pb-10">
<template v-for="chapter in courseData.chapters" :key="chapter.id">
<q-item-label header class="bg-slate-100 dark:bg-slate-800 text-[var(--text-main)] font-bold sticky top-0 z-10 border-b dark:border-white/5 text-sm py-4">
{{ getLocalizedText(chapter.title) }}
</q-item-label>
<q-item
v-for="lesson in chapter.lessons"
:key="lesson.id"
clickable
v-ripple
:active="currentLesson?.id === lesson.id"
active-class="bg-blue-50 text-blue-700 dark:bg-blue-900/20 dark:text-blue-200 font-medium"
class="border-b border-gray-50 dark:border-white/5"
@click="!lesson.is_locked && handleLessonSelect(lesson.id)"
:disable="lesson.is_locked"
>
<q-item-section avatar v-if="lesson.is_locked">
<q-icon name="lock" size="xs" color="grey" />
</q-item-section>
<q-item-section>
<q-item-label class="text-sm md:text-base line-clamp-2 text-[var(--text-main)]">
{{ getLocalizedText(lesson.title) }}
</q-item-label>
</q-item-section>
<q-item-section side>
<q-icon v-if="lesson.progress?.is_completed" name="check_circle" color="positive" size="xs" />
<q-icon v-else-if="currentLesson?.id === lesson.id" name="play_circle" color="primary" size="xs" />
<q-icon v-else name="radio_button_unchecked" color="grey-4" size="xs" />
</q-item-section>
</q-item>
</template>
</q-list>
</div>
<div v-else-if="isLoading" class="p-6 text-center text-slate-500">
<q-spinner color="primary" size="2em" />
<div class="mt-2 text-xs">{{ $t('classroom.loadingCurriculum') }}</div>
</div>
</q-drawer>
<!-- Main Content -->
<q-page-container class="bg-white dark:bg-slate-900">
<q-page class="flex flex-col h-full bg-slate-50 dark:bg-[#0B0F1A]">
<!-- Video Player & Content Area -->
<div class="w-full max-w-7xl mx-auto p-4 md:p-6 flex-grow">
<!-- Video Player -->
<div v-if="currentLesson && videoSrc" class="bg-black rounded-xl overflow-hidden shadow-lg mb-6 aspect-video relative group">
<video
ref="videoRef"
:src="videoSrc"
class="w-full h-full object-contain"
@click="togglePlay"
@timeupdate="updateProgress"
@loadedmetadata="onVideoMetadataLoaded"
@ended="onVideoEnded"
/>
<!-- Custom Controls Overlay (Simplified) -->
<div class="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 to-transparent transition-opacity opacity-0 group-hover:opacity-100">
<div class="flex items-center gap-4 text-white">
<q-btn flat round dense :icon="isPlaying ? 'pause' : 'play_arrow'" @click.stop="togglePlay" />
<div class="relative flex-grow h-1 bg-white/30 rounded cursor-pointer group/progress" @click="seek">
<div class="absolute top-0 left-0 h-full bg-blue-500 rounded group-hover/progress:h-1.5 transition-all" :style="{ width: videoProgress + '%' }"></div>
</div>
<span class="text-xs font-mono">{{ currentTimeDisplay }} / {{ durationDisplay }}</span>
<!-- Volume Control -->
<div class="flex items-center gap-2 group/volume">
<q-btn flat round dense :icon="volumeIcon" @click.stop="handleToggleMute" color="white" />
<div class="w-0 group-hover/volume:w-20 overflow-hidden transition-all duration-300 flex items-center">
<input
type="range"
min="0"
max="1"
step="0.1"
:value="volume"
@input="handleVolumeChange"
class="w-20 h-1 bg-white/30 rounded-lg appearance-none cursor-pointer accent-blue-500"
/>
</div>
</div>
</div>
</div>
</div>
<!-- Lesson Info -->
<div v-if="currentLesson" class="bg-[var(--bg-surface)] p-6 rounded-2xl shadow-sm border border-[var(--border-color)] mt-6">
<!-- ใช้สีจากตัวแปรกลาง: จะแยกโหมดให้อัตโนมัติ (สว่าง=ดำ / มืด=ขาว) -->
<h1 class="text-2xl md:text-3xl font-bold mb-3 text-slate-900 dark:text-white">{{ getLocalizedText(currentLesson.title) }}</h1>
<p class="text-slate-700 dark:text-slate-300 text-base md:text-lg" v-if="currentLesson.description">{{ getLocalizedText(currentLesson.description) }}</p>
<!-- Lesson Content Area (Text/HTML) -->
<div v-if="currentLesson.type === 'QUIZ'" class="mt-6 p-8 bg-[var(--bg-elevated)] rounded-xl border border-[var(--border-color)] text-center">
<q-icon name="quiz" size="4rem" color="primary" class="mb-4" />
<h2 class="text-xl font-bold mb-2 text-slate-900 dark:text-white">{{ $t('quiz.startTitle', 'แบบทดสอบ') }}</h2>
<p class="text-slate-500 mb-6">{{ getLocalizedText(currentLesson.quiz?.description || currentLesson.description) }}</p>
<div class="flex justify-center gap-4 text-sm text-slate-500 mb-8">
<span v-if="currentLesson.quiz?.questions?.length"><q-icon name="format_list_numbered" /> {{ currentLesson.quiz.questions.length }} </span>
<span v-if="currentLesson.quiz?.time_limit"><q-icon name="schedule" /> {{ currentLesson.quiz.time_limit }} นาท</span>
</div>
<q-btn
color="primary"
size="lg"
rounded
:label="$t('quiz.startBtn', 'เริ่มทำแบบทดสอบ')"
icon="play_arrow"
@click="$router.push(`/classroom/quiz?course_id=${courseId}&lesson_id=${currentLesson.id}`)"
/>
</div>
<div v-else-if="currentLesson.content" class="mt-6 prose dark:prose-invert max-w-none p-6 bg-[var(--bg-elevated)] rounded-xl border border-[var(--border-color)]">
<div v-html="getLocalizedText(currentLesson.content)" class="text-base md:text-lg leading-relaxed text-slate-900 dark:text-slate-200"></div>
</div>
<!-- Attachments Section -->
<div v-if="currentLesson.attachments && currentLesson.attachments.length > 0" class="mt-8">
<h3 class="text-lg font-bold mb-4 text-slate-900 dark:text-white flex items-center gap-2">
<q-icon name="attach_file" />
{{ $t('classroom.attachments') || 'เอกสารประกอบ' }}
</h3>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<a
v-for="file in currentLesson.attachments"
:key="file.file_name"
:href="file.presigned_url"
target="_blank"
class="flex items-center gap-4 p-4 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 transition-colors group"
>
<div class="w-10 h-10 rounded-lg bg-red-100 dark:bg-red-900/30 text-red-600 flex items-center justify-center">
<q-icon name="picture_as_pdf" size="24px" />
</div>
<div class="flex-1 min-w-0">
<div class="font-bold text-slate-900 dark:text-slate-200 truncate group-hover:text-blue-600 transition-colors">
{{ file.file_name }}
</div>
<div class="text-xs text-slate-500 dark:text-slate-400">
{{ (file.file_size / 1024 / 1024).toFixed(2) }} MB
</div>
</div>
<q-icon name="download" class="text-slate-400 group-hover:text-blue-600" />
</a>
</div>
</div>
</div>
</div>
</q-page>
</q-page-container>
</q-layout>
</template>
<style>
.mobile-hide-label .q-btn__content span {
display: none;
}
@media (min-width: 768px) {
.mobile-hide-label .q-btn__content span {
display: inline;
margin-left: 8px;
}
}
</style>