StudyDetailPage.vue 34.6 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 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
<!--
  * @Date: 2025-04-07
  * @Description: 学习详情页面
-->
<template>
    <div class="study-detail-page bg-gradient-to-b from-green-50/70 to-white/90 min-h-screen pb-20">
        <div v-if="course" class="flex flex-col h-screen">
            <!-- 固定区域:视频播放和标签页 -->
            <div class="fixed top-0 left-0 right-0 z-10 top-wrapper">
                <!-- 视频播放区域 -->
                <div v-if="course.course_type === 'video'" class="w-full relative">
                    <!-- 视频封面和播放按钮 -->
                    <div v-if="!isPlaying" class="relative w-full" :style="{ aspectRatio: '16/9', backgroundColor: courseFile.cover ? 'transparent' : '#000' }">
                        <img v-if="courseFile.cover" :src="courseFile.cover" :alt="course.title" class="w-full h-full object-cover" />
                        <div class="absolute inset-0 flex items-center justify-center cursor-pointer"
                            @click="startPlay">
                            <div
                                class="w-20 h-20 rounded-full bg-black/50 flex items-center justify-center hover:bg-black/70 transition-colors">
                                <font-awesome-icon icon="circle-play" class="text-5xl text-white"
                                    style="font-size: 3rem;" />
                            </div>
                        </div>
                    </div>
                    <!-- 视频播放器 -->
                    <VideoPlayer v-if="isPlaying" ref="videoPlayerRef"
                        :video-url="courseFile?.list?.length ? courseFile['list'][0]['url'] : ''" :autoplay="false"
                        :video-id="courseFile?.list?.length ? courseFile['list'][0]['meta_id'] : ''"
                        :use-native-on-ios="false"
                        @onPlay="handleVideoPlay" @onPause="handleVideoPause" />
                </div>
                <div v-if="course.course_type === 'audio'" class="w-full relative border-b border-gray-200">
                    <!-- 音频播放器 -->
                    <AudioPlayer ref="audioPlayerRef" v-if="audioList.length" :songs="audioList" @play="onAudioPlay"
                        @pause="onAudioPause" />
                </div>
                <!-- 图片列表展示区域 -->
                <div v-if="course.course_type === 'image'" class="w-full relative">
                    <van-swipe class="w-full" :autoplay="0" :show-indicators="true">
                        <van-swipe-item v-for="(item, index) in courseFile?.list" :key="index"
                            @click.native="showImagePreview(index)">
                            <van-image :src="item.url" class="w-full" fit="cover" style="aspect-ratio: 16/9;">
                                <template #image>
                                    <img :src="item.url" class="w-full h-full object-cover" />
                                </template>
                            </van-image>
                        </van-swipe-item>
                    </van-swipe>
                </div>
                <!-- 文件列表展示区域 -->
                <!-- <div v-if="course.course_type === 'file'" class="w-full relative bg-white rounded-lg shadow-sm">
                    <div class="p-4 space-y-3">
                        <div v-for="(item, index) in courseFile?.list" :key="index"
                            class="group hover:bg-gray-50 transition-colors rounded-lg p-3">
                            <div class="flex items-center justify-between space-x-3 px-2">
                                <div class="flex items-center space-x-3 flex-1 min-w-0">
                                    <font-awesome-icon icon="file-alt" class="text-gray-400 text-lg flex-shrink-0" />
                                    <h3 class="text-x font-medium text-gray-900 truncate">{{ item.title }}</h3>
                                </div>
                                <div v-if="item.url.toLowerCase().endsWith('.pdf')"
                                    class="text-x text-blue-600 hover:text-blue-800 hover:underline whitespace-nowrap"
                                    @click="showPdf(item)">查看文件</div>
                                <div v-else @click="downloadFile(item)"
                                    class="text-x text-blue-600 hover:text-blue-800 hover:underline whitespace-nowrap">
                                    下载文件</div>
                            </div>
                        </div>
                    </div>
                </div> -->

                <!-- 默认展示区 -->
                <div v-if="!course.course_type" class="relative" style="border-bottom: 1px solid #e5e7eb;">
                    <div class="h-24 bg-white flex items-center justify-center px-4">
                        <h3 class="text-lg font-medium text-gray-900 truncate">{{ course.title }}</h3>
                    </div>
                </div>
                <!-- 标签页区域 -->
                <div class="px-4 py-3 bg-white" style="position: relative;">
                    <van-tabs v-model:active="activeTab" sticky animated swipeable shrink color="#4caf50"
                        @change="handleTabChange">
                        <van-tab title="介绍" name="intro">
                        </van-tab>
                        <van-tab :title-style="{ 'min-width': '50%' }" name="comments">
                            <template #title>评论({{ commentCount }})</template>
                        </van-tab>
                    </van-tabs>
                    <div v-if="task_list.length > 0" @click="goToCheckin"
                        style="position: absolute; right: 1rem; top: 1.5rem; font-size: 0.875rem; color: #666;">打卡互动
                    </div>
                </div>
            </div>

            <!-- 滚动区域:介绍和评论内容 -->
            <div class="overflow-y-auto flex-1"
                :style="{ paddingTop: topWrapperHeight, height: 'calc(100vh - ' + topWrapperHeight + ')' }">
                <div id="intro" class="py-4 px-4">
                    <h1 class="text-lg font-bold mb-2">{{ course.title }}</h1>
                    <div class="text-gray-500 text-sm flex items-center gap-2">
                        <span>开课时间 {{ course.schedule_time ? dayjs(course.schedule_time).format('YYYY-MM-DD HH:mm:ss') :
                            '暂无'
                            }}</span>
                        <!-- <span class="text-gray-300">|</span> -->
                        <!-- <span>没有字段{{ course.studyCount || 0 }}次学习</span> -->
                    </div>

                    <!-- 学习资料入口 -->
                    <div v-if="course.course_type === 'file' && courseFile?.list && courseFile.list.length > 0"
                        class="bg-white rounded-lg p-4 mb-4 cursor-pointer hover:bg-gray-50 transition-colors mt-4 shadow-sm"
                        @click="showMaterialsPopup = true">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 bg-green-600 rounded-lg flex items-center justify-center">
                                    <van-icon name="notes" class="text-white" size="20" />
                                </div>
                                <div>
                                    <div class="text-base font-medium text-gray-900">学习资料</div>
                                    <div class="text-sm text-gray-500">共{{ courseFile.list.length }}个文件</div>
                                </div>
                            </div>
                            <van-icon name="arrow" class="text-gray-400" />
                        </div>
                    </div>
                </div>

                <div class="h-2 bg-gray-100"></div>
                <!-- 评论区 -->
                <StudyCommentsSection :comment-count="commentCount" :comment-list="commentList"
                    :popup-comment-list="popupCommentList" :popup-finished="popupFinished"
                    :bottom-wrapper-height="bottomWrapperHeight" v-model:showCommentPopup="showCommentPopup"
                    v-model:popupLoading="popupLoading" v-model:popupComment="popupComment" @toggleLike="toggleLike"
                    @popupLoad="onPopupLoad" @submitPopupComment="submitPopupComment"
                    @commentDeleted="handleCommentDeleted" />
            </div>

            <!-- 底部操作栏 -->
            <div
                class="fixed bottom-0 left-0 right-0 bg-white border-t px-4 py-2 flex items-center space-x-4 bottom-wrapper">
                <div class="flex-none flex flex-col items-center gap-1 cursor-pointer active:opacity-80"
                    @click="showCatalog = true">
                    <van-icon name="bars" class="text-lg text-gray-600" />
                    <span class="text-xs text-gray-600">课程目录</span>
                </div>
                <div class="flex-grow flex-1 min-w-0">
                    <!-- <van-field v-model="newComment" rows="1" autosize type="textarea" placeholder="请输入留言"
                        class="bg-gray-100 rounded-lg !p-0">
                        <template #input>
                            <textarea v-model="newComment" rows="1" placeholder="请输入留言"
                                class="w-full h-full bg-transparent outline-none resize-none" />
                        </template>
                    </van-field> -->
                    <van-field v-model="newComment" rows="1" autosize type="textarea" placeholder="请输入评论"
                            class="flex-1 bg-gray-100 rounded-lg" />
                </div>
                <van-button type="primary" size="small" @click="submitComment">发送</van-button>
            </div>
        </div>

        <!-- 图片预览组件 -->
        <van-image-preview v-model:show="showPreview" :images="previewImages" :show-index="false"
            :close-on-click-image="false">
            <template #image="{ src, style, onLoad }">
                <img :src="src" :style="[{ width: '100%' }, style]" @load="onLoad" />
            </template>
            <template #cover>
                <!-- 关闭按钮 -->
                <div class="image-preview-close-btn" @click="closeImagePreview">
                    <van-icon name="cross" size="20" color="#fff" />
                </div>
            </template>
        </van-image-preview>

        <!-- 课程目录弹窗 -->
        <StudyCatalogPopup v-model:showCatalog="showCatalog" :lessons="course_lessons" :course-id="courseId"
            :course-type-maps="course_type_maps" @lessonClick="handleLessonClick" />

        <!-- PDF预览改为独立页面,点击资源时跳转到 /pdfPreview -->

        <!-- Office 文档预览弹窗 -->
        <!--<van-popup v-model:show="officeShow" position="center" round closeable :style="{ height: '80%', width: '90%' }">
            <div class="h-full flex flex-col">
                <div class="p-4 border-b border-gray-200">
                    <h3 class="text-lg font-medium text-center truncate">{{ officeTitle }}</h3>
                </div>
                <div class="flex-1 overflow-auto">
                    <!~~ <OfficeViewer
                        v-if="officeShow && officeUrl && officeFileType"
                        :src="officeUrl"
                        :file-type="officeFileType"
                        height="100%"
                        @rendered="onOfficeRendered"
                        @error="onOfficeError"
                        @retry="onOfficeRetry"
                    /> ~~>
                </div>
            </div>
        </van-popup>-->

        <!-- 音频播放器弹窗 -->
        <van-popup v-model:show="audioShow" position="bottom" round closeable :style="{ height: '60%', width: '100%' }">
            <div class="p-4">
                <h3 class="text-lg font-medium mb-4 text-center">{{ audioTitle }}</h3>
                <AudioPlayer v-if="audioShow && audioUrl" :songs="[{ title: audioTitle, url: audioUrl }]"
                    class="w-full" />
            </div>
        </van-popup>

        <!-- 视频播放器弹窗 -->
        <van-popup v-model:show="videoShow" position="center" round closeable
            :style="{ width: '95%', maxHeight: '80vh' }" @close="stopPopupVideoPlay">
            <div class="p-4">
                <h3 class="text-lg font-medium mb-4 text-center">视频预览</h3>
                <div class="relative w-full bg-black rounded-lg overflow-hidden" style="aspect-ratio: 16/9;">
                    <!-- 视频封面 -->
                    <div v-show="!isPopupVideoPlaying"
                        class="absolute inset-0 bg-black flex items-center justify-center cursor-pointer"
                        @click="startPopupVideoPlay">
                        <div class="w-16 h-16 bg-white bg-opacity-80 rounded-full flex items-center justify-center">
                            <svg class="w-8 h-8 text-black ml-1" fill="currentColor" viewBox="0 0 24 24">
                                <path d="M8 5v14l11-7z" />
                            </svg>
                        </div>
                    </div>
                    <!-- 视频播放器 -->
                    <VideoPlayer v-show="isPopupVideoPlaying" ref="popupVideoPlayerRef" :video-url="videoUrl"
                        :video-id="videoTitle" :autoplay="false" :use-native-on-ios="false" class="w-full h-full" @play="handlePopupVideoPlay"
                        @pause="handlePopupVideoPause" />
                </div>
            </div>
        </van-popup>

        <!-- 打卡弹窗 -->
        <CheckInDialog v-model:show="showCheckInDialog" :items_today="task_list" :items_history="timeout_task_list"
            @check-in-success="handleCheckInSuccess" />

        <!-- 学习资源弹窗 -->
        <StudyMaterialsPopup v-model:showMaterialsPopup="showMaterialsPopup" :files="courseFile?.list || []"
            @openPdf="showPdf" @openAudio="showAudio" @openVideo="showVideo" @openImage="showImage" />
    </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useTitle } from '@vueuse/core';
