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

494 lines
21 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 { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, markLessonComplete, checkLessonAccess, fetchVideoProgress } = useCourse()
// 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
// 2. Fetch progress separately (New Flow)
// Note: fetchLessonContent might return progress in some APIs, but here we use dedicated endpoint as requested
const progressRes = await fetchVideoProgress(lessonId)
if (progressRes.success && progressRes.data) {
const p = progressRes.data
// Restore video time
if (p.video_progress_seconds > 0) {
currentTime.value = p.video_progress_seconds
// Force update video element if ready, otherwise onVideoMetadataLoaded will handle it
if (videoRef.value) {
videoRef.value.currentTime = currentTime.value
}
}
// Check if completed to update UI
if (p.is_completed) {
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
}
}
}
}
}
}
} catch (error) {
console.error('Error loading lesson:', error)
} finally {
isLessonLoading.value = false
}
}
const onVideoMetadataLoaded = () => {
if (videoRef.value && currentLesson.value) {
// Restore time if needed
if (currentTime.value > 0) {
videoRef.value.currentTime = currentTime.value
}
}
}
const togglePlay = () => {
if (!videoRef.value) return
if (isPlaying.value) videoRef.value.pause()
else videoRef.value.play()
isPlaying.value = !isPlaying.value
}
const updateProgress = () => {
if (!videoRef.value) return
currentTime.value = videoRef.value.currentTime
duration.value = videoRef.value.duration
videoProgress.value = (currentTime.value / duration.value) * 100
// Throttle save progress logic is handled in watcher or separate interval usually,
// but let's check if we should save periodically here for simplicity or use specific events
}
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 วินาทีเมื่อเล่นวิดีโอ
watch(() => isPlaying.value, (playing) => {
if (playing) {
saveProgressInterval.value = setInterval(async () => {
if (videoRef.value && currentLesson.value) {
// Send integers to avoid potential backend float issues
const res = await saveVideoProgress(
currentLesson.value.id,
Math.floor(videoRef.value.currentTime),
Math.floor(videoRef.value.duration || 0)
)
// Update local completion state if backend reports completed
if (res.success && res.data?.is_completed && courseData.value) {
for (const chapter of courseData.value.chapters) {
const lesson = chapter.lessons.find((l: any) => l.id === currentLesson.value.id)
if (lesson) {
if (!lesson.progress) lesson.progress = {}
lesson.progress.is_completed = true
break
}
}
}
}
}, 10000) // Every 10 seconds
} else {
clearInterval(saveProgressInterval.value)
// Save one last time on pause
if (videoRef.value && currentLesson.value) {
saveVideoProgress(
currentLesson.value.id,
Math.floor(videoRef.value.currentTime),
Math.floor(videoRef.value.duration || 0)
)
}
}
})
// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)
// เมื่อวิดีโอจบ ให้บันทึกว่าเรียนจบ (Complete)
const onVideoEnded = async () => {
isPlaying.value = false
if (currentLesson.value) {
const res = await markLessonComplete(courseId.value, currentLesson.value.id)
if (res.success && res.data) {
// 1. Update UI tick
if (courseData.value) {
for (const chapter of courseData.value.chapters) {
const lesson = chapter.lessons.find((l: any) => l.id === currentLesson.value.id)
if (lesson) {
if (!lesson.progress) lesson.progress = {}
lesson.progress.is_completed = true
break
}
}
}
// 2. Play Next Lesson (if available)
if (res.data.next_lesson_id) {
// Optional: Add auto-play user preference check or delay
// For now, let's just show a notification or auto-load after small delay
// handleLessonSelect(res.data.next_lesson_id)
// Or just let user click next
}
// 3. Handle Course Completion
if (res.data.is_course_completed) {
// Maybe show a congratulation modal
alert("ยินดีด้วย! คุณเรียนจบหลักสูตรแล้ว")
}
}
// Reload course data to ensure everything is synced (optional but safer)
// await loadCourseData()
}
}
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" @click="seek">
<div class="absolute top-0 left-0 h-full bg-blue-500 rounded" :style="{ width: videoProgress + '%' }"></div>
</div>
<span class="text-xs font-mono">{{ currentTimeDisplay }} / {{ durationDisplay }}</span>
</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 -->
<!-- Lesson Content Area (Text/HTML) -->
<div v-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>