Files
ai_academy/frontend/src/views/training/CourseDetail.vue
T

690 lines
20 KiB
Vue

<template>
<div class="course-detail">
<!-- 页头:返回 + 课程信息 + 我的学习状态 -->
<header class="detail-header">
<div class="detail-title-row">
<t-button variant="text" shape="square" class="detail-back" @click="goBack">
<template #icon>
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>
</template>
</t-button>
<t-tag v-if="course" :theme="course.mode === 'online' ? 'primary' : 'success'" variant="light" size="small" :class="{ 'course-tag-offline': course.mode !== 'online' }">
{{ course.mode === 'online' ? '线上课程' : '线下课程' }}
</t-tag>
<h2 class="detail-name">{{ course?.name || '课程详情' }}</h2>
<t-tag v-if="course" theme="default" variant="outline" size="small">{{ typeText }}</t-tag>
</div>
<div class="detail-meta">
<span v-if="course">学时 {{ course.hours }}<template v-if="course.credits"> · 学分 {{ course.credits }}</template></span>
<span v-if="myTask?.deadline">学习期限:{{ fmtDate(myTask.deadline) }}</span>
<t-tag v-if="taskState" :theme="taskTheme" variant="light" size="small">{{ taskState }}</t-tag>
<span v-if="progressPercent > 0" class="detail-progress-text">学习进度 {{ progressPercent }}%</span>
</div>
<div v-if="materials.length" class="detail-bar" :class="progressPercent >= 95 ? 'is-done' : ''">
<i :style="{ width: `${progressPercent}%` }"></i>
</div>
</header>
<div class="detail-body">
<!-- 课件列表 -->
<aside class="material-list">
<div class="material-list__title">课件 ({{ materials.length }})</div>
<button
v-for="m in materials"
:key="m.id"
type="button"
class="material-item"
:class="{ 'is-active': current?.id === m.id }"
@click="openMaterial(m)"
>
<span class="material-item__icon" :class="`kind-${previewKind(m)}`">{{ kindIcon(m) }}</span>
<span class="material-item__name" :title="m.name">{{ m.name }}</span>
<span class="material-item__percent" :class="{ 'is-done': (progressMap[m.id]?.percent || 0) >= 95 }">
{{ progressMap[m.id]?.percent ? `${progressMap[m.id].percent}%` : '' }}
</span>
</button>
<t-empty v-if="!loading && !materials.length" description="暂无课件" class="material-empty" />
</aside>
<!-- 预览区 -->
<main class="preview-pane">
<t-loading :loading="previewLoading" class="preview-pane__inner" :fullscreen="false">
<DocumentPreview
v-if="current && docBlob"
:source-blob="docBlob"
:file-type="previewKind(current)"
:file-name="current.name"
active
fill-height
/>
<DocumentPreview
v-else-if="current && isDoc(current)"
:knowledge-id="current.knowledge_id"
:file-type="previewKind(current)"
:file-name="current.name"
active
fill-height
/>
<t-empty
v-else-if="current"
class="preview-empty"
description="该课件未上传文件,请联系培训管理员补传"
/>
<t-empty v-else class="preview-empty" description="从左侧选择课件开始学习" />
</t-loading>
</main>
</div>
<!-- 随堂考试(开启随堂考试或绑定题库即可考) -->
<div v-if="course?.exam_enabled || course?.exam_ready" class="panel-box exam-box">
<div class="panel-box__header">
<span class="panel-box__title">随堂考试</span>
<div class="panel-box__actions">
<template v-if="examRecord">
<span class="exam-score" :class="examPassed ? 'is-good' : 'is-bad'">
{{ examRecord.score ?? '—' }} 分
<t-tag :theme="examPassed ? 'success' : 'warning'" variant="light" size="small">
{{ examPassed ? '已通过' : '未通过' }}
</t-tag>
</span>
<t-button v-if="!examPassed" theme="primary" variant="outline" :loading="examLoading" @click="startExam">
重新考试
</t-button>
</template>
<t-button v-else theme="primary" :loading="examLoading" @click="startExam">开始考试</t-button>
</div>
</div>
<p class="exam-hint">考试题目来自课程绑定的题库,及格后完成本课;未通过可反复重考巩固学习。</p>
</div>
<!-- 在线答题(逐题作答:实时统计/题号导航/作答后揭示答案) -->
<QuestionExamDialog
:visible="takeVisible"
:paper="takePaper"
:questions="takeQuestions"
:submitting="submitting"
@update:visible="takeVisible = $event"
@submit="onSubmitExam"
/>
<!-- 交卷结果 -->
<t-dialog v-model:visible="resultVisible" header="考试结果" width="420">
<div class="exam-result">
<div class="exam-result__score" :class="resultPassed ? 'is-good' : 'is-bad'">{{ resultScore }}<span>分</span></div>
<div class="exam-result__line">
及格线 {{ takePaper?.pass_score }} 分 ·
<t-tag :theme="resultPassed ? 'success' : 'warning'" variant="light" size="small">
{{ resultPassed ? '恭喜通过!' : '未通过,可重新考试' }}
</t-tag>
</div>
<div v-if="wrongCount > 0" class="exam-result__wrong">答错 {{ wrongCount }} 题,已计入错题本,可在「学习与错题」中复习</div>
<div class="exam-result__synced">成绩已记录:可在「学习考试 → 我的考试成绩」查看,并计入课程考试状态</div>
</div>
<template #footer>
<t-button theme="primary" @click="resultVisible = false">知道了</t-button>
</template>
</t-dialog>
</div>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin } from 'tdesign-vue-next'
import DocumentPreview from '@/components/document-preview.vue'
import QuestionExamDialog from './components/QuestionExamDialog.vue'
import {
downloadMaterialFile,
getCourse,
getCourseExamPaper,
getMyCourseExamRecord,
listCourseProgress,
listMaterials,
listMyLearningTasks,
saveLearningProgress,
submitExam,
unwrap,
type LearningTask,
type MaterialProgress,
type TrainingCourse,
type TrainingExamRecord,
type TrainingMaterial,
type TrainingPaper,
type TrainingQuestion,
} from '@/api/training'
import { resolvePreviewKind } from '@/utils/filePreview'
const route = useRoute()
const router = useRouter()
const courseId = String(route.params.courseId || '')
const loading = ref(false)
const course = ref<TrainingCourse | null>(null)
const materials = ref<TrainingMaterial[]>([])
const myTask = ref<LearningTask | null>(null)
const progressMap = ref<Record<string, MaterialProgress>>({})
// 预览区状态
const current = ref<TrainingMaterial | null>(null)
const previewLoading = ref(false)
const docBlob = ref<Blob | null>(null)
// 考试状态
const examLoading = ref(false)
const examRecord = ref<TrainingExamRecord | null>(null)
const examPassed = ref(false)
const takeVisible = ref(false)
const takePaper = ref<TrainingPaper | null>(null)
const takeQuestions = ref<TrainingQuestion[]>([])
const submitting = ref(false)
const resultVisible = ref(false)
const resultScore = ref(0)
const resultPassed = ref(false)
const wrongCount = ref(0)
// ---- 课程信息 / 学习状态 ----
const typeText = computed(() => (course.value?.type === 'elective' ? '选修' : '必修'))
const taskState = computed(() => {
const map: Record<string, string> = { done: '已完成', doing: '学习中', overdue: '已逾期', pending: '待学习' }
return myTask.value ? map[myTask.value.status] || '' : ''
})
const taskTheme = computed(() =>
myTask.value?.status === 'done' ? 'success' : myTask.value?.status === 'overdue' ? 'danger' : 'primary')
// 课程整体进度 = 各课件 percent 的平均(有课件才计算)。
const progressPercent = computed(() => {
const list = Object.values(progressMap.value)
if (!list.length) return 0
const sum = list.reduce((n, p) => n + (p.percent || 0), 0)
return Math.round(sum / list.length)
})
// ---- 课件预览 ----
const ext = (name: string) => name.split('.').pop()?.toLowerCase() || ''
const previewKind = (m: TrainingMaterial) => {
if (m.knowledge_id || m.file_key) return String(resolvePreviewKind(ext(m.name)))
return 'unsupported'
}
const isVideo = (m: TrainingMaterial) => previewKind(m) === 'video' || (!m.knowledge_id && !!m.file_key)
const isDoc = (m: TrainingMaterial) => !isVideo(m) && (m.knowledge_id || m.file_key)
const kindIcon = (m: TrainingMaterial) => {
const kind = previewKind(m)
if (isVideo(m)) return '▶'
const map: Record<string, string> = { pdf: 'PDF', docx: 'DOC', pptx: 'PPT', image: 'IMG', excel: 'XLS', text: 'TXT', markdown: 'MD' }
return map[kind] || 'DOC'
}
const stopHeartbeat = () => {
if (docTimer) { clearInterval(docTimer); docTimer = null }
if (videoTimer) { clearInterval(videoTimer); videoTimer = null }
docSeconds = 0
docPercentStep = 0
}
// 打开课件:文档带 knowledge_id 时走知识库流(DocumentPreview 自带拉取);
// 视频/仅 file_key 的课件统一走课件文件流(blob 播放/渲染)。
const openMaterial = async (m: TrainingMaterial) => {
if (current.value?.id === m.id) return
stopHeartbeat()
current.value = m
docBlob.value = null
if (!m.knowledge_id && !m.file_key) return
if (isVideo(m) || !m.knowledge_id) {
previewLoading.value = true
try {
docBlob.value = await downloadMaterialFile(m.id)
if (isVideo(m)) bindVideoHeartbeat()
} catch {
MessagePlugin.error('课件文件加载失败,请稍后重试')
current.value = null
} finally {
previewLoading.value = false
}
return
}
startDocHeartbeat(m)
}
// ---- 学习进度心跳 ----
// 文档:每 30s 按停留档位上报(30→60→95);视频:每 15s 按播放位置上报。
// percent≥95 后端自动完成任务并计积分(SaveLearningProgress)。
let docTimer: ReturnType<typeof setInterval> | null = null
let videoTimer: ReturnType<typeof setInterval> | null = null
let docSeconds = 0
let docPercentStep = 0
const DOC_STEP_SECONDS = 30
const DOC_STEP_PERCENTS = [30, 60, 95]
const reportProgress = async (m: TrainingMaterial, positionSec: number, percent: number) => {
if (!myTask.value || !m) return
try {
await saveLearningProgress(myTask.value.id, m.id, Math.floor(positionSec), Math.min(100, Math.max(0, Math.round(percent))))
const prev = progressMap.value[m.id]
const merged: MaterialProgress = {
material_id: m.id,
position_sec: Math.max(positionSec, prev?.position_sec || 0),
percent: Math.max(Math.round(percent), prev?.percent || 0),
}
progressMap.value = { ...progressMap.value, [m.id]: merged }
} catch {
// 进度上报失败不打断学习,下个心跳再试。
}
}
const startDocHeartbeat = (m: TrainingMaterial) => {
if (!myTask.value) return
docTimer = setInterval(() => {
docSeconds += DOC_STEP_SECONDS
const step = DOC_STEP_PERCENTS[Math.min(docPercentStep, DOC_STEP_PERCENTS.length - 1)]
docPercentStep += 1
void reportProgress(m, docSeconds, step)
}, DOC_STEP_SECONDS * 1000)
}
const startVideoHeartbeat = (m: TrainingMaterial, videoEl: HTMLVideoElement) => {
if (!myTask.value) return
videoTimer = setInterval(() => {
const pct = videoEl.duration > 0 ? (videoEl.currentTime / videoEl.duration) * 100 : 0
void reportProgress(m, videoEl.currentTime, Math.max(pct, 5))
}, 15 * 1000)
}
// DocumentPreview 渲染出的 video 元素挂载后接心跳(video 在预览容器内部)。
const bindVideoHeartbeat = () => {
if (!current.value || !isVideo(current.value)) return
const material = current.value
const tryBind = (retries: number) => {
const el = document.querySelector('.preview-pane video') as HTMLVideoElement | null
if (el) {
startVideoHeartbeat(material, el)
} else if (retries > 0) {
setTimeout(() => tryBind(retries - 1), 500)
}
}
tryBind(10)
}
// ---- 随堂考试 ----
const startExam = async () => {
examLoading.value = true
try {
const data = unwrap<{ paper: TrainingPaper; questions: TrainingQuestion[] }>(await getCourseExamPaper(courseId))
if (!data?.paper) throw new Error('no paper')
takePaper.value = data.paper
takeQuestions.value = data.questions || []
takeVisible.value = true
} catch (e: any) {
const msg = e?.response?.data?.message || e?.message
MessagePlugin.warning(msg || '取卷失败,该课程可能未绑定题库')
} finally {
examLoading.value = false
}
}
const onSubmitExam = async ({ answers }: { answers: Record<string, string> }) => {
if (!takePaper.value) return
submitting.value = true
try {
const record = unwrap<TrainingExamRecord>(await submitExam(takePaper.value.id, answers))
if (!record) throw new Error('submit failed')
const score = record.score ?? 0
const passed = takePaper.value.pass_score > 0 ? score >= takePaper.value.pass_score : score >= (takePaper.value.total_score * 0.6)
resultScore.value = Math.round(score * 100) / 100
resultPassed.value = passed
wrongCount.value = record.wrong_question_ids?.length || 0
takeVisible.value = false
resultVisible.value = true
examRecord.value = record
examPassed.value = passed
} catch (e: any) {
const msg = e?.response?.data?.message || e?.message
MessagePlugin.warning(msg || '交卷失败,请稍后重试')
} finally {
submitting.value = false
}
}
// ---- 加载与生命周期 ----
const fmtDate = (raw: string | null) => (raw ? new Date(raw).toLocaleDateString() : '')
const goBack = () => {
if (window.history.length > 1) router.back()
else router.push('/platform/training/dashboard')
}
const loadAll = async () => {
loading.value = true
try {
const [c, m, t, p, r] = await Promise.all([
getCourse(courseId),
listMaterials(courseId),
listMyLearningTasks().catch(() => null),
listCourseProgress(courseId).catch(() => null),
getMyCourseExamRecord(courseId).catch(() => null),
])
course.value = unwrap<TrainingCourse>(c) || null
materials.value = unwrap<TrainingMaterial[]>(m) || []
const tasks = (t && unwrap<LearningTask[]>(t)) || []
myTask.value = tasks.find((task) => task.course_id === courseId) || null
const progress = (p && unwrap<MaterialProgress[]>(p)) || []
progressMap.value = Object.fromEntries(progress.map((item) => [item.material_id, item]))
const exam = r && unwrap<{ record: TrainingExamRecord | null; passed: boolean }>(r)
examRecord.value = exam?.record || null
examPassed.value = !!exam?.passed
// [2026-11 需求] 进入有课件的课程默认打开第一个课件,免手动从左侧选择
if (materials.value.length) void openMaterial(materials.value[0])
} finally {
loading.value = false
}
}
// 切走/关闭页面停心跳,防泄漏。
onBeforeUnmount(stopHeartbeat)
onMounted(loadAll)
</script>
<style lang="less" scoped>
@import (reference) './training.less';
.course-detail {
.training-page-frame();
display: flex;
flex-direction: column;
gap: 12px;
}
.detail-header {
padding: 4px 0 0;
}
.detail-title-row {
display: flex;
align-items: center;
gap: 10px;
}
.detail-back {
flex-shrink: 0;
}
.detail-name {
margin: 0;
font-size: var(--app-text-xl, 20px);
font-weight: 600;
color: var(--td-text-color-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.detail-meta {
display: flex;
align-items: center;
gap: 14px;
margin: 8px 0 6px;
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
}
.detail-progress-text {
color: var(--td-brand-color);
font-weight: 600;
}
.detail-bar {
height: 6px;
border-radius: var(--app-radius-pill);
background: var(--td-bg-color-component);
overflow: hidden;
max-width: 480px;
i {
display: block;
height: 100%;
border-radius: var(--app-radius-pill);
background: var(--td-brand-color);
transition: width 0.4s ease;
}
&.is-done i {
background: var(--td-success-color);
}
}
.detail-body {
display: flex;
gap: 14px;
min-height: 0;
flex: 1;
}
// ---- 课件列表 ----
.material-list {
width: 260px;
flex-shrink: 0;
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
padding: 10px;
overflow-y: auto;
&__title {
font-size: var(--app-text-md);
font-weight: 600;
color: var(--td-text-color-primary);
padding: 2px 6px 10px;
}
}
.material-item {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 8px;
border: 0;
border-radius: var(--app-radius-sm);
background: transparent;
font: inherit;
text-align: left;
cursor: pointer;
transition: background var(--app-motion-fast) ease;
&:hover {
background: var(--td-bg-color-container-hover);
}
&.is-active {
background: var(--td-brand-color-1, rgba(7, 192, 95, 0.08));
.material-item__name {
color: var(--td-brand-color);
font-weight: 600;
}
}
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: -2px;
}
&__icon {
flex-shrink: 0;
min-width: 34px;
height: 22px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 4px;
font-size: 11px;
font-weight: 700;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
&.kind-video {
color: #fff;
background: var(--td-error-color);
}
}
&__name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
color: var(--td-text-color-primary);
font-size: var(--app-text-md);
}
&__percent {
flex-shrink: 0;
font-size: var(--app-text-sm);
color: var(--td-text-color-secondary);
&.is-done {
color: var(--td-success-color);
font-weight: 600;
}
}
}
.material-empty {
padding: 32px 0;
}
// ---- 预览区 ----
.preview-pane {
flex: 1;
min-width: 0;
min-height: 460px;
background: var(--td-bg-color-container);
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-md);
overflow: hidden;
&__inner {
height: 100%;
display: block;
}
}
.preview-empty {
padding: 96px 0;
}
// ---- 随堂考试 ----
.exam-box {
.training-panel-box();
flex-shrink: 0;
}
.exam-hint {
margin: 0;
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
}
.exam-score {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 600;
font-size: var(--app-text-lg);
&.is-good {
color: var(--td-success-color);
}
&.is-bad {
color: var(--td-warning-color);
}
}
.exam-meta {
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
margin-bottom: 12px;
}
.take-question {
padding: 10px 0;
border-top: 1px solid var(--td-component-stroke);
&__stem {
color: var(--td-text-color-primary);
font-size: var(--app-text-md);
margin-bottom: 8px;
}
&__score {
color: var(--td-text-color-placeholder);
margin-left: 6px;
}
&__options {
display: flex;
flex-direction: column;
gap: 8px;
}
&__opt {
align-items: flex-start;
}
}
// ---- 交卷结果 ----
.exam-result {
text-align: center;
padding: 12px 0;
&__score {
font-size: 44px;
font-weight: 700;
line-height: 1.2;
span {
font-size: var(--app-text-md);
font-weight: 400;
margin-left: 4px;
color: var(--td-text-color-secondary);
}
&.is-good {
color: var(--td-success-color);
}
&.is-bad {
color: var(--td-warning-color);
}
}
&__line {
margin: 10px 0 6px;
color: var(--td-text-color-secondary);
}
&__wrong {
color: var(--td-text-color-secondary);
font-size: var(--app-text-md);
}
&__synced {
margin-top: 8px;
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
}
}
</style>