import VideoPlayer from '@/components/media/VideoPlayer.vue';
import AudioPlayer from '@/components/media/AudioPlayer.vue';
import CheckInDialog from '@/components/checkin/CheckInDialog.vue';
// import OfficeViewer from '@/components/media/OfficeViewer.vue';
import dayjs from 'dayjs';
import { showToast } from 'vant';
import { normalizeCheckinTaskItems } from '@/utils/tools'
import StudyCommentsSection from '@/components/studyDetail/StudyCommentsSection.vue';
import StudyCatalogPopup from '@/components/studyDetail/StudyCatalogPopup.vue';
import StudyMaterialsPopup from '@/components/studyDetail/StudyMaterialsPopup.vue';
import { useStudyComments } from '@/composables/useStudyComments';
import { useStudyRecordTracker } from '@/composables/useStudyRecordTracker';

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

const route = useRoute();
const router = useRouter();
const course = ref(null);

const {
    commentCount,
    commentList,
    newComment,
    showCommentPopup,
    popupComment,
    popupCommentList,
    popupLoading,
    popupFinished,
    refreshComments,
    toggleLike,
    submitComment,
    onPopupLoad,
    submitPopupComment
} = useStudyComments(course);

/**
 * @function handleCommentDeleted
 * @description 删除评论成功后,同步更新评论列表与数量(包含主列表与弹窗列表)
 * @param {number|string} comment_id - 被删除的评论ID
 * @returns {void}
 */
