StudyCoursePage.vue 15.3 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
<!--
 * @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="bg-white">
            <van-image class="w-full 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 ref="tabs_wrapper_ref" class="py-3 bg-white sticky top-0 z-10">
                <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 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 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>
                        </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>

        <!-- 打卡弹窗:统一使用 CheckInDialog 组件 -->
        <CheckInDialog
            v-model:show="showCheckInDialog"
            :items_today="task_list"
            :items_history="timeout_task_list"
            @check-in-success="handleCheckInSuccess"
        />
    </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 CheckInDialog from '@/components/ui/CheckInDialog.vue';

// 导入接口
import { getCourseDetailAPI } from '@/api/course';

const router = useRouter();

// 页面标题
useTitle('课程详情');

// 当前激活的标签页
const activeTab = ref('detail');
// 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);
const tabs_wrapper_ref = ref(null);
const tabs_wrapper_height = ref(0);
const tabs_wrapper_resize_observer = ref(null);
const is_tab_scrolling = ref(false);

/**
 * 初始化并监听标签容器宽度
 * @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',
    };
});

const updateTabsWrapperHeight = () => {
    nextTick(() => {
        const el = tabs_wrapper_ref.value;
        if (!el) return;
        tabs_wrapper_height.value = el.offsetHeight || 0;
        if (tabs_wrapper_resize_observer.value) {
            tabs_wrapper_resize_observer.value.disconnect();
        }
        tabs_wrapper_resize_observer.value = new ResizeObserver(() => {
            tabs_wrapper_height.value = el.offsetHeight || 0;
        });
        tabs_wrapper_resize_observer.value.observe(el);
    });
};

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([]);

onMounted(async () => {
    /**
     * 组件挂载时获取课程详情
     */
    // 获取课程ID
    const courseId = router.currentRoute.value.params.id;
    // 调用接口获取课程详情
    const { code, data } = await getCourseDetailAPI({ i: courseId });
    if (code === 1) {
        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,
                    is_finish: item.is_finish,
                    checkin_subtask_id: item.checkin_subtask_id,
                });
            });
        }

        // 处理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,
                    is_finish: item.is_finish,
                    checkin_subtask_id: item.checkin_subtask_id,
                });
            });
        }

        course_lessons.value = data.schedule || [];
    }
    else {
        // 课程不存在,跳转到课程主页面
        showToast('课程不存在')
        router.go(-1);
    }
    /**
     * 初始化滚动监听与标签高度
     */
    window.addEventListener('scroll', handleScroll, { passive: true });
    window.addEventListener('resize', updateTabsWrapperHeight);
    updateTabsWrapperHeight();
    // 初始化标签容器宽度监听
    initTabsContainerWidth();
    handleScroll();
});

// 在组件卸载时移除监听器
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
    window.removeEventListener('resize', updateTabsWrapperHeight);
    // 取消标签容器监听
    if (tabs_resize_observer.value) {
        tabs_resize_observer.value.disconnect();
        tabs_resize_observer.value = null;
    }
    if (tabs_wrapper_resize_observer.value) {
        tabs_wrapper_resize_observer.value.disconnect();
        tabs_wrapper_resize_observer.value = null;
    }
});

// 防抖函数
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(() => {
    if (is_tab_scrolling.value) return;

    const buffer = 20;
    const offset_top = (tabs_wrapper_height.value || 0) + buffer;
    const current_scroll = window.scrollY + offset_top;

    const sections = tabs.value
        .map((t) => {
            const el = document.getElementById(t.name);
            if (!el) return null;
            const rect = el.getBoundingClientRect();
            const top = rect.top + window.scrollY;
            return { name: t.name, top };
        })
        .filter(Boolean)
        .sort((a, b) => a.top - b.top);

    if (!sections.length) return;

    const doc_height = document.documentElement.scrollHeight;
    const win_height = window.innerHeight;
    const is_at_bottom = window.scrollY + win_height >= doc_height - buffer;

    if (is_at_bottom) {
        activeTab.value = sections[sections.length - 1].name;
        return;
    }

    let matched = sections[0].name;
    for (let i = 0; i < sections.length; i++) {
        if (current_scroll >= sections[i].top) {
            matched = sections[i].name;
        } else {
            break;
        }
    }
    activeTab.value = matched;
}, 100);


// 处理标签页切换
// 在script setup中添加
const previousTab = ref('detail');

// 修改handleTabChange函数
const handleTabChange = (name) => {
    previousTab.value = activeTab.value;
    activeTab.value = name; // 立即更新activeTab的值
    is_tab_scrolling.value = true;
    nextTick(() => {
        const element = document.getElementById(name);
        if (element) {
            const rect = element.getBoundingClientRect();
            const buffer = 10;
            const offset_top = (tabs_wrapper_height.value || 0) + buffer;
            const topOffset = Math.max(0, rect.top + window.scrollY - offset_top);
            window.scrollTo({ top: topOffset, behavior: 'smooth' });
            setTimeout(() => {
                is_tab_scrolling.value = false;
            }, 500);
        } else {
            is_tab_scrolling.value = false;
        }
    });
};

const goToStudyDetail = (lessonId) => {
    router.push(`/studyDetail/${lessonId}`);
};

// 打卡相关状态
const showCheckInDialog = ref(false);

// 处理打卡选择
const goToCheckin = () => {
    if(!(task_list.value.length || timeout_task_list.value.length)) {
        showToast('暂无打卡任务');
        return;
    }
    showCheckInDialog.value = true;
};

/**
 * 处理打卡成功
 * 注释:统一弹窗触发成功事件后,页面提示成功。
 */
const handleCheckInSuccess = () => {
    showToast('打卡成功');
}
</script>

<style scoped>
.study-course-page {
    min-height: 100vh;
}

.course-header {
    height: auto;
}

.course-tabs {
    background-color: #fff;
}

.course-catalog {
    background-color: #fff;
}
</style>