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

622 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 { fetchCourseLearningInfo, fetchLessonContent, saveVideoProgress, markLessonComplete, checkLessonAccess } = useCourse()
// State
const sidebarOpen = ref(false)
const activeTab = ref<'details' | 'announcements'>('details')
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 (typeof text === 'string') return text
return text?.th || text?.en || ''
}
const toggleSidebar = () => {
sidebarOpen.value = !sidebarOpen.value
}
const switchTab = (tab: 'details' | 'announcements', lessonId: any = null) => {
activeTab.value = tab
if (lessonId) {
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) {
alert('บทเรียนนี้ยังไม่เปิดให้เข้าชม')
isLessonLoading.value = false
return
}
const res = await fetchLessonContent(courseId.value, lessonId)
if (res.success) {
currentLesson.value = res.data
// Restore progress if available
if (res.progress) {
// Wait for video metadata to load usually, but set state
// We might set currentTime once metadata loaded
if (res.progress.video_progress_seconds > 0) {
currentTime.value = res.progress.video_progress_seconds
// We will apply this to videoRef locally when it is ready
}
}
}
} 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 ''
const content = getLocalizedText(currentLesson.value.content)
// Check if content looks like a URL (starts with http/https or /)
// And doesn't contain obvious text indicators
if (content && (content.startsWith('http') || content.startsWith('/')) && !content.includes(' ')) {
return content
}
return ''
})
// ==========================================
// 3. ระบบบันทึกความคืบหน้า (Progress Tracking)
// ==========================================
// บันทึกอัตโนมัติทุกๆ 10 วินาทีเมื่อเล่นวิดีโอ
watch(() => isPlaying.value, (playing) => {
if (playing) {
saveProgressInterval.value = setInterval(() => {
if (videoRef.value && currentLesson.value) {
// Send integers to avoid potential backend float issues
saveVideoProgress(
currentLesson.value.id,
Math.floor(videoRef.value.currentTime),
Math.floor(videoRef.value.duration || 0)
)
}
}, 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)
const onVideoEnded = async () => {
isPlaying.value = false
if (currentLesson.value) {
await markLessonComplete(courseId.value, currentLesson.value.id)
// โหลดข้อมูลคอร์สใหม่เพื่ออัปเดตสถานะติ๊กถูกด้านข้าง
await loadCourseData()
// Auto play next logic could go here
}
}
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>
<div class="learning-shell font-main antialiased selection:bg-blue-500/30 dark:!bg-[#0F172A] dark:!text-slate-200 transition-colors">
<!-- Header: Custom top bar for learning context -->
<header class="learning-header px-2 md:px-4 h-14 md:h-[56px] border-b border-slate-200 dark:border-white/5 flex items-center justify-between gap-2 md:gap-4 dark:!bg-slate-800 transition-colors">
<div class="flex items-center gap-1 md:gap-6 min-w-0 flex-1">
<!-- Mobile Sidebar Toggle -->
<button class="md:hidden text-slate-900 dark:text-white p-2 hover:bg-slate-100 dark:hover:bg-white/5 rounded-lg flex-shrink-0 transition-colors" @click="toggleSidebar">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" /></svg>
</button>
<!-- Back Navigation -->
<NuxtLink to="/dashboard/my-courses" class="text-slate-700 dark:text-slate-400 hover:text-slate-900 dark:hover:text-white transition-colors flex items-center gap-2 flex-shrink-0 p-2 md:p-0">
<span class="text-lg md:text-base"></span>
<span class="hidden md:inline text-[11px] font-bold">กลบไปหนาหล</span>
</NuxtLink>
<div class="w-[1px] h-4 bg-slate-200 dark:bg-white/10 hidden md:block flex-shrink-0"/>
<h1 class="text-[13px] md:text-sm font-black text-slate-900 dark:text-white tracking-tight truncate min-w-0 pr-2">
{{ courseData ? getLocalizedText(courseData.course.title) : 'กำลังโหลด...' }}
</h1>
</div>
<!-- Right Header Actions (Progress) -->
<div class="flex items-center gap-2 md:gap-10 pr-2 md:pr-0">
<div class="flex items-center gap-2 md:gap-3" v-if="courseData">
<span class="text-[10px] font-bold text-slate-700 dark:text-slate-400 whitespace-nowrap">
<span class="hidden md:inline">เรยนจบแล </span>0%
</span>
<div class="w-12 md:w-32 h-1 bg-white/10 rounded-full overflow-hidden flex-shrink-0">
<div class="h-full bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.3)]" style="width: 0%"/>
</div>
</div>
</div>
</header>
<!-- Sidebar: Course Curriculum list -->
<aside class="learning-sidebar dark:!bg-gray-900 dark:!border-r-white/5 transition-colors" :class="{ 'open': sidebarOpen }">
<div class="py-2" v-if="courseData">
<!-- Chapters & Lessons List -->
<div v-for="chapter in courseData.chapters" :key="chapter.id" class="mt-4">
<div class="chapter-header px-4 py-2 dark:!bg-slate-900 dark:!text-white dark:!border-b-white/5">
{{ getLocalizedText(chapter.title) }}
</div>
<div
v-for="lesson in chapter.lessons"
:key="lesson.id"
class="lesson-item px-4 dark:!text-slate-300 dark:!border-b-white/5 hover:dark:!bg-white/5 hover:dark:!text-white transition-colors"
:class="{
'active-lesson': currentLesson?.id === lesson.id && activeTab === 'details',
'completed': lesson.progress?.is_completed,
'locked': lesson.is_locked
}"
@click="!lesson.is_locked && switchTab('details', lesson.id)"
>
<div class="flex items-center gap-2 overflow-hidden">
<span class="flex-shrink-0 text-slate-400 text-xs" v-if="lesson.is_locked">🔒</span>
<span class="text-[12px] font-medium tracking-tight truncate pr-4">
{{ getLocalizedText(lesson.title) }}
</span>
</div>
<span class="icon-status flex-shrink-0" :class="{ 'text-emerald-500': lesson.progress?.is_completed, 'text-blue-500': currentLesson?.id === lesson.id }">
<span v-if="lesson.progress?.is_completed"></span>
<span v-else-if="currentLesson?.id === lesson.id"></span>
</span>
</div>
</div>
</div>
<div v-else-if="isLoading" class="p-6 text-center text-slate-500 text-sm">
กำลงโหลดเนอหา...
</div>
</aside>
<!-- Sidebar Overlay for mobile -->
<div v-if="sidebarOpen" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-[85] md:hidden" @click="toggleSidebar"/>
<!-- Main View Area -->
<div class="main-container custom-scrollbar overflow-x-hidden pt-6 dark:!bg-[#0B0F1A] transition-colors">
<main class="w-full max-w-7xl mx-auto px-4 md:px-8 pb-10 md:pb-20">
<!-- Tab Content: Announcements (Center Aligned) -->
<div v-if="activeTab === 'announcements'" class="animate-fade-in max-w-4xl mx-auto space-y-8 pt-8 md:pt-14">
<h2 class="text-2xl md:text-[28px] font-black text-slate-900 dark:text-white tracking-tight">ประกาศทงหมดในคอรสน</h2>
<div class="text-center text-slate-500 py-10">งไมประกาศในขณะน</div>
</div>
<!-- Tab Content: Lesson Details (Grid System) -->
<div v-if="activeTab === 'details'" class="animate-fade-in pt-4 md:pt-10">
<div class="grid grid-cols-1 md:grid-cols-12 gap-8 md:gap-10 items-start" v-if="currentLesson">
<!-- Left Side: Video + Title + Notes (8/12) -->
<div class="md:col-span-8 space-y-10 pb-24 md:pb-0">
<!-- Content Display Area -->
<div class="aspect-video relative group overflow-hidden rounded-2xl ring-1 ring-white/10 shadow-2xl bg-black">
<!-- Case: Quiz -->
<div v-if="currentLesson.type === 'QUIZ'" class="absolute inset-0 flex flex-col items-center justify-center bg-slate-900 text-white p-6 text-center">
<div class="w-20 h-20 rounded-full bg-blue-600/20 flex items-center justify-center mb-6">
<span class="text-4xl">📝</span>
</div>
<h3 class="text-xl font-bold mb-2">แบบทดสอบ: {{ getLocalizedText(currentLesson.title) }}</h3>
<p class="text-slate-400 mb-6 text-sm max-w-md">ทดสอบความเขาใจของคณในบทเรยนน</p>
<NuxtLink :to="`/classroom/quiz?course_id=${courseId}&lesson_id=${currentLesson.id}`" class="px-8 py-3 bg-blue-600 hover:bg-blue-500 rounded-xl font-bold text-sm transition-colors">
เรมทำแบบทดสอบ
</NuxtLink>
</div>
<!-- Case: Video with Source -->
<template v-else-if="videoSrc">
<video
ref="videoRef"
class="w-full h-full object-contain"
@timeupdate="updateProgress"
@loadedmetadata="onVideoMetadataLoaded"
@ended="onVideoEnded"
@play="isPlaying = true"
@pause="isPlaying = false"
:src="videoSrc"
>
Browser ของคณไมรองรบการเลนวโอ
</video>
<!-- Play Overlay -->
<div v-if="!isPlaying" class="absolute inset-0 flex items-center justify-center bg-black/5 backdrop-blur-[1px]">
<button class="w-16 h-16 md:w-20 md:h-20 rounded-full bg-blue-600/30 border border-white/20 flex items-center justify-center backdrop-blur-xl hover:scale-110 transition-transform shadow-lg" @click="togglePlay">
<svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-white fill-white translate-x-0.5" viewBox="0 0 24 24"><path d="M8 5v14l11-7z"/></svg>
</button>
</div>
<!-- Controls Overlay -->
<div class="absolute bottom-0 inset-x-0 p-4 md:p-6 pt-16 bg-gradient-to-t from-black/95 via-black/40 to-transparent">
<div class="flex items-center gap-4 text-[11px] font-bold text-white/80">
<button class="text-xs hover:text-blue-500 transition-colors" @click="togglePlay">{{ isPlaying ? '' : '' }}</button>
<span class="font-mono">{{ currentTimeDisplay }} / {{ durationDisplay }}</span>
<div class="flex-grow h-[3px] bg-white/10 rounded-full relative cursor-pointer" @click="seek">
<div :style="{ width: videoProgress + '%' }" class="absolute top-0 left-0 h-full bg-blue-500 rounded-full"/>
</div>
<div class="flex gap-4">
<span class="cursor-pointer hover:text-white" @click="videoRef?.requestFullscreen()"></span>
</div>
</div>
</div>
</template>
<!-- Case: Video but No Source -->
<div v-else class="absolute inset-0 flex flex-col items-center justify-center bg-slate-900 text-slate-500">
<span class="text-4xl mb-4">🎬</span>
<p class="font-medium text-sm">ไมพบวโอในบทเรยนน</p>
</div>
</div>
<!-- Lesson Title -->
<div>
<h2 class="text-2xl md:text-[32px] font-black text-slate-900 dark:text-white leading-tight tracking-tight break-words mb-2">
{{ getLocalizedText(currentLesson.title) }}
</h2>
</div>
<!-- Lesson Notes/Description Card -->
<div class="rounded-2xl bg-white dark:!bg-slate-800 border border-slate-200 dark:border-slate-700 p-6 md:p-10 shadow-sm dark:shadow-xl transition-colors" v-if="currentLesson.description">
<h3 class="text-[14px] md:text-[16px] font-black text-slate-900 dark:text-slate-50 mb-6 uppercase tracking-[0.2em] border-b border-slate-200 dark:border-slate-600 pb-4">รายละเอยดบทเรยน</h3>
<div class="text-[16px] md:text-[18px] text-slate-700 dark:text-slate-200 leading-relaxed font-medium space-y-6">
<p>{{ getLocalizedText(currentLesson.description) }}</p>
</div>
</div>
</div>
<!-- Right Side: Resources + Actions (4/12) -->
<div class="md:col-span-4 space-y-6 md:sticky md:top-6">
<!-- Resources Card -->
<div class="rounded-2xl bg-white dark:!bg-slate-800 border border-slate-200 dark:border-slate-700 p-6 md:p-8 shadow-sm dark:shadow-xl transition-colors" v-if="currentLesson.attachments && currentLesson.attachments.length > 0">
<h3 class="text-[14px] md:text-[16px] font-black text-slate-900 dark:text-slate-100 mb-6 uppercase tracking-[0.2em] border-b border-slate-200 dark:border-slate-700 pb-4">เอกสารประกอบ</h3>
<div class="space-y-3">
<!-- Attachment Row -->
<div v-for="att in currentLesson.attachments" :key="att.id" class="flex items-center justify-between p-4 bg-slate-50 dark:bg-slate-700/50 rounded-2xl border border-slate-200 dark:border-slate-600 group hover:bg-slate-100 dark:hover:bg-slate-600/50 transition-all cursor-pointer min-w-0">
<a :href="att.file_path" target="_blank" class="flex items-center gap-3 min-w-0 flex-1 no-underline">
<span class="text-xl flex-shrink-0">📄</span>
<div class="flex flex-col min-w-0">
<span class="text-[14px] font-bold text-slate-800 dark:text-slate-100 truncate pr-2">{{ att.file_name }}</span>
<span class="text-[11px] font-black text-slate-500 dark:text-slate-400 uppercase">{{ (att.file_size / 1024 / 1024).toFixed(2) }} MB</span>
</div>
</a>
<a :href="att.file_path" target="_blank" class="w-8 h-8 rounded-full flex items-center justify-center bg-slate-100 dark:bg-slate-700/50 group-hover:bg-blue-600 text-slate-600 dark:text-slate-400 group-hover:text-white transition-all text-xs flex-shrink-0"></a>
</div>
</div>
</div>
<!-- Navigation Actions (Desktop Only - Inside Column) -->
<div class="hidden md:flex flex-col gap-4">
<button v-if="currentLesson.next_lesson_id" @click="loadLesson(currentLesson.next_lesson_id)" class="w-full py-5 bg-blue-600 hover:bg-blue-500 rounded-2xl text-[14px] font-black text-white shadow-xl shadow-blue-600/20 transition-all active:scale-95">
บทเรียนถัดไป
</button>
<button v-if="currentLesson.prev_lesson_id" @click="loadLesson(currentLesson.prev_lesson_id)" class="w-full py-5 bg-slate-800 hover:bg-slate-700 rounded-2xl text-[14px] font-black text-slate-300 transition-all ring-1 ring-white/10">
บทเรียนก่อนหน้า
</button>
</div>
</div>
</div>
<div v-else-if="isLessonLoading" class="text-center pt-20 text-white">
<span class="loading-spinner">กำลงโหลดบทเรยน...</span>
</div>
<div v-else class="text-center pt-20 text-slate-400">
กรณาเลอกบทเรยนจากเมนานซาย
</div>
</div>
<!-- Sticky Bottom Bar (Mobile Only) -->
<div v-if="activeTab === 'details' && currentLesson" class="md:hidden fixed bottom-0 inset-x-0 p-4 bg-white dark:bg-slate-900/90 dark:backdrop-blur-xl border-t border-slate-300 dark:border-white/5 z-[100] flex gap-3 transition-colors">
<button v-if="currentLesson.prev_lesson_id" @click="loadLesson(currentLesson.prev_lesson_id)" class="flex-1 py-4 bg-slate-800 rounded-xl text-xs font-black text-slate-300 ring-1 ring-white/10">
ย้อนกลับ
</button>
<button v-if="currentLesson.next_lesson_id" @click="loadLesson(currentLesson.next_lesson_id)" class="flex-[2] py-4 bg-blue-600 rounded-xl text-xs font-black text-white shadow-lg shadow-blue-600/20">
บทเรียนถัดไป
</button>
</div>
</main>
</div>
</div>
</template>
<style scoped>
.learning-shell {
display: grid;
grid-template-columns: 320px 1fr;
grid-template-rows: 56px 1fr;
height: 100vh;
overflow: hidden;
background: #ffffff;
color: #1e293b;
transition: background 0.2s, color 0.2s;
}
:global(.dark) .learning-shell {
background: #0F172A;
color: #F8FAFC;
}
.learning-header {
grid-column: 1 / -1;
background: #ffffff;
border-bottom: 1px solid #e2e8f0;
display: flex;
align-items: center;
justify-content: space-between;
z-index: 100;
transition: background 0.2s, border-color 0.2s;
}
:global(.dark) .learning-header {
background: #1e293b;
border-bottom-color: rgba(255, 255, 255, 0.05);
}
.learning-sidebar {
grid-row: 2;
grid-column: 1;
background: #ffffff;
border-right: 1px solid #e2e8f0;
overflow-y: auto;
z-index: 90;
transition: background 0.2s, border-color 0.2s;
}
:global(.dark) .learning-sidebar {
background: #111827;
border-right-color: rgba(255, 255, 255, 0.05);
}
.main-container {
grid-row: 2;
grid-column: 2;
display: flex;
flex-direction: column;
overflow-y: auto;
background: #ffffff;
transition: background 0.2s;
}
:global(.dark) .main-container {
background: #0B0F1A;
}
@media (max-width: 1024px) {
.main-container {
grid-column: 1;
}
}
.lesson-item {
padding: 14px 24px;
cursor: pointer;
display: flex;
justify-content: space-between;
align-items: center;
transition: all 0.2s;
color: #000000;
border-bottom: 1px solid #e2e8f0;
}
.lesson-item:hover {
background-color: #f1f5f9;
color: #000000;
}
:global(.dark) .lesson-item {
color: #e2e8f0;
border-bottom-color: rgba(255, 255, 255, 0.01);
}
:global(.dark) .lesson-item:hover {
background-color: rgba(255, 255, 255, 0.03);
color: #ffffff;
}
.active-tab {
background: rgba(59, 130, 246, 0.1);
color: #2563eb;
font-weight: 700;
}
.active-lesson {
background-color: #f3f4f6;
color: #000000;
box-shadow: inset 4px 0 0 #3B82F6;
}
:global(.dark) .active-lesson {
background-color: #1E293B;
color: #fff;
}
.chapter-header {
background: #f3f4f6;
color: #000000;
font-weight: 800;
font-size: 13px;
border-bottom: 1px solid #d1d5db;
transition: all 0.2s;
letter-spacing: 0.05em;
}
:global(.dark) .chapter-header {
background: #0F172A;
color: #ffffff;
border-bottom-color: rgba(255, 255, 255, 0.05);
}
.learning-footer {
position: sticky;
bottom: 0;
z-index: 50;
}
.animate-fade-in {
animation: fadeIn 0.4s ease-out forwards;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
.custom-scrollbar::-webkit-scrollbar {
width: 4px;
}
.custom-scrollbar::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.1);
border-radius: 10px;
}
@media (max-width: 1024px) {
.learning-shell { grid-template-columns: 1fr; }
.learning-sidebar {
position: fixed;
left: -320px;
top: 56px;
bottom: 0;
width: 320px;
transition: transform 0.3s ease;
}
.learning-sidebar.open { transform: translateX(320px); }
}
</style>