const handleCommentDeleted = (comment_id) => {
    const id = String(comment_id || '')
    if (!id) return

    commentList.value = (commentList.value || []).filter(item => String(item?.id) !== id)
    popupCommentList.value = (popupCommentList.value || []).filter(item => String(item?.id) !== id)
    commentCount.value = Math.max(0, Number(commentCount.value || 0) - 1)
}

const activeTab = ref('intro');
const showCatalog = ref(false);
const isPlaying = ref(false);
const videoPlayerRef = ref(null);
const audioPlayerRef = ref(null);

// 课程目录相关
const course_lessons = ref([]);
const course_type_maps = ref({
    video: '视频',
    audio: '音频',
    image: '图片',
    file: '文件',
});

// 开始播放视频
const startPlay = async () => {
    console.log('StudyDetailPage: startPlay 被调用');
    isPlaying.value = true;

    // 等待 VideoPlayer 组件挂载并初始化完成
    await nextTick();

    // 需要额外等待 VideoPlayer 组件的 handleMounted 完成
    // 使用 setTimeout 确保播放器已经初始化
    setTimeout(() => {
        console.log('StudyDetailPage: videoPlayerRef.value:', videoPlayerRef.value);
        console.log('StudyDetailPage: typeof videoPlayerRef.value?.play:', typeof videoPlayerRef.value?.play);
        if (videoPlayerRef.value) {
            videoPlayerRef.value.play();
        } else {
            console.error('StudyDetailPage: videoPlayerRef.value 不存在');
        }
    }, 300); // 增加延迟,确保播放器初始化完成
};

