Files
schoolNews/schoolNewsWeb/src/views/public/course/components/CourseLearning.vue

1270 lines
34 KiB
Vue
Raw Normal View History

2025-10-21 17:59:34 +08:00
<template>
<div class="course-learning">
<!-- 学习页头部 -->
<div class="learning-header">
<div class="header-left">
<el-button @click="handleBack" :icon="ArrowLeft" text>
2025-10-24 18:28:35 +08:00
{{ backButtonText }}
2025-10-21 17:59:34 +08:00
</el-button>
2025-10-28 19:04:35 +08:00
<span class="course-name">{{ courseItemVO?.name }}</span>
2025-10-21 17:59:34 +08:00
</div>
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
<div class="header-right">
<span class="progress-info">
学习进度{{ currentProgress }}%
</span>
</div>
</div>
<div class="learning-container">
2025-10-24 18:28:35 +08:00
<!-- 浮动展开按钮侧边栏收起时显示 -->
<div v-if="sidebarCollapsed" class="float-expand-btn" @click="toggleSidebar">
<el-button circle :icon="Expand" />
</div>
2025-10-21 17:59:34 +08:00
<!-- 左侧章节目录 -->
<div class="chapter-sidebar" :class="{ collapsed: sidebarCollapsed }">
<div class="sidebar-header">
<span class="sidebar-title">课程目录</span>
2025-10-28 19:04:35 +08:00
<el-button text :icon="Fold" @click="toggleSidebar" />
2025-10-21 17:59:34 +08:00
</div>
<div v-if="!sidebarCollapsed" class="chapter-list">
<el-collapse v-model="activeChapters">
2025-10-28 19:04:35 +08:00
<el-collapse-item v-for="(chapterItem, chapterIndex) in courseItemVO?.chapters || []" :key="chapterIndex"
:name="chapterIndex">
2025-10-21 17:59:34 +08:00
<template #title>
<div class="chapter-item-title">
2025-10-28 19:04:35 +08:00
<span>{{ chapterIndex + 1 }}. {{ chapterItem.name }}</span>
<span class="chapter-count">{{ getChapterNodes(chapterIndex).length }}</span>
2025-10-21 17:59:34 +08:00
</div>
</template>
<div class="node-items">
2025-10-28 19:04:35 +08:00
<div v-for="(node, nodeIndex) in getChapterNodes(chapterIndex)" :key="nodeIndex" class="node-item-bar" :class="{
active: currentChapterIndex === chapterIndex && currentNodeIndex === nodeIndex,
completed: isNodeCompleted(chapterIndex, nodeIndex)
}" @click="selectNode(chapterIndex, nodeIndex)">
2025-10-21 17:59:34 +08:00
<div class="node-item-content">
<el-icon v-if="isNodeCompleted(chapterIndex, nodeIndex)" class="check-icon">
<CircleCheck />
</el-icon>
<el-icon v-else class="node-type-icon">
<Document v-if="node.nodeType === 0" />
<Edit v-else-if="node.nodeType === 1" />
<Upload v-else />
</el-icon>
<span class="node-item-name">{{ node.name }}</span>
</div>
<div class="node-item-meta">
2025-10-28 19:04:35 +08:00
<el-tag v-if="node.isRequired === 1" type="danger" size="small" effect="plain">
2025-10-21 17:59:34 +08:00
必修
</el-tag>
<span v-if="node.duration" class="node-duration">
{{ node.duration }}分钟
</span>
</div>
</div>
</div>
</el-collapse-item>
</el-collapse>
</div>
</div>
<!-- 右侧学习内容区 -->
2025-10-28 19:04:35 +08:00
<div ref="contentAreaRef" class="content-area" :class="{ expanded: sidebarCollapsed }"
@scroll="handleContentScroll">
2025-10-21 17:59:34 +08:00
<!-- 加载中 -->
<div v-if="loading" class="loading-container">
<el-skeleton :rows="8" animated />
</div>
<!-- 节点内容 -->
<div v-else-if="currentNode" class="node-content">
<div class="node-header">
<h2 class="node-title">{{ currentNode.name }}</h2>
<div class="node-meta">
<el-tag v-if="currentNode.isRequired === 1" type="danger" size="small">
必修
</el-tag>
<span v-if="currentNode.duration" class="duration">
2025-10-28 19:04:35 +08:00
<el-icon>
<Clock />
</el-icon>
2025-10-21 17:59:34 +08:00
{{ currentNode.duration }} 分钟
</span>
</div>
</div>
<!-- 文章资源 -->
<div v-if="currentNode.nodeType === 0 && articleData" class="article-content">
<ArticleShowView
:as-dialog="false"
:article-data="articleData"
:category-list="[]"
@videos-completed="handleArticleVideosCompleted"
/>
2025-10-21 17:59:34 +08:00
</div>
<!-- 富文本内容 -->
<div v-else-if="currentNode.nodeType === 1" class="rich-text-content" v-html="currentNode.content">
</div>
<!-- 文件内容 -->
<div v-else-if="currentNode.nodeType === 2" class="file-content">
<div v-if="isVideoFile(currentNode.videoUrl)" class="video-wrapper">
2025-10-28 19:04:35 +08:00
<video :src="getFileUrl(currentNode.videoUrl)" controls class="video-player"
@timeupdate="handleVideoProgress" @ended="handleVideoEnded">
2025-10-21 17:59:34 +08:00
您的浏览器不支持视频播放
</video>
</div>
<div v-else-if="isAudioFile(currentNode.videoUrl)" class="audio-wrapper">
2025-10-28 19:04:35 +08:00
<audio :src="getFileUrl(currentNode.videoUrl)" controls class="audio-player"
@timeupdate="handleAudioProgress" @ended="handleAudioEnded">
2025-10-21 17:59:34 +08:00
您的浏览器不支持音频播放
</audio>
</div>
<div v-else class="file-download">
2025-10-28 19:04:35 +08:00
<el-icon class="file-icon">
<Document />
</el-icon>
2025-10-21 17:59:34 +08:00
<p>文件资源</p>
<el-button type="primary" @click="downloadFile(currentNode.videoUrl)">
2025-10-28 19:04:35 +08:00
<el-icon>
<Download />
</el-icon>
2025-10-21 17:59:34 +08:00
下载文件
</el-button>
</div>
</div>
<!-- 学习操作 -->
<div class="learning-actions">
<!-- 完成状态标签仅显示不可手动标记 -->
<el-tag v-if="isCurrentNodeCompleted" type="success" size="large">
<el-icon style="margin-right: 4px;">
2025-10-28 19:04:35 +08:00
<CircleCheck />
</el-icon>
已完成
</el-tag>
<el-tag v-else type="info" size="large">
<el-icon style="margin-right: 4px;">
<InfoFilled />
</el-icon>
学习中滚动到底部或视频播放完成后自动标记
</el-tag>
2025-10-21 17:59:34 +08:00
<div class="navigation-buttons">
2025-10-28 19:04:35 +08:00
<el-button @click="gotoPrevious" :disabled="!hasPrevious" :icon="ArrowLeft">
2025-10-21 17:59:34 +08:00
上一节
</el-button>
2025-10-28 19:04:35 +08:00
<el-button @click="gotoNext" :disabled="!hasNext" type="primary">
2025-10-21 17:59:34 +08:00
下一节
2025-10-28 19:04:35 +08:00
<el-icon>
<ArrowRight />
</el-icon>
2025-10-21 17:59:34 +08:00
</el-button>
</div>
</div>
</div>
<!-- 暂无内容 -->
<div v-else class="empty-content">
<el-empty description="暂无学习内容" />
</div>
</div>
</div>
</div>
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
</template>
<script setup lang="ts">
2025-10-24 18:28:35 +08:00
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRoute } from 'vue-router';
2025-10-21 17:59:34 +08:00
import { ElMessage } from 'element-plus';
import {
ArrowLeft,
ArrowRight,
Expand,
Fold,
CircleCheck,
Document,
Edit,
Upload,
Clock,
Download,
InfoFilled
2025-10-21 17:59:34 +08:00
} from '@element-plus/icons-vue';
2025-10-27 17:29:25 +08:00
import { ArticleShowView } from '@/views/public/article';
2025-10-21 17:59:34 +08:00
import { courseApi } from '@/apis/study';
2025-10-27 13:42:34 +08:00
import { learningRecordApi, learningHistoryApi } from '@/apis/study';
2025-10-21 17:59:34 +08:00
import { resourceApi } from '@/apis/resource';
import { useStore } from 'vuex';
import { FILE_DOWNLOAD_URL } from '@/config';
2025-10-28 19:04:35 +08:00
import type { CourseItemVO, LearningRecord, TbLearningHistory } from '@/types';
2025-10-21 17:59:34 +08:00
interface Props {
courseId: string;
chapterIndex?: number;
nodeIndex?: number;
2025-10-24 18:28:35 +08:00
backButtonText?: string;
2025-10-21 17:59:34 +08:00
}
const props = withDefaults(defineProps<Props>(), {
chapterIndex: 0,
2025-10-24 18:28:35 +08:00
nodeIndex: 0,
2025-10-28 19:04:35 +08:00
backButtonText: '返回'
2025-10-21 17:59:34 +08:00
});
const emit = defineEmits<{
'back': [];
}>();
const store = useStore();
2025-10-24 18:28:35 +08:00
const userInfo = computed(() => store.getters['auth/user']);
const route = useRoute();
2025-10-21 17:59:34 +08:00
const loading = ref(false);
2025-10-28 19:04:35 +08:00
const courseItemVO = ref<CourseItemVO | null>(null);
2025-10-21 17:59:34 +08:00
const currentChapterIndex = ref(0);
const currentNodeIndex = ref(0);
const sidebarCollapsed = ref(false);
const activeChapters = ref<number[]>([0]);
const articleData = ref<any>(null);
2025-10-24 18:28:35 +08:00
const contentAreaRef = ref<HTMLElement | null>(null);
2025-10-21 17:59:34 +08:00
// 学习记录
const learningRecord = ref<LearningRecord | null>(null);
const completedNodes = ref<Set<string>>(new Set());
const learningStartTime = ref<number>(0);
const learningTimer = ref<number | null>(null);
2025-10-24 18:28:35 +08:00
const hasScrolledToBottom = ref(false);
const previousNodeKey = ref<string | null>(null);
// 富文本视频跟踪
const totalRichTextVideos = ref(0);
const completedRichTextVideos = ref<Set<number>>(new Set());
2025-10-21 17:59:34 +08:00
2025-10-27 13:42:34 +08:00
// 学习历史记录
const learningHistory = ref<TbLearningHistory | null>(null);
const historyStartTime = ref<number>(0);
const historyTimer = ref<number | null>(null);
2025-10-28 19:04:35 +08:00
// 辅助函数:获取章节的节点列表
function getChapterNodes(chapterIndex: number): CourseItemVO[] {
if (!courseItemVO.value) return [];
const chapter = courseItemVO.value.chapters?.[chapterIndex];
if (!chapter?.chapterID) return [];
return courseItemVO.value.chapterNodes?.[chapter.chapterID] || [];
}
2025-10-21 17:59:34 +08:00
// 当前节点
const currentNode = computed(() => {
2025-10-28 19:04:35 +08:00
const nodes = getChapterNodes(currentChapterIndex.value);
return nodes[currentNodeIndex.value] || null;
2025-10-21 17:59:34 +08:00
});
// 当前进度
const currentProgress = computed(() => {
2025-10-28 19:04:35 +08:00
if (!courseItemVO.value || !courseItemVO.value.chapters) return 0;
2025-10-21 17:59:34 +08:00
let totalNodes = 0;
let completedCount = 0;
2025-10-28 19:04:35 +08:00
courseItemVO.value.chapters.forEach((chapter, chapterIdx) => {
const nodes = getChapterNodes(chapterIdx);
nodes.forEach((node, nodeIdx) => {
2025-10-21 17:59:34 +08:00
totalNodes++;
if (isNodeCompleted(chapterIdx, nodeIdx)) {
completedCount++;
}
});
});
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
if (totalNodes === 0) return 0;
return Math.round((completedCount / totalNodes) * 100);
});
// 是否有上一节
const hasPrevious = computed(() => {
if (currentChapterIndex.value === 0 && currentNodeIndex.value === 0) {
return false;
}
return true;
});
// 是否有下一节
const hasNext = computed(() => {
2025-10-28 19:04:35 +08:00
if (!courseItemVO.value || !courseItemVO.value.chapters) return false;
const chapters = courseItemVO.value.chapters;
const currentChapterNodes = getChapterNodes(currentChapterIndex.value);
2025-10-21 17:59:34 +08:00
// 不是当前章节的最后一个节点
2025-10-28 19:04:35 +08:00
if (currentNodeIndex.value < currentChapterNodes.length - 1) {
2025-10-21 17:59:34 +08:00
return true;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
// 不是最后一章
if (currentChapterIndex.value < chapters.length - 1) {
return true;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
return false;
});
// 当前节点是否完成
const isCurrentNodeCompleted = computed(() => {
return isNodeCompleted(currentChapterIndex.value, currentNodeIndex.value);
});
watch(() => props.courseId, (newId) => {
if (newId) {
loadCourse();
}
}, { immediate: true });
watch(() => [props.chapterIndex, props.nodeIndex], () => {
currentChapterIndex.value = props.chapterIndex || 0;
currentNodeIndex.value = props.nodeIndex || 0;
loadNodeContent();
}, { immediate: true });
2025-10-27 13:42:34 +08:00
watch(currentNode, async () => {
// 保存上一个节点的学习历史记录
if (learningHistory.value) {
await saveHistoryRecord();
stopHistoryTimer();
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
if (currentNode.value) {
loadNodeContent();
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 为新节点创建学习历史记录
await createHistoryRecord();
2025-10-21 17:59:34 +08:00
}
});
onMounted(() => {
// 不在这里启动定时器,等待学习记录加载完成后再启动
// startLearningTimer(); 移到loadLearningRecord和createLearningRecord成功后
2025-10-21 17:59:34 +08:00
});
onBeforeUnmount(() => {
stopLearningTimer();
saveLearningProgress();
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 保存学习历史记录
if (learningHistory.value) {
saveHistoryRecord();
}
stopHistoryTimer();
2025-10-21 17:59:34 +08:00
});
// 加载课程
async function loadCourse() {
loading.value = true;
try {
2025-10-28 19:04:35 +08:00
const res = await courseApi.getCourseProgress(props.courseId);
2025-10-21 17:59:34 +08:00
if (res.success && res.data) {
2025-10-28 19:04:35 +08:00
courseItemVO.value = res.data;
2025-10-21 17:59:34 +08:00
// 确保数据结构完整
2025-10-28 19:04:35 +08:00
if (!courseItemVO.value.chapters) {
courseItemVO.value.chapters = [];
}
if (!courseItemVO.value.chapterNodes) {
courseItemVO.value.chapterNodes = {};
2025-10-21 17:59:34 +08:00
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
// 加载学习记录
await loadLearningRecord();
}
} catch (error) {
console.error('加载课程失败:', error);
ElMessage.error('加载课程失败');
} finally {
loading.value = false;
}
}
// 加载学习记录
async function loadLearningRecord() {
2025-10-24 18:28:35 +08:00
if (!userInfo.value?.id) return;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
try {
2025-10-24 18:28:35 +08:00
const res = await learningRecordApi.getCourseLearningRecord({
userID: userInfo.value.id,
2025-10-21 17:59:34 +08:00
resourceType: 2, // 课程
2025-10-24 18:28:35 +08:00
courseID: props.courseId
2025-10-21 17:59:34 +08:00
});
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
if (res.success && res.dataList && res.dataList.length > 0) {
learningRecord.value = res.dataList[0];
console.log('✅ 学习记录加载成功:', learningRecord.value);
2025-10-24 18:28:35 +08:00
// 从本地存储加载已完成的节点列表
2025-10-21 17:59:34 +08:00
const savedProgress = localStorage.getItem(`course_${props.courseId}_nodes`);
if (savedProgress) {
completedNodes.value = new Set(JSON.parse(savedProgress));
}
// 学习记录加载成功后,启动学习计时器
if (!learningRecord.value.isComplete) {
startLearningTimer();
console.log('⏱️ 学习计时器已启动');
}
2025-10-24 18:28:35 +08:00
} else {
// 没有学习记录,创建新的
await createLearningRecord();
2025-10-21 17:59:34 +08:00
}
} catch (error) {
console.error('加载学习记录失败:', error);
}
}
// 简单的字符串哈希函数
function hashString(str: string): string {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
// 转换为16进制字符串并确保长度一致
return Math.abs(hash).toString(16).padStart(8, '0') + str.substring(0, 8).replace(/[^a-zA-Z0-9]/g, '');
}
// 生成课程学习记录的taskId当没有真实taskId时
function generateCourseTaskId(
courseId: string,
chapterId?: string,
nodeId?: string,
userId?: string
): string {
// 使用简短格式确保不超过50字符SC_{组合hash}
// SC = Self-study Course
const combinedString = `${courseId}_${chapterId || ''}_${nodeId || ''}_${userId || ''}`;
const combinedHash = hashString(combinedString).substring(0, 20);
const courseHash = hashString(courseId).substring(0, 10);
return `SC_${courseHash}_${combinedHash}`; // 长度3 + 10 + 1 + 20 = 34字符
}
2025-10-24 18:28:35 +08:00
// 创建学习记录
async function createLearningRecord() {
if (!userInfo.value?.id) return;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
try {
2025-10-28 19:04:35 +08:00
const currentChapter = courseItemVO.value?.chapters?.[currentChapterIndex.value];
const currentNodeData = currentChapter?.chapterID ?
courseItemVO.value?.chapterNodes?.[currentChapter.chapterID]?.[currentNodeIndex.value] :
null;
const taskId = route.query.taskId as string;
// 如果没有taskId生成一个自学任务ID
const effectiveTaskId = taskId || generateCourseTaskId(
props.courseId,
currentChapter?.chapterID,
currentNodeData?.nodeID,
userInfo.value.id
);
2025-10-24 18:28:35 +08:00
const res = await learningRecordApi.createRecord({
userID: userInfo.value.id,
resourceType: 2, // 课程
courseID: props.courseId,
2025-10-28 19:04:35 +08:00
chapterID: currentChapter?.chapterID,
nodeID: currentNodeData?.nodeID,
taskID: effectiveTaskId
2025-10-24 18:28:35 +08:00
});
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
if (res.success && res.data) {
learningRecord.value = res.data;
console.log('✅ 学习记录创建成功taskID:', effectiveTaskId);
// 学习记录创建成功后,启动学习计时器
startLearningTimer();
console.log('⏱️ 学习计时器已启动');
2025-10-24 18:28:35 +08:00
}
} catch (error) {
console.error('创建学习记录失败:', error);
}
}
2025-10-21 17:59:34 +08:00
// 加载节点内容
async function loadNodeContent() {
if (!currentNode.value) return;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
// 如果是文章资源,加载文章内容
if (currentNode.value.nodeType === 0 && currentNode.value.resourceID) {
try {
const res = await resourceApi.getResourceById(currentNode.value.resourceID);
if (res.success && res.data) {
articleData.value = {
...res.data.resource,
tags: res.data.tags || []
};
}
} catch (error) {
console.error('加载文章失败:', error);
}
} else {
articleData.value = null;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
// 展开当前章节
if (!activeChapters.value.includes(currentChapterIndex.value)) {
activeChapters.value.push(currentChapterIndex.value);
}
}
// 选择节点
2025-10-24 18:28:35 +08:00
async function selectNode(chapterIndex: number, nodeIndex: number) {
// 检查前一个节点是否需要标记完成
if (previousNodeKey.value && (hasScrolledToBottom.value || !hasScrollbar())) {
await markNodeComplete(previousNodeKey.value);
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 切换到新节点
2025-10-21 17:59:34 +08:00
currentChapterIndex.value = chapterIndex;
currentNodeIndex.value = nodeIndex;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 重置滚动状态
hasScrolledToBottom.value = false;
previousNodeKey.value = `${chapterIndex}-${nodeIndex}`;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 滚动到顶部
if (contentAreaRef.value) {
contentAreaRef.value.scrollTop = 0;
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 等待 DOM 更新后初始化视频监听
await nextTick();
initRichTextVideoListeners();
2025-10-21 17:59:34 +08:00
}
// 上一节
function gotoPrevious() {
2025-10-28 19:04:35 +08:00
if (!hasPrevious.value || !courseItemVO.value) return;
2025-10-21 17:59:34 +08:00
if (currentNodeIndex.value > 0) {
currentNodeIndex.value--;
} else {
// 跳到上一章的最后一节
currentChapterIndex.value--;
2025-10-28 19:04:35 +08:00
const prevChapterNodes = getChapterNodes(currentChapterIndex.value);
currentNodeIndex.value = prevChapterNodes.length - 1;
2025-10-21 17:59:34 +08:00
}
}
// 下一节
function gotoNext() {
2025-10-28 19:04:35 +08:00
if (!hasNext.value || !courseItemVO.value) return;
const currentChapterNodes = getChapterNodes(currentChapterIndex.value);
if (currentNodeIndex.value < currentChapterNodes.length - 1) {
2025-10-21 17:59:34 +08:00
currentNodeIndex.value++;
} else {
// 跳到下一章的第一节
currentChapterIndex.value++;
currentNodeIndex.value = 0;
}
}
// 判断节点是否完成
function isNodeCompleted(chapterIndex: number, nodeIndex: number): boolean {
const nodeKey = `${chapterIndex}-${nodeIndex}`;
return completedNodes.value.has(nodeKey);
}
// 开始学习计时
function startLearningTimer() {
learningStartTime.value = Date.now();
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 每10秒保存一次学习进度如果未完成
2025-10-21 17:59:34 +08:00
learningTimer.value = window.setInterval(() => {
2025-10-24 18:28:35 +08:00
// 如果课程已完成,停止定时器
if (learningRecord.value?.isComplete) {
stopLearningTimer();
return;
}
2025-10-21 17:59:34 +08:00
saveLearningProgress();
2025-10-24 18:28:35 +08:00
}, 10000); // 10秒
2025-10-21 17:59:34 +08:00
}
// 停止学习计时
function stopLearningTimer() {
if (learningTimer.value) {
clearInterval(learningTimer.value);
learningTimer.value = null;
}
}
// 保存学习进度
async function saveLearningProgress() {
if (!userInfo.value?.id) {
console.warn('⚠️ 无法保存学习进度:用户信息不存在');
return;
}
if (!learningRecord.value) {
console.warn('⚠️ 无法保存学习进度:学习记录不存在');
return;
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 如果课程已完成,不再保存进度
if (learningRecord.value.isComplete) {
console.log('课程已完成,跳过进度保存');
return;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
const currentTime = Date.now();
const duration = Math.floor((currentTime - learningStartTime.value) / 1000); // 秒
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
try {
2025-10-24 18:28:35 +08:00
const updatedRecord = {
id: learningRecord.value.id,
userID: userInfo.value.id,
resourceType: 2,
resourceID: props.courseId,
2025-10-21 17:59:34 +08:00
duration: (learningRecord.value.duration || 0) + duration,
progress: currentProgress.value,
2025-10-24 18:28:35 +08:00
isComplete: currentProgress.value === 100
};
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
await learningRecordApi.updateRecord(updatedRecord);
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 更新本地记录
learningRecord.value.duration = updatedRecord.duration;
learningRecord.value.progress = updatedRecord.progress;
learningRecord.value.isComplete = updatedRecord.isComplete;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
// 重置开始时间
learningStartTime.value = currentTime;
console.log(`💾 学习进度已保存 - 时长: ${updatedRecord.duration}秒, 进度: ${updatedRecord.progress}%`);
2025-10-21 17:59:34 +08:00
} catch (error) {
console.error('❌ 保存学习进度失败:', error);
2025-10-21 17:59:34 +08:00
}
}
2025-10-24 18:28:35 +08:00
// 标记节点完成
async function markNodeComplete(nodeKey: string) {
if (completedNodes.value.has(nodeKey)) return;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 如果课程已完成,不再标记节点
if (learningRecord.value?.isComplete) {
console.log('课程已完成,跳过节点标记');
return;
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
completedNodes.value.add(nodeKey);
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 保存到本地存储
localStorage.setItem(
`course_${props.courseId}_nodes`,
JSON.stringify(Array.from(completedNodes.value))
);
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 更新学习进度
await saveLearningProgress();
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 如果全部完成,标记课程为完成
if (currentProgress.value === 100) {
await markCourseComplete();
}
}
// 标记课程完成
async function markCourseComplete() {
if (!userInfo.value?.id || !learningRecord.value) return;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
try {
// 使用learningRecord中保存的taskID可能是真实任务ID或生成的自学ID
const taskId = learningRecord.value.taskID || (route.query.taskId as string);
2025-10-24 18:28:35 +08:00
await learningRecordApi.markComplete({
id: learningRecord.value.id,
userID: userInfo.value.id,
resourceType: 2,
resourceID: props.courseId,
taskID: taskId,
2025-10-24 18:28:35 +08:00
progress: 100,
isComplete: true
});
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
ElMessage.success('恭喜你完成了整个课程!');
} catch (error) {
console.error('标记课程完成失败:', error);
}
}
// 检查是否有滚动条
function hasScrollbar(): boolean {
if (!contentAreaRef.value) return false;
return contentAreaRef.value.scrollHeight > contentAreaRef.value.clientHeight;
}
// 处理内容区域滚动
function handleContentScroll(event: Event) {
const target = event.target as HTMLElement;
const scrollTop = target.scrollTop;
const scrollHeight = target.scrollHeight;
const clientHeight = target.clientHeight;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 判断是否滚动到底部留10px容差
if (scrollHeight - scrollTop - clientHeight < 10) {
if (!hasScrolledToBottom.value) {
hasScrolledToBottom.value = true;
// 滚动到底部,标记当前节点完成
const nodeKey = `${currentChapterIndex.value}-${currentNodeIndex.value}`;
markNodeComplete(nodeKey);
}
}
}
2025-10-21 17:59:34 +08:00
// 处理视频进度
function handleVideoProgress(event: Event) {
// 可以在这里记录视频播放进度
const video = event.target as HTMLVideoElement;
const progress = (video.currentTime / video.duration) * 100;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
// 如果播放超过80%,自动标记为完成
if (progress > 80 && !isCurrentNodeCompleted.value) {
// markAsComplete();
}
}
// 处理视频结束
async function handleVideoEnded() {
2025-10-21 17:59:34 +08:00
if (!isCurrentNodeCompleted.value) {
ElMessage.success('视频播放完成,已自动标记为完成');
// 自动标记当前节点为完成
const nodeKey = `${currentChapterIndex.value}-${currentNodeIndex.value}`;
await markNodeComplete(nodeKey);
2025-10-21 17:59:34 +08:00
}
}
2025-10-24 18:28:35 +08:00
// 初始化富文本中的视频监听器
function initRichTextVideoListeners() {
// 使用 setTimeout 确保 DOM 完全渲染
setTimeout(() => {
// 尝试多种选择器查找富文本内容区域
const selectors = [
'.node-content .rich-text-content',
'.content-area .rich-text-content',
'.rich-text-content'
];
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
let richTextContent: Element | null = null;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
for (const selector of selectors) {
richTextContent = document.querySelector(selector);
if (richTextContent) {
break;
}
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
if (!richTextContent) {
return;
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
const videos = richTextContent.querySelectorAll('video');
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
if (videos.length === 0) {
return;
}
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 初始化视频数量和完成状态
totalRichTextVideos.value = videos.length;
completedRichTextVideos.value.clear();
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 监听所有视频的播放结束事件
videos.forEach((video, index) => {
const videoElement = video as HTMLVideoElement;
// 移除旧的监听器,避免重复添加
videoElement.removeEventListener('ended', () => handleRichTextVideoEnded(index));
// 添加新的监听器,传递视频索引
videoElement.addEventListener('ended', () => handleRichTextVideoEnded(index));
});
}, 300); // 延迟 300ms 确保 DOM 完全渲染
}
// 处理富文本视频播放结束
async function handleRichTextVideoEnded(videoIndex: number) {
2025-10-24 18:28:35 +08:00
// 标记该视频已完成
completedRichTextVideos.value.add(videoIndex);
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
const completedCount = completedRichTextVideos.value.size;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
// 检查是否所有视频都已完成
if (completedCount >= totalRichTextVideos.value) {
if (!isCurrentNodeCompleted.value) {
ElMessage.success(`所有视频播放完成 (${totalRichTextVideos.value}/${totalRichTextVideos.value}),已自动标记为完成`);
// 自动标记当前节点为完成
const nodeKey = `${currentChapterIndex.value}-${currentNodeIndex.value}`;
await markNodeComplete(nodeKey);
2025-10-24 18:28:35 +08:00
}
}
}
// 处理文章视频播放完成从ArticleShow组件emit的事件
async function handleArticleVideosCompleted() {
if (!isCurrentNodeCompleted.value) {
console.log('📹 文章中的所有视频播放完成,自动标记节点为完成');
const nodeKey = `${currentChapterIndex.value}-${currentNodeIndex.value}`;
await markNodeComplete(nodeKey);
}
}
2025-10-21 17:59:34 +08:00
// 处理音频进度
function handleAudioProgress(event: Event) {
const audio = event.target as HTMLAudioElement;
const progress = (audio.currentTime / audio.duration) * 100;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
if (progress > 80 && !isCurrentNodeCompleted.value) {
// markAsComplete();
}
}
// 处理音频结束
async function handleAudioEnded() {
2025-10-21 17:59:34 +08:00
if (!isCurrentNodeCompleted.value) {
ElMessage.success('音频播放完成,已自动标记为完成');
// 自动标记当前节点为完成
const nodeKey = `${currentChapterIndex.value}-${currentNodeIndex.value}`;
await markNodeComplete(nodeKey);
2025-10-21 17:59:34 +08:00
}
}
// 判断是否为视频文件
function isVideoFile(url?: string): boolean {
if (!url) return false;
const videoExtensions = ['.mp4', '.webm', '.ogg', '.mov', '.avi'];
return videoExtensions.some(ext => url.toLowerCase().endsWith(ext));
}
// 判断是否为音频文件
function isAudioFile(url?: string): boolean {
if (!url) return false;
const audioExtensions = ['.mp3', '.wav', '.ogg', '.m4a'];
return audioExtensions.some(ext => url.toLowerCase().endsWith(ext));
}
// 获取文件URL
function getFileUrl(fileId?: string): string {
if (!fileId) return '';
return FILE_DOWNLOAD_URL + fileId;
}
// 下载文件
function downloadFile(fileId?: string) {
if (!fileId) return;
window.open(getFileUrl(fileId), '_blank');
}
// 切换侧边栏
function toggleSidebar() {
sidebarCollapsed.value = !sidebarCollapsed.value;
}
// 返回
2025-10-27 13:42:34 +08:00
// ==================== 学习历史记录功能 ====================
// 创建学习历史记录
async function createHistoryRecord() {
2025-10-28 19:04:35 +08:00
if (!userInfo.value?.id || !courseItemVO.value || !currentNode.value) return;
2025-10-27 13:42:34 +08:00
try {
2025-10-28 19:04:35 +08:00
const chapterItem = courseItemVO.value.chapters![currentChapterIndex.value];
const chapter = chapterItem;
2025-10-27 13:42:34 +08:00
const node = currentNode.value;
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
const res = await learningHistoryApi.recordCourseLearn(
userInfo.value.id,
props.courseId,
chapter?.chapterID,
node.nodeID,
0 // 初始时长为0
);
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
if (res.success && res.data) {
learningHistory.value = res.data;
console.log('✅ 课程学习历史记录创建成功:', learningHistory.value);
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 开始计时
startHistoryTimer();
}
} catch (error) {
console.error('❌ 创建课程学习历史记录失败:', error);
}
}
// 开始学习历史计时
function startHistoryTimer() {
historyStartTime.value = Date.now();
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 每30秒保存一次学习历史
historyTimer.value = window.setInterval(() => {
saveHistoryRecord();
}, 30000); // 30秒
}
// 停止学习历史计时
function stopHistoryTimer() {
if (historyTimer.value) {
clearInterval(historyTimer.value);
historyTimer.value = null;
}
}
// 保存学习历史记录
async function saveHistoryRecord() {
if (!userInfo.value?.id || !learningHistory.value) return;
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
const currentTime = Date.now();
const duration = Math.floor((currentTime - historyStartTime.value) / 1000); // 秒
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 如果时长太短小于1秒不保存
if (duration < 1) return;
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
try {
const updatedHistory: TbLearningHistory = {
...learningHistory.value,
duration: (learningHistory.value.duration || 0) + duration,
endTime: new Date().toISOString()
};
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 调用API更新学习历史
const res = await learningHistoryApi.recordLearningHistory(updatedHistory);
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
if (res.success && res.data) {
learningHistory.value = res.data;
console.log(`💾 课程学习历史已保存 - 累计时长: ${learningHistory.value.duration}秒 - 节点: ${currentNode.value?.name}`);
}
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 重置开始时间
historyStartTime.value = currentTime;
} catch (error) {
console.error('❌ 保存课程学习历史失败:', error);
}
}
2025-10-21 17:59:34 +08:00
function handleBack() {
stopLearningTimer();
saveLearningProgress();
2025-10-28 19:04:35 +08:00
2025-10-27 13:42:34 +08:00
// 保存学习历史记录
if (learningHistory.value) {
saveHistoryRecord();
}
stopHistoryTimer();
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
emit('back');
}
</script>
<style lang="scss" scoped>
.course-learning {
min-height: 100vh;
display: flex;
flex-direction: column;
background: #f5f7fa;
}
.learning-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px 24px;
background: #fff;
border-bottom: 1px solid #e4e7ed;
position: sticky;
top: 0;
z-index: 100;
2025-10-24 18:28:35 +08:00
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.header-left {
display: flex;
align-items: center;
gap: 16px;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.course-name {
font-size: 16px;
font-weight: 600;
color: #303133;
}
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.header-right {
.progress-info {
font-size: 14px;
color: #606266;
}
}
}
.learning-container {
display: flex;
flex: 1;
height: calc(100vh - 61px);
2025-10-24 18:28:35 +08:00
position: relative;
}
.float-expand-btn {
position: absolute;
left: 16px;
top: 16px;
z-index: 10;
2025-10-28 19:04:35 +08:00
2025-10-24 18:28:35 +08:00
:deep(.el-button) {
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
2025-10-21 17:59:34 +08:00
}
.chapter-sidebar {
width: 320px;
background: #fff;
border-right: 1px solid #e4e7ed;
overflow-y: auto;
transition: width 0.3s;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
&.collapsed {
width: 0;
overflow: hidden;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.sidebar-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
border-bottom: 1px solid #e4e7ed;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.sidebar-title {
font-size: 16px;
font-weight: 600;
color: #303133;
}
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.chapter-list {
padding: 8px;
}
}
.chapter-item-title {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding-right: 20px;
font-size: 14px;
font-weight: 500;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.chapter-count {
font-size: 12px;
color: #909399;
background: #f5f7fa;
padding: 2px 8px;
border-radius: 10px;
}
}
.node-items {
padding-left: 12px;
}
.node-item-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 12px;
margin: 4px 0;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
&:hover {
background: #f5f7fa;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
&.active {
background: #ecf5ff;
color: #409eff;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
&.completed {
.check-icon {
color: #67c23a;
}
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-item-content {
display: flex;
align-items: center;
gap: 8px;
flex: 1;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-type-icon {
font-size: 16px;
color: #909399;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.check-icon {
font-size: 16px;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-item-name {
font-size: 13px;
color: #606266;
}
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-item-meta {
display: flex;
align-items: center;
gap: 8px;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-duration {
font-size: 12px;
color: #909399;
}
}
}
.content-area {
flex: 1;
overflow-y: auto;
background: #fff;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
&.expanded {
margin-left: 0;
}
}
.loading-container {
padding: 24px;
}
.node-content {
max-width: 900px;
margin: 0 auto;
padding: 24px;
}
.node-header {
margin-bottom: 24px;
padding-bottom: 16px;
border-bottom: 1px solid #e4e7ed;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-title {
font-size: 24px;
font-weight: 600;
color: #303133;
margin: 0 0 12px 0;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.node-meta {
display: flex;
align-items: center;
gap: 12px;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.duration {
display: flex;
align-items: center;
gap: 4px;
font-size: 14px;
color: #606266;
}
}
}
.article-content,
.rich-text-content {
margin-bottom: 24px;
line-height: 1.8;
color: #303133;
}
.rich-text-content {
:deep(img) {
max-width: 100%;
height: auto;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
:deep(video) {
max-width: 100%;
height: auto;
}
}
.file-content {
margin-bottom: 24px;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.video-wrapper,
.audio-wrapper {
display: flex;
justify-content: center;
padding: 24px;
background: #000;
border-radius: 8px;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.video-player {
max-width: 100%;
max-height: 500px;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.audio-player {
width: 100%;
}
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.file-download {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 60px;
background: #f5f7fa;
border-radius: 8px;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.file-icon {
font-size: 64px;
color: #909399;
margin-bottom: 16px;
}
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
p {
margin-bottom: 16px;
color: #606266;
}
}
}
.learning-actions {
display: flex;
justify-content: space-between;
align-items: center;
padding-top: 24px;
border-top: 1px solid #e4e7ed;
2025-10-28 19:04:35 +08:00
2025-10-21 17:59:34 +08:00
.navigation-buttons {
display: flex;
gap: 12px;
}
}
.empty-content {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
min-height: 400px;
}
</style>