StudyCoursePage.vue
23.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
<!--
* @Date: 2024-01-17
* @Description: 课程详情页面
-->
<template>
<AppLayout :has-title="false">
<div class="study-course-page bg-gradient-to-b from-green-50/70 to-white/90 min-h-screen">
<div v-if="course" class="flex flex-col h-screen">
<!-- 固定区域:课程封面和标签页 -->
<div class=" bg-white">
<!-- 课程封面区域 -->
<van-image class="w-full aspect-video object-cover" :src="course?.cover || 'https://cdn.ipadbiz.cn/mlaj/images/default_block.png'" :alt="course?.title" />
<div class="p-4">
<!-- 标题和价格区域 -->
<div class="flex items-start justify-between gap-3 mb-2">
<h1 class="text-black text-xl font-bold flex-1 min-w-0">{{ course?.title }}</h1>
<div v-if="course?.price !== '0.00'" class="text-orange-500 font-bold text-xl flex-shrink-0">¥{{ course?.price || '0' }}</div>
<div v-else class="text-orange-500 text-base font-semibold"> 免费 </div>
</div>
<div class="flex items-center text-gray-500 text-sm">
<span>已更新 {{ course?.count }} 期</span>
<span class="mx-2">|</span>
<span>{{ course?.buy_count }} 人订阅</span>
</div>
</div>
<div class="h-2 bg-gray-100"></div>
<!-- 标签页区域 -->
<div class="py-3 bg-white transition-all duration-300" :class="{'fixed top-0 left-0 right-0 z-10': isTabFixed}" :style="isTabFixed ? { transform: `translateY(0)` } : {}">
<div class="flex justify-around items-center relative" ref="tabs_container_ref">
<!-- 动态标签:详情、目录,任务存在时显示打卡互动 -->
<div
v-for="(tab, index) in tabs"
:key="tab.name"
:class="['px-4 py-2 cursor-pointer transition-colors relative', activeTab === tab.name ? 'text-green-600 font-medium' : 'text-gray-600']"
@click="handleTabChange(tab.name)"
:ref="el => setTabRef(tab.name, el)"
>
{{ tab.title }}
</div>
<div
class="absolute bottom-0 left-0 bg-green-600 transition-all duration-300 z-20"
:style="indicatorStyle"
></div>
</div>
</div>
</div>
<!-- 滚动区域:详情、目录和互动内容 -->
<div class="overflow-y-auto flex-1"
:style="{ paddingTop: topWrapperHeight, height: 'calc(100vh - ' + topWrapperHeight + ')' }">
<!-- 详情区域 -->
<div id="detail" class="py-4 px-4">
<div v-if="course?.feature">
<div class="text-black text-xl font-bold mb-2">课程特色</div>
<div class="text-gray-700 text-sm leading-relaxed" v-html="course?.feature"></div>
<br />
</div>
<div v-if="course?.highlights">
<div class="text-black text-xl font-bold mb-2">课程亮点</div>
<div class="text-gray-700 text-sm leading-relaxed" v-html="course?.highlights"></div>
<br />
</div>
<div v-if="course?.learning_goal">
<div class="text-black text-xl font-bold mb-2">学习目标</div>
<div class="text-gray-700 text-sm leading-relaxed" v-html="course?.learning_goal"></div>
<br />
</div>
<van-empty v-if="!course?.feature && !course?.highlights && course?.learning_goal" description="暂无详情" />
</div>
<div class="h-2 bg-gray-100"></div>
<!-- 目录区域 -->
<div id="catalog" class="py-4">
<div v-if="course_lessons.length" class="space-y-4">
<div v-for="(lesson, index) in course_lessons" :key="index"
@click="goToStudyDetail(lesson.id)"
class="bg-white p-4 cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-200 relative">
<!-- <div v-if="lesson.progress > 0 && lesson.progress < 100"
class="absolute top-2 right-2 px-2 py-1 bg-green-100 text-green-600 text-xs rounded">
没有字段=>上次看到</div> -->
<div class="text-black text-base font-medium mb-2">{{ lesson.title }}</div>
<div class="flex items-center text-sm text-gray-500">
<span>{{ course_type_maps[lesson.course_type] }}</span>
<span v-if="course_type_maps[lesson.course_type]" class="mx-2">|</span>
<span>开课时间: {{ lesson.schedule_time ? dayjs(lesson.schedule_time).format('YYYY-MM-DD') : '暂无' }}</span>
<span class="mx-2">|</span>
<span v-if="lesson.duration">建议时长: {{ lesson.duration }} 分钟</span>
<!-- <span class="mx-2">|</span> -->
<!-- <span>没有字段=> 已学习{{ lesson?.progress }}%</span> -->
</div>
</div>
</div>
<van-empty v-else description="暂无目录" />
</div>
<div class="h-2 bg-gray-100"></div>
<!-- 互动区域 -->
<div id="interaction" class="py-4 px-4" v-if="task_list.length > 0">
<div class="bg-white rounded-lg p-4 mb-4 cursor-pointer">
<div class="flex items-center justify-between" @click="goToCheckin()">
<div class="flex items-center gap-3">
<van-icon size="3rem" name="calendar-o" class="text-xl text-gray-600" />
<div>
<div class="text-base font-medium">打卡</div>
<div class="text-sm text-gray-500">关联{{ task_list.length }}个打卡</div>
</div>
</div>
<van-icon name="arrow" class="text-gray-400" />
</div>
</div>
</div>
<!-- 添加底部填充区域 -->
<div style="height: 30vh;"></div>
</div>
</div>
<!-- 打卡弹窗 -->
<van-popup
v-model:show="showCheckInDialog"
round
position="bottom"
@close="closeCheckInDialog"
:style="{ minHeight: '30%', maxHeight: '80%', width: '100%' }"
>
<div class="p-4">
<div class="flex justify-between items-center mb-3">
<h3 class="font-medium">
<span :class="{ 'text-green-500' : showTaskList }" @click="toggleTask('today')">今日打卡</span>
<span :class="{ 'text-green-500' : showTimeoutTaskList }" @click="toggleTask('timeout')">历史打卡</span>
</h3>
<van-icon name="cross" @click="showCheckInDialog = false" />
</div>
<div v-if="checkInSuccess" class="bg-green-50 border border-green-200 rounded-lg p-4 text-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-10 w-10 text-green-500 mx-auto mb-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<h4 class="text-green-700 font-medium mb-1">打卡成功!</h4>
</div>
<template v-else>
<div class="grid grid-cols-2 gap-4 py-2">
<button
v-for="checkInType in default_list"
:key="checkInType.id"
class="flex flex-col items-center p-2 rounded-lg border transition-colors
bg-white/70 border-gray-100 hover:bg-white"
:class="{
'bg-green-100 border-green-200': selectedCheckIn?.id === checkInType.id
}"
@click="handleCheckInSelect(checkInType)"
>
<div class="w-12 h-12 rounded-full flex items-center justify-center mb-1 transition-colors
bg-gray-100 text-gray-500"
:class="{
'bg-green-500 text-white': selectedCheckIn?.id === checkInType.id
}"
>
<van-icon v-if="checkInType.task_type === 'checkin'" name="edit" size="1.5rem" :color="checkInType.is_gray ? 'gray' : ''" />
<van-icon v-if="checkInType.task_type === 'upload'" name="tosend" size="1.5rem" :color="checkInType.is_gray ? 'gray' : ''" />
</div>
<span :class="['text-xs', checkInType.is_gray ? 'text-gray-500' : '']">{{ checkInType.name }}</span>
</button>
</div>
<div v-if="selectedCheckIn" class="mt-3">
<button
class="mt-2 w-full bg-gradient-to-r from-green-500 to-green-600 text-white py-2 rounded-lg flex items-center justify-center"
@click="handleCheckInSubmit"
:disabled="isCheckingIn"
>
<template v-if="isCheckingIn">
<div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2"></div>
提交中...
</template>
<template v-else>提交打卡</template>
</button>
</div>
</template>
</div>
</van-popup>
</div>
</AppLayout>
</template>
<script setup>
import { ref, onMounted, nextTick, onUnmounted, computed } from 'vue';
import { useTitle } from '@vueuse/core';
import { useRouter } from "vue-router";
import dayjs from 'dayjs';
import { showToast } from 'vant';
import AppLayout from '@/components/layout/AppLayout.vue';
// 导入接口
import { getCourseDetailAPI } from '@/api/course';
import { checkinTaskAPI } from '@/api/checkin';
const router = useRouter();
// 页面标题
useTitle('课程详情');
// 当前激活的标签页
const activeTab = ref('detail');
const topWrapperHeight = ref(0);
const resizeObserver = ref(null);
// tabs DOM映射
const tabRefs = ref([]);
const tabElMap = ref({});
/**
* 设置标签引用映射
* @param {string} name - 标签名称
* @param {HTMLElement} el - 对应的元素
* 注释:用于根据激活标签定位指示条位置
*/
const setTabRef = (name, el) => {
if (el) {
tabElMap.value[name] = el;
}
};
/**
* 计算标签配置
* @returns {Array<{title:string,name:string}>} 标签数组(含条件展示的打卡互动)
* 注释:当存在打卡任务时,追加“打卡互动”标签
*/
const tabs = computed(() => {
const base = [
{ title: '课程详情', name: 'detail' },
{ title: '课程目录', name: 'catalog' },
];
if (task_list.value && task_list.value.length > 0) {
base.push({ title: '打卡互动', name: 'interaction' });
}
return base;
});
/**
* 当前激活标签的索引
* @returns {number} 当前标签在 tabs 中的索引
* 注释:用于计算底部指示条的宽度和位置
*/
const currentTabIndex = computed(() => {
return tabs.value.findIndex((t) => t.name === activeTab.value);
});
// 标签容器引用与尺寸
const tabs_container_ref = ref(null);
const tabs_container_width = ref(0);
const tabs_resize_observer = ref(null);
/**
* 初始化并监听标签容器宽度
* @returns {void}
* 注释:确保在首次渲染和尺寸变化时能正确计算分段宽度
*/
const initTabsContainerWidth = () => {
nextTick(() => {
const el = tabs_container_ref.value;
if (!el) return;
tabs_container_width.value = el.clientWidth;
if (tabs_resize_observer.value) {
tabs_resize_observer.value.disconnect();
}
tabs_resize_observer.value = new ResizeObserver(() => {
tabs_container_width.value = el.clientWidth;
});
tabs_resize_observer.value.observe(el);
});
};
/**
* 指示条样式计算
* @returns {{width:string, transform:string, height:string}} 指示条宽度与位置样式
* 注释:优先按栏目数量进行分段计算,缺省时回退到DOM测量
*/
const indicatorStyle = computed(() => {
const count = tabs.value.length || 1;
const index = currentTabIndex.value >= 0 ? currentTabIndex.value : 0;
// 优先使用容器分段宽度进行计算
if (tabs_container_width.value > 0 && count > 0) {
const segment = tabs_container_width.value / count;
return {
width: segment + 'px',
transform: `translateX(${segment * index}px)`,
height: '2px',
};
}
// 回退:使用激活标签的实际尺寸
const el = tabElMap.value[activeTab.value];
const width = el ? el.offsetWidth : 0;
const left = el ? el.offsetLeft : 0;
return {
width: width + 'px',
transform: `translateX(${left}px)`,
height: '2px',
};
});
// 计算topWrapperHeight的函数
const updateTopWrapperHeight = () => {
setTimeout(() => {
nextTick(() => {
const topWrapper = document.querySelector('.top-wrapper');
if (topWrapper) {
// 断开之前的observer连接
if (resizeObserver.value) {
resizeObserver.value.disconnect();
}
// 使用 ResizeObserver 监听元素尺寸变化
resizeObserver.value = new ResizeObserver(() => {
topWrapperHeight.value = `${topWrapper.offsetHeight}px`;
});
resizeObserver.value.observe(topWrapper);
}
});
}, 500)
};
const course = ref([]);
const course_lessons = ref([]);
const course_type_maps = ref({
video: '视频',
audio: '音频',
image: '图片',
file: '文件',
})
const task_list = ref([]);
const timeout_task_list = ref([]);
const default_list = ref([]);
const showTaskList = ref(true);
const showTimeoutTaskList = ref(false);
onMounted(async () => {
/**
* 组件挂载时获取课程详情
*/
// 获取课程ID
const courseId = router.currentRoute.value.params.id;
// 调用接口获取课程详情
const { code, data } = await getCourseDetailAPI({ i: courseId });
if (code) {
course.value = data;
task_list.value = [];
timeout_task_list.value = [];
// 处理task_list数据格式
if (data.task_list) {
data.task_list.forEach(item => {
task_list.value.push({
id: item.id,
name: item.title,
task_type: item.task_type,
is_gray: item.is_gray
});
});
}
// 处理timeout_task_list数据格式
if (data.timeout_task_list) {
data.timeout_task_list.forEach(item => {
timeout_task_list.value.push({
id: item.id,
name: item.title,
task_type: item.task_type,
is_gray: item.is_gray
});
});
}
course_lessons.value = data.schedule || [];
default_list.value = task_list.value;
showTaskList.value = true;
}
else {
// 课程不存在,跳转到课程主页面
showToast('课程不存在')
router.go(-1);
}
/**
* 初始化时计算topWrapperHeight
*/
// 添加滚动监听
window.addEventListener('scroll', handleScroll);
// 添加窗口大小变化监听
window.addEventListener('resize', updateTopWrapperHeight);
// 确保在组件挂载后计算高度
updateTopWrapperHeight();
// 初始化标签容器宽度监听
initTabsContainerWidth();
});
// 在组件卸载时移除监听器
onUnmounted(() => {
window.removeEventListener('scroll', handleScroll);
window.removeEventListener('resize', updateTopWrapperHeight);
// 组件卸载时取消监听
if (resizeObserver.value) {
resizeObserver.value.disconnect();
resizeObserver.value = null;
}
// 取消标签容器监听
if (tabs_resize_observer.value) {
tabs_resize_observer.value.disconnect();
tabs_resize_observer.value = null;
}
});
// 处理滚动事件
// 在script setup中添加
const isTabFixed = ref(false);
const tabOriginalTop = ref(0);
onMounted(async () => {
setTimeout(() => {
nextTick(() => {
// 记录标签页原始位置
const tabElement = document.querySelector('.py-3.bg-white');
if (tabElement) {
tabOriginalTop.value = tabElement.getBoundingClientRect().top + window.scrollY;
}
})
}, 500);
});
// 防抖函数
const debounce = (fn, delay) => {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
};
// 修改handleScroll函数
/**
* 处理滚动联动,更新标签激活态
* 注释:当互动区域不存在时,仅在详情与目录之间联动
*/
const handleScroll = debounce(() => {
const detailElement = document.getElementById('detail');
const catalogElement = document.getElementById('catalog');
const interactionElement = document.getElementById('interaction');
const tabElement = document.querySelector('.py-3.bg-white');
if (!detailElement || !catalogElement || !tabElement) return;
const currentScrollY = window.scrollY;
isTabFixed.value = currentScrollY >= tabOriginalTop.value;
const scrollTop = window.scrollY;
const tabHeight = tabElement.offsetHeight;
const buffer = 50; // 缓冲区域
// 计算各区域顶部位置(互动不存在则设为无穷大)
const detailTop = detailElement.offsetTop - tabHeight - buffer;
const catalogTop = catalogElement.offsetTop - tabHeight - buffer;
const interactionTop = interactionElement ? (interactionElement.offsetTop - tabHeight - buffer) : Infinity;
// 页面高度与底部判断
const scrollHeight = document.documentElement.scrollHeight;
const clientHeight = document.documentElement.clientHeight;
const isAtBottom = scrollTop + clientHeight >= scrollHeight - buffer;
// 联动判断
if (scrollTop <= detailTop) {
activeTab.value = 'detail';
} else if (interactionElement && (isAtBottom || scrollTop >= interactionTop)) {
activeTab.value = 'interaction';
} else if (scrollTop >= catalogTop && scrollTop < interactionTop) {
activeTab.value = 'catalog';
} else if (scrollTop >= detailTop && scrollTop < catalogTop) {
activeTab.value = 'detail';
}
}, 100);
// 处理标签页切换
// 在script setup中添加
const previousTab = ref('detail');
const getTransitionTiming = (current, previous) => {
const tabOrder = { detail: 0, catalog: 1, interaction: 2 };
return tabOrder[current] > tabOrder[previous] ? 'cubic-bezier(0.4, 0, 0.2, 1)' : 'cubic-bezier(0.4, 0, 0.2, 1)';
};
// 修改handleTabChange函数
const handleTabChange = (name) => {
previousTab.value = activeTab.value;
activeTab.value = name; // 立即更新activeTab的值
let offset = 100; // 调整偏移量, 配合目录的高度
nextTick(() => {
const element = document.getElementById(name);
if (element) {
const topOffset = element.offsetTop - offset - parseInt(topWrapperHeight.value);
window.scrollTo({
top: topOffset,
behavior: 'smooth'
});
}
});
};
const goToStudyDetail = (lessonId) => {
router.push(`/studyDetail/${lessonId}`);
};
// 打卡相关状态
const showCheckInDialog = ref(false);
const selectedCheckIn = ref(null);
const isCheckingIn = ref(false);
const checkInSuccess = ref(false);
// 处理打卡选择
const handleCheckInSelect = (type) => {
if (type.is_gray && type.task_type === 'checkin') {
showToast('您已经完成了今天的打卡');
return;
}
if (type.task_type === 'upload') {
router.push({
path: '/checkin/index',
query: {
id: type.id
}
});
showCheckInDialog.value = false;
return;
} else {
selectedCheckIn.value = type;
}
};
// 处理打卡提交
const handleCheckInSubmit = async () => {
if (!selectedCheckIn.value) {
showToast('请选择打卡项目');
return;
}
isCheckingIn.value = true;
try {
const { code } = await checkinTaskAPI({ task_id: selectedCheckIn.value.id });
if (code) {
checkInSuccess.value = true;
// 重置表单
setTimeout(() => {
checkInSuccess.value = false;
selectedCheckIn.value = null;
showCheckInDialog.value = false;
}, 1500);
}
} catch (error) {
console.error('打卡失败:', error);
showToast('打卡失败,请重试');
} finally {
isCheckingIn.value = false;
}
};
const goToCheckin = () => {
if(!default_list.value.length) {
showToast('暂无打卡任务');
return;
}
showCheckInDialog.value = true;
};
const toggleTask = (type) => {
if(type === 'today') {
showTaskList.value = true;
showTimeoutTaskList.value = false;
default_list.value = task_list.value;
} else {
showTaskList.value = false;
showTimeoutTaskList.value = true;
default_list.value = timeout_task_list.value;
}
}
const closeCheckInDialog = () => {
showCheckInDialog.value = false;
// 切换到今日任务
showTaskList.value = true;
showTimeoutTaskList.value = false;
default_list.value = task_list.value;
}
</script>
<style scoped>
.study-course-page {
min-height: 100vh;
}
.course-header {
height: auto;
}
.course-tabs {
background-color: #fff;
}
.course-catalog {
background-color: #fff;
}
</style>