// 处理视频播放状态
const handleVideoPlay = (video) => {
    isPlaying.value = true;
    // 学习时长埋点开始
    startAction();
};

const handleVideoPause = (video) => {
    // 保持视频播放器可见,只在初始状态显示封面
    // 学习时长埋点结束
    endAction();
};

// 弹窗视频播放控制函数
const startPopupVideoPlay = async () => {
    isPopupVideoPlaying.value = true;
    await nextTick();
    if (popupVideoPlayerRef.value) {
        popupVideoPlayerRef.value.play();
    }
};

const handlePopupVideoPlay = (video) => {
    isPopupVideoPlaying.value = true;
};

const handlePopupVideoPause = (video) => {
    // 保持视频播放器可见,只在初始状态显示封面
};

// 停止弹窗视频播放
const stopPopupVideoPlay = () => {
    console.log('停止弹窗视频播放');
    if (popupVideoPlayerRef.value && typeof popupVideoPlayerRef.value.pause === 'function') {
        popupVideoPlayerRef.value.pause();
    }
    isPopupVideoPlaying.value = false;
};



// 图片预览相关
const showPreview = ref(false);
const previewImages = ref([]);

// 显示图片预览
const showImagePreview = (startPosition) => {
    previewImages.value = courseFile.value?.list?.map(item => item.url) || [];
    showPreview.value = true;
};

