"use client"; import { useEffect, useState } from "react"; import { useParams, useRouter } from "next/navigation"; import { Link } from "@/app/digital/i18n/navigation"; import { VideoPlayer } from "@/app/digital/components/course/VideoPlayer"; import { LessonMarkdown } from "./LessonMarkdown"; import { getLesson, type LessonDetail } from "@/config/digital/lessons"; import { CURRICULUM_CONFIG, DOWNLOAD_CONFIG } from "@/config/digital/course"; import { canWatchLesson, isFreeTrial } from "@/app/digital/lib/course-payment"; import { useAuthAndVip } from "@/app/digital/lib/useAuthAndVip"; import { getStoredToken, getStoredUser } from "@/app/digital/lib/pocketbase"; import { getCompletedLessons, getNote, isBookmarked, markCompleted, setLastWatched, setNote as saveNote, toggleBookmark, } from "@/app/digital/lib/learning"; import Header from "@/app/digital/components/Header"; import AuthModal from "@/app/digital/components/AuthModal"; import { getPayEnv, redirectToPay, getDeviceFromEnv, } from "@/app/digital/lib/payment"; const COURSE_LESSONS = CURRICULUM_CONFIG.modules.flatMap(({ lessons }, moduleIndex) => lessons.map((_, lessonIndex) => ({ moduleIndex, lessonIndex })) ); type DeckSlide = { title: string; body: string; }; function buildDeckSlides(lesson: LessonDetail): DeckSlide[] { const sections = lesson.markdown .split("\n## ") .slice(1) .map((section) => { const [rawTitle, ...bodyLines] = section.split("\n"); return { title: rawTitle.trim(), body: bodyLines .filter((line) => line.trim()) .slice(0, 5) .join("\n") .replace(/^- /gm, "") .replace(/^\d+\. /gm, ""), }; }) .filter((slide) => slide.title && slide.body); return [ { title: "本节导览", body: `${lesson.name}\n预计学习 ${lesson.duration}\n完成课件后可标记进度并保存笔记。`, }, ...sections, ]; } function LessonDeck({ lesson, onComplete, }: { lesson: LessonDetail; onComplete: () => void; }) { const slides = buildDeckSlides(lesson); const [activeIndex, setActiveIndex] = useState(0); const [playing, setPlaying] = useState(false); const activeSlide = slides[activeIndex] ?? slides[0]; const progress = slides.length > 0 ? Math.round(((activeIndex + 1) / slides.length) * 100) : 0; useEffect(() => { if (!playing) return; const timer = window.setTimeout(() => { setActiveIndex((current) => { if (current >= slides.length - 1) { setPlaying(false); onComplete(); return current; } return current + 1; }); }, 6500); return () => window.clearTimeout(timer); }, [activeIndex, onComplete, playing, slides.length]); return (

Interactive Lesson

{activeSlide.title}

{activeIndex + 1} / {slides.length}

{activeSlide.body}

); } export default function LessonPage() { const params = useParams(); const router = useRouter(); const { vip, refetch } = useAuthAndVip(); const [authOpen, setAuthOpen] = useState(false); const [payRedirecting, setPayRedirecting] = useState(false); const [bookmarked, setBookmarked] = useState(false); const [completed, setCompleted] = useState(false); const [lessonNote, setLessonNote] = useState(""); const [statusMessage, setStatusMessage] = useState(""); const moduleIndex = Number(params.moduleIndex); const lessonIndex = Number(params.lessonIndex); const lesson = getLesson(moduleIndex, lessonIndex); const unlocked = canWatchLesson(moduleIndex, lessonIndex, vip); const lessonName = lesson?.name; const currentLessonIndex = COURSE_LESSONS.findIndex( (item) => item.moduleIndex === moduleIndex && item.lessonIndex === lessonIndex ); const previousLesson = currentLessonIndex > 0 ? COURSE_LESSONS[currentLessonIndex - 1] : null; const nextLesson = currentLessonIndex >= 0 && currentLessonIndex < COURSE_LESSONS.length - 1 ? COURSE_LESSONS[currentLessonIndex + 1] : null; useEffect(() => { if (lessonName && unlocked) setLastWatched(moduleIndex, lessonIndex, lessonName); }, [moduleIndex, lessonIndex, lessonName, unlocked]); useEffect(() => { if (!lesson) return; const key = `${moduleIndex}-${lessonIndex}`; setBookmarked(isBookmarked(moduleIndex, lessonIndex)); setCompleted(getCompletedLessons().has(key)); setLessonNote(getNote(moduleIndex, lessonIndex)); setStatusMessage(""); }, [moduleIndex, lessonIndex, lesson]); const handleBookmark = () => { const active = toggleBookmark(moduleIndex, lessonIndex); setBookmarked(active); setStatusMessage(active ? "已收藏本节" : "已取消收藏"); }; const handleMarkCompleted = () => { markCompleted(moduleIndex, lessonIndex); setCompleted(true); setStatusMessage("本节已完成"); }; const handleSaveNote = () => { saveNote(moduleIndex, lessonIndex, lessonNote); setStatusMessage("笔记已保存"); }; const startPay = (userId: string) => { const env = getPayEnv(); const channel = "wxpay"; const device = getDeviceFromEnv(env); const returnUrl = `${window.location.origin}/`; redirectToPay({ user_id: userId, return_url: returnUrl, channel, device, type: "video", useJoinConfig: true, }); }; const handleEnroll = async () => { if (payRedirecting) return; setPayRedirecting(true); try { // 先验证登录态 let meRes = await fetch("/api/digital/auth/me", { credentials: "include" }); let meData = await meRes.json().catch(() => ({})); if (meData?.user?.id) { // 已登录:先校验 VIP,已是 VIP 则无需支付 const vipRes = await fetch(`/api/digital/vip/check?email=${encodeURIComponent(meData.user.email)}`, { credentials: "include" }); const vipData = await vipRes.json().catch(() => ({})); if (vipData?.vip) { await refetch(); return; } startPay(meData.user.id); return; } const storedUser = getStoredUser(); const storedToken = getStoredToken(); if (storedUser?.id && storedToken) { await fetch("/api/digital/auth/sync-session", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: storedToken, record: storedUser }), credentials: "include", }).catch(() => null); meRes = await fetch("/api/digital/auth/me", { credentials: "include" }); meData = await meRes.json().catch(() => ({})); if (meData?.user?.id) { const vipRes = await fetch(`/api/digital/vip/check?email=${encodeURIComponent(meData.user.email)}`, { credentials: "include" }); const vipData = await vipRes.json().catch(() => ({})); if (vipData?.vip) { await refetch(); return; } startPay(meData.user.id); return; } } setAuthOpen(true); } finally { setPayRedirecting(false); } }; if (!lesson || isNaN(moduleIndex) || isNaN(lessonIndex)) { return (

章节不存在

请检查链接或返回课程首页

返回首页
); } return (

{lesson.name} {isFreeTrial(moduleIndex, lessonIndex) && ( 试看 )}

时长 {lesson.duration}

{unlocked ? ( lesson.videoUrl ? ( ) : ( ) ) : (

报名解锁本章节

)}
{unlocked && (
{previousLesson && ( 上一节 )} {nextLesson && ( 下一节 )}
)} {statusMessage && (

{statusMessage}

)} {unlocked && (

配套文档

)} {unlocked && (

学习笔记