// 关闭图片预览
const closeImagePreview = () => {
    showPreview.value = false;
};

/**
 * @function handleCheckInSuccess
 * @description 打卡成功后提示并进行轻反馈
 * @returns {void}
 */
const handleCheckInSuccess = () => {
    // 打卡成功轻提示
    showToast('打卡成功');
};

const audioList = ref([]);

// 设置页面标题
useTitle('学习详情');

const topWrapperHeight = ref(0);
const bottomWrapperHeight = ref(0);

// 标记是否由tab切换触发的滚动
const isTabScrolling = ref(false);

const handleScroll = () => {
    // 如果是由tab切换触发的滚动,不处理
    if (isTabScrolling.value) return;

    const introElement = document.getElementById('intro');
    const commentElement = document.getElementById('comment');
    if (!introElement || !commentElement) return;

    const scrollTop = window.scrollY;
    const commentOffset = commentElement.offsetTop - parseInt(topWrapperHeight.value) - 20; // 20是一个偏移量

    // 根据滚动位置更新activeTab
    if (scrollTop >= commentOffset) {
        activeTab.value = 'comments';
    } else {
        activeTab.value = 'intro';
    }
};

const courseFile = ref({});

/**
 * @function sync_study_course_back_position
 * @description 同步学习课程返回位置
 * @param {string} lesson_id - 当前课程目录项ID
 * @returns {void}
 * 注释:在用户点击目录项时调用,记录当前滚动位置和目录项ID
 */

const sync_study_course_back_position = (lesson_id) => {
    const from_course_id = route.query.from_course_id || '';
    if (!from_course_id) return;

    const key = `study_course_scroll_${from_course_id}`;
    const raw = sessionStorage.getItem(key);

    let payload = null;
    try {
        payload = raw ? JSON.parse(raw) : null;
    } catch (e) {
        payload = null;
    }

    if (!payload || typeof payload !== 'object') {
        payload = { scroll_y: 0, lesson_id: '', saved_at: 0 };
    }

    payload.lesson_id = lesson_id || payload.lesson_id || '';
    payload.saved_at = Date.now();

    sessionStorage.setItem(key, JSON.stringify(payload));
};

watch(
    () => route.params.id,
    (val) => {
        sync_study_course_back_position(val || '');
    },
    { immediate: true }
);

const handleLessonClick = async (lesson) => {
    showCatalog.value = false; // 关闭目录弹窗
    isPlaying.value = false; // 重置播放状态
    // 同步学习课程返回位置
    sync_study_course_back_position(lesson.id);

    // 更新URL地址,不触发页面重新加载
    router.replace({ params: { id: lesson.id } });

    // 重新获取课程数据
    const { code, data } = await getScheduleCourseAPI({ i: lesson.id });
    if (code === 1) {
        course.value = data;
        courseFile.value = data.file;

        // 更新音频列表数据
        if (data.course_type === 'audio' && data.file?.list?.length) {
            audioList.value = data.file.list.map(item => ({
                meta_id: item.meta_id,
                title: item.title || '未命名音频',
                artist: '',
                url: item.url,
                cover: item.cover || 'https://cdn.ipadbiz.cn/mlaj/images/audio_d_cover.jpg'
            }));
        } else {
            audioList.value = [];
        }

        await refreshComments();

        // 重新计算顶部和底部容器的高度
        nextTick(() => {
            const topWrapper = document.querySelector('.top-wrapper');
            const bottomWrapper = document.querySelector('.bottom-wrapper');
            if (topWrapper) {
                topWrapperHeight.value = topWrapper.clientHeight + 'px';
            }
            if (bottomWrapper) {
                bottomWrapperHeight.value = bottomWrapper.clientHeight + 'px';
            }
        });

        // 图片附件或者附件不存在
        // 进入后直接执行学习时长埋点
        if (course.value?.course_type === 'image' || !course.value?.course_type) {
            // 新增记录
            let paramsObj = {
                schedule_id: courseId.value,
            }
            addRecord(paramsObj);
        }
    }
};

// Office 文档预览相关
const officeShow = ref(false);
const officeTitle = ref('');
const officeUrl = ref('');
const officeFileType = ref('');

// 音频播放器相关
const audioShow = ref(false);
const audioTitle = ref('');
const audioUrl = ref('');

// 视频播放器相关
const videoShow = ref(false);
const videoTitle = ref('');
const videoUrl = ref('');
const isPopupVideoPlaying = ref(false); // 弹窗视频播放状态
const popupVideoPlayerRef = ref(null); // 弹窗视频播放器引用

const showPdf = ({ title, url, meta_id }) => {
    // 跳转到PDF预览页面,并带上返回的课程ID和打开资料弹框的标记
    const encodedUrl = encodeURIComponent(url);
    const encodedTitle = encodeURIComponent(title);
    router.replace({ name: 'PdfPreview', query: { url: encodedUrl, title: encodedTitle, returnId: courseId.value, openMaterials: '1' } });
    // 新增记录
    let paramsObj = {
        schedule_id: courseId.value,
        meta_id
    }
    addRecord(paramsObj);
};

/**
 * 显示 Office 文档预览
 * @param {Object} file - 文件对象,包含title、url、meta_id
 */
// const showOfficeDocument = ({ title, url, meta_id }) => {
//     console.log('showOfficeDocument called with:', { title, url, meta_id });

//     // 清理 URL 中的反引号和多余空格
//     const cleanUrl = url.replace(/`/g, '').trim();

//     officeTitle.value = title;
//     officeUrl.value = cleanUrl;
//     officeFileType.value = getOfficeFileType(cleanUrl);

//     console.log('Office document props set:', {
//         title: officeTitle.value,
//         url: officeUrl.value,
//         fileType: officeFileType.value
//     });

//     // 验证 URL 格式
//     try {
//         new URL(cleanUrl);
//         console.log('URL validation passed:', cleanUrl);
//     } catch (error) {
//         console.error('Invalid URL format:', cleanUrl, error);
//         showToast('文档链接格式不正确');
//         return;
//     }

//     officeShow.value = true;

//     // 新增记录
//     let paramsObj = {
//         schedule_id: courseId.value,
//         meta_id
//     }
//     addRecord(paramsObj);
// };

/**
 * 显示音频播放器
 * @param {Object} file - 文件对象,包含title、url、meta_id
 */
const showAudio = ({ title, url, meta_id }) => {
    audioTitle.value = title;
    audioUrl.value = url;
    audioShow.value = true;
    // 新增记录
    let paramsObj = {
        schedule_id: courseId.value,
        meta_id
    }
    addRecord(paramsObj);
};

/**
 * 显示视频播放器
 * @param {Object} file - 文件对象,包含title、url、meta_id
 */
const showVideo = ({ title, url, meta_id }) => {
    videoTitle.value = title;
    videoUrl.value = url;
    videoShow.value = true;
    isPopupVideoPlaying.value = false; // 重置播放状态
    // 新增记录
    let paramsObj = {
        schedule_id: courseId.value,
        meta_id
    }
    addRecord(paramsObj);
};

// 监听弹窗关闭,停止视频播放
watch(videoShow, (newVal) => {
    if (!newVal) {
        // 弹窗关闭时停止视频播放
        stopPopupVideoPlay();
    }
});

/**
 * 显示图片预览
 * @param {Object} file - 文件对象,包含title、url、meta_id
 */
const showImage = ({ title, url, meta_id }) => {
    previewImages.value = [url];
    showPreview.value = true;
    // 新增记录
    let paramsObj = {
        schedule_id: courseId.value,
        meta_id
    }
    addRecord(paramsObj);
};

const onPdfLoad = (load) => {
    // console.warn('pdf加载状态', load);
};

/**
 * PDF下载进度回调
 * @param {number} progress - 下载进度 0-100
 */
const onPdfProgress = (progress) => {
    // console.log('PDF下载进度:', progress);
};

/**
 * PDF下载完成回调
 */
const onPdfComplete = () => {
    // console.log('PDF下载完成');
};

/**
 * Office 文档渲染完成回调
 */
const onOfficeRendered = () => {
    console.log('Office 文档渲染完成');
    // showToast('文档加载完成');
};

/**
 * Office 文档渲染错误回调
 * @param {Error} error - 错误对象
 */
const onOfficeError = (error) => {
    console.error('Office 文档渲染失败:', error);
    showToast('文档加载失败,请重试');
};

/**
 * Office 文档重试回调
 */
const onOfficeRetry = () => {
    console.log('重试加载 Office 文档');
    // 可以在这里添加重新获取文档的逻辑
};

const courseId = computed(() => {
    return route.params.id || '';
});

const { startAction, endAction, addRecord } = useStudyRecordTracker({
    course,
    courseId,
    videoPlayerRef,
    audioPlayerRef
});

onMounted(async () => {
    // 延迟设置topWrapper和bottomWrapper的高度
    setTimeout(() => {
        nextTick(() => {
            const topWrapper = document.querySelector('.top-wrapper');
            const bottomWrapper = document.querySelector('.bottom-wrapper');
            if (topWrapper) {
                topWrapperHeight.value = topWrapper.clientHeight + 'px';
            }
            if (bottomWrapper) {
                bottomWrapperHeight.value = bottomWrapper.clientHeight + 'px';
            }

            // 添加滚动监听
            window.addEventListener('scroll', handleScroll);
        })
    }, 500);

    if (courseId.value) {
        const { code, data } = await getScheduleCourseAPI({ i: courseId.value });
        if (code === 1) {
            course.value = data;
            courseFile.value = data.file;
           // 课程大纲细项打卡互动
            task_list.value = [];
            timeout_task_list.value = [];

            // 处理task_list数据格式
            task_list.value = normalizeCheckinTaskItems(course.value?.task_list)

            // 处理timeout_task_list数据格式
            timeout_task_list.value = normalizeCheckinTaskItems(course.value.data?.timeout_task_list)

            // 音频列表处理
            if (data.course_type === 'audio') {
                audioList.value = data.file.list;
                data.file.list.forEach((item, index) => {
                    item.cover = 'https://cdn.ipadbiz.cn/mlaj/images/audio_d_cover.jpg'
                })
            }

            // 刷新评论列表
            await refreshComments();

            // 获取课程信息
            const detail = await getCourseDetailAPI({ i: course.value.group_id });
            if (detail.code === 1) {
                // 课程目录
                course_lessons.value = detail.data.schedule || [];
            }
        }
        // 图片附件或者附件不存在
        // 进入后直接执行学习时长埋点
        if (course.value.course_type === 'image' || !course.value.course_type) {
            // 新增记录
            let paramsObj = {
                schedule_id: courseId.value,
            }
            addRecord(paramsObj);
        }
    }
});

// 处理标签页切换
const handleTabChange = (name) => {
    // 先更新activeTab值
    activeTab.value = name;

    // 设置标记,表示这是由tab切换触发的滚动
    isTabScrolling.value = true;

    // 然后执行滚动操作
    nextTick(() => {
        const element = document.getElementById(name === 'intro' ? 'intro' : 'comment');
        if (element) {
            const topOffset = element.offsetTop - parseInt(topWrapperHeight.value);
            window.scrollTo({
                top: topOffset,
                behavior: 'smooth'
            });

            // 滚动动画结束后重置标记
            setTimeout(() => {
                isTabScrolling.value = false;
            }, 500); // 假设滚动动画持续500ms
        } else {
            isTabScrolling.value = false;
        }
    });
};

// 在组件卸载时移除滚动监听
onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
    endAction();
});

// 学习资料弹窗状态
const showMaterialsPopup = ref(false);

// 路由参数监听:如果openMaterials=1,则打开学习资料弹框
watch(() => route.query.openMaterials, (val) => {
    if (val === '1' || val === 1 || val === true) {
        showMaterialsPopup.value = true;
    }
}, { immediate: true });

// 监听弹框关闭:关闭时移除URL中的openMaterials参数,防止刷新再次打开
watch(showMaterialsPopup, (val, oldVal) => {
    if (oldVal && !val) {
        const newQuery = { ...route.query };
        delete newQuery.openMaterials;
        router.replace({ path: route.path, query: newQuery });
    }
});


/**
 * 在新窗口中打开文件
 * @param {Object} file - 文件对象,包含title、url、meta_id
 */
// const openFileInNewWindow = ({ title, url, meta_id }) => {
//     // 在新窗口中打开文件URL
//     window.open(url, '_blank');

//     // 记录访问行为
//     let paramsObj = {
//         schedule_id: courseId.value,
//         meta_id
//     }
//     addRecord(paramsObj);
// }

/**
 * 判断文件是否可以在新窗口中打开
 * @param {string} fileName - 文件名
 * @returns {boolean} 是否可以在新窗口中打开
 */
// const canOpenInNewWindow = (fileName) => {
//     if (!fileName || typeof fileName !== 'string') {
//         return false;
//     }

//     const extension = fileName.split('.').pop().toLowerCase();
//     const supportedTypes = ['pdf', 'jpg', 'jpeg', 'png', 'gif', 'mp3', 'aac', 'wav', 'ogg', 'mp4', 'avi', 'mov'];
//     return supportedTypes.includes(extension);
// }


/**
 * 判断文件是否为 Office 文档
 * @param {string} fileName - 文件名
 * @returns {boolean} 是否为 Office 文档
 */
// const isOfficeFile = (fileName) => {
//     if (!fileName || typeof fileName !== 'string') {
//         return false;
//     }

//     const extension = fileName.split('.').pop().toLowerCase();
//     const officeTypes = ['docx', 'xlsx', 'xls', 'pptx'];
//     return officeTypes.includes(extension);
// }

/**
 * 获取 Office 文档类型
 * @param {string} fileName - 文件名
 * @returns {string} 文档类型 (docx, excel, pptx)
 */
// const getOfficeFileType = (fileName) => {
//     if (!fileName || typeof fileName !== 'string') {
//         return '';
//     }

//     const extension = fileName.split('.').pop().toLowerCase();

//     if (extension === 'docx') {
//         return 'docx';
//     } else if (extension === 'xlsx' || extension === 'xls') {
//         return 'excel';
//     } else if (extension === 'pptx') {
//         return 'pptx';
//     }

//     return '';
// }

/**
 * 音频播放事件
 * @param audio 音频对象
 */
const onAudioPlay = (audio, meta_id) => {
    console.log('开始播放音频', audio);
    // 学习时长埋点开始
    startAction({ meta_id });
}

/**
 * 音频暂停事件
 * @param audio 音频对象
 */
const onAudioPause = (audio) => {
    console.log('暂停播放音频', audio);
    // 学习时长埋点结束
    endAction();
}

// 打卡相关状态
const showCheckInDialog = ref(false);
const task_list = ref([]);
const timeout_task_list = ref([]);
// 统一弹窗后不再维护默认列表与切换状态

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

/**
 * 格式化文件大小
 * @param {number} size - 文件大小(字节)
 * @returns {string} 格式化后的文件大小
 */
const formatFileSize = (size) => {
    if (!size) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB'];
    let index = 0;
    let fileSize = size;

    while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024;
        index++;
    }

    return `${fileSize.toFixed(1)} ${units[index]}`;
}
</script>

<style lang="less" scoped>
:deep(.van-cell.van-field) {
    background-color: rgb(244, 244, 244);
}

#pdf-container {
    margin-top: 3rem;
    // 高度100%-3rem
    height: calc(100% - 3rem);
    width: 100%;
    padding: 0px;
}

// 图片预览关闭按钮样式
.image-preview-close-btn {
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;
    width: 50px;
    height: 50px;
    background: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

.image-preview-close-btn:hover {
    background: rgba(0, 0, 0, 0.8);
    transform: translateX(-50%) scale(1.1);
}

.image-preview-close-btn:active {
    transform: translateX(-50%) scale(0.95);
}
</style>