CourseDetailPage.vue 38.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 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 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
<template>
  <AppLayout :rightContent="rightContent" :has-title="false">
    <div class="pb-24 mb-6">
      <!-- Course Image -->
      <div class="mb-4">
        <img :src="course?.cover || 'https://cdn.ipadbiz.cn/mlaj/images/default_block.png'" :alt="course?.title"
          class="w-full h-auto" />
      </div>

      <!-- Course Header -->
      <div class="px-4">
        <div style="padding-bottom: 1rem;">
          <div v-if="course?.group_type_title" class="bg-gray-100 rounded-lg p-2 mb-3 inline-block">
            <div class="text-gray-600 text-sm font-semibold">{{ course?.group_type_title }}</div>
          </div>
          <h1 class="text-2xl text-gray-900 font-bold mb-1">{{ course?.title }}</h1>
          <h2 class="text-sm text-gray-500">{{ course?.subtitle }}</h2>
          <div class="mt-4 flex justify-between items-center">
            <div class="flex items-baseline gap-2">
              <template v-if="course?.pay_type !== 'DESIGNATE'">
                <div v-if="course?.price !== '0.00'" class="flex items-baseline">
                  <span class="text-red-500 font-bold text-2xl">¥{{ course?.price }}</span>
                  <!-- <span class="text-gray-500 text-sm ml-1">/人</span> -->
                </div>
                <div v-else class="text-red-500 text-lg font-bold">
                  免费
                </div>
              </template>
              <div v-else class="text-red-500 text-sm font-bold">
                指定学习
              </div>
            </div>
            <div class="text-gray-500 text-sm">
              {{ course?.buy_count }}人订阅
            </div>
          </div>
          <div v-if="course?.expireDate" class="text-xs text-gray-500 mt-3 border-t border-gray-100 pt-3">
            有效期: {{ course?.expireDate || '没有字段' }}
          </div>
        </div>
      </div>

      <!-- Course Main Content -->
      <div class="px-4">
        <!-- Course Details -->
        <!-- <FrostedGlass class="mb-4 p-4 rounded-xl" v-if="course?.introduce">
          <h3 class="text-lg font-bold text-gray-800 mb-3">本课程介绍</h3>
          <p v-html="course?.introduce" class="text-gray-700 whitespace-pre-line"></p>
        </FrostedGlass> -->

        <!-- Tab Navigation -->
        <FrostedGlass class="mb-6 rounded-xl overflow-hidden">
          <div class="border-b border-gray-200">
            <div class="flex">
              <button v-for="(item, index) in curriculumItems" :key="index" @click="activeTab = item.title" :class="[
                'flex-1 py-3 font-medium text-center',
                activeTab === item.title
                  ? 'text-green-600 border-b-2 border-green-600 bg-green-50/50'
                  : 'text-gray-500'
              ]">
                {{ item.title }}
              </button>
            </div>
          </div>

          <!-- Tab Content -->
          <div class="p-4">
            <!-- <div v-if="activeTab === '课程特色'">
              <div v-html="course?.feature"></div>
            </div> -->

            <div v-if="activeTab === '课程介绍'" @click="handleIntroduceClick">
              <!-- <p v-html="course?.introduce" class="text-gray-700 whitespace-pre-line"></p> -->
              <p v-html="course?.introduce" class="text-gray-700"></p>
            </div>

            <div v-if="activeTab === '主讲教师'">
              <div v-for="(item, index) in lecturers" :key="index" class="flex items-start" style="margin-bottom: 1rem;">
                <div class="w-16 h-16 rounded-full overflow-hidden mr-4 flex-shrink-0">
                  <img :src="item?.photo || 'https://cdn.ipadbiz.cn/mlaj/images/default_block.png'" alt="lecturer"
                    class="w-full h-full object-cover" @error="handleImageError" />
                </div>
                <div class="flex-1 min-w-0">
                  <h4 class="font-bold text-gray-900">{{ item?.name }}</h4>
                  <p class="text-sm text-gray-600">{{ item?.educational }}</p>
                  <p class="text-xs text-gray-500 mt-1 break-words">{{ item?.introduction }}</p>
                </div>
              </div>
            </div>

            <div v-if="activeTab === '课程大纲'">
              <div class="space-y-4">
                <div v-for="(item, index) in displayedSchedule" :key="index" class="border-l-2 border-green-500 pl-3" @click="goToStudyDetail(item)">
                  <h4 class="font-medium text-gray-800">{{ item.title }}</h4>
                  <p class="text-sm text-gray-600 mt-1">{{ item.duration }}分钟 · 开课时间: {{ item.schedule_time }}</p>
                </div>
                <div v-if="course?.schedule?.length > 4" class="flex justify-center mt-4">
                  <button @click="toggleSchedule"
                    class="p-2 rounded-full hover:bg-green-50 text-green-600 hover:text-green-700 transition-all duration-300">
                    <van-icon :name="isScheduleExpanded ? 'arrow-up' : 'arrow-down'"
                      class="text-xl transform transition-transform duration-300" />
                  </button>
                </div>
              </div>
            </div>

            <div v-if="activeTab === '打卡互动' && task_list.length > 0">
              <!-- 打卡区域 -->
              <div class="py-4">
                <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>

            <!-- <div v-if="activeTab === '课程亮点'">
              <div class="space-y-3 text-gray-700">
                <div v-html="course?.highlights"></div>
              </div>
            </div> -->

            <!-- <div v-if="activeTab === '学习目标'">
              <div class="space-y-3 text-gray-700">
                <div v-html="course?.learning_goal"></div>
              </div>
            </div> -->
          </div>
        </FrostedGlass>

        <!-- lecturers Introduction -->
        <!-- <FrostedGlass class="mb-6 p-4 rounded-xl" v-if="lecturers.length">
          <h3 class="text-lg font-bold text-gray-800 mb-3">主讲老师</h3>
          <div v-for="(item, index) in lecturers" :key="index" class="flex items-center" style="margin-bottom: 1rem;">
            <div class="w-16 h-16 rounded-full overflow-hidden mr-4">
              <img :src="item?.photo || 'https://cdn.ipadbiz.cn/mlaj/images/default_block.png'" alt="lecturer"
                class="w-full h-full object-cover" @error="handleImageError" />
            </div>
            <div>
              <h4 class="font-bold text-gray-900">{{ item?.name }}</h4>
              <p class="text-sm text-gray-600">{{ item?.educational }}</p>
              <p class="text-xs text-gray-500 mt-1">{{ item?.introduce }}</p>
            </div>
          </div>
        </FrostedGlass> -->

        <!-- Student Reviews -->
        <FrostedGlass class="mb-6 p-4 rounded-xl">
          <div class="flex justify-between items-center mb-3">
            <h3 class="text-lg font-bold text-gray-800">学员评价</h3>
            <!-- 立即评论按钮 - 仅在已购买但未评价时显示 -->
            <van-button
              v-if="isPurchased && !isReviewed"
              @click="showReviewPopup = true"
              size="small"
              round
              color="linear-gradient(to right, #3b82f6, #2563eb)"
              class="shadow-sm text-xs px-4 py-1.5 min-w-[80px] hover:shadow-md transition-all duration-200"
            >
              <van-icon name="edit" size="12" class="mr-1" />
              立即评论
            </van-button>
          </div>
          <div class="flex items-center mb-3">
            <div class="flex items-center mr-2">
              <van-rate v-model="commentScore" readonly allow-half color="#facc15" void-color="#e5e7eb" size="20" />
            </div>
            <div class="text-gray-700">{{ commentScore }} ({{ commentTotal }}条评论)</div>
          </div>

          <div class="space-y-4">
            <div v-for="(item, index) in commentList" :key="index" class="border-b border-gray-100 pb-3">
              <div class="flex justify-between">
                <div class="font-medium text-gray-800">{{ item.name || '匿名用户' }}</div>
                <div class="text-xs text-gray-500">{{ formatDate(item.created_time) }}</div>
              </div>
              <p class="text-sm text-gray-600 mt-1">
                {{ item.note }}
              </p>
            </div>
          </div>
          <button @click="router.push(`/courses/${course?.id}/reviews`)"
            class="w-full text-center text-green-600 mt-3 text-sm">
            查看全部评价
          </button>
        </FrostedGlass>
      </div>

      <!-- Bottom Action Bar -->
      <div class="fixed bottom-16 left-0 right-0 bg-white shadow-lg p-3 flex justify-between items-center">
        <div class="flex space-x-4">
          <!-- <button class="flex flex-col items-center text-gray-500 text-xs">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-6 w-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z"
              />
            </svg>
            分享
          </button> -->
          <button class="flex flex-col items-center text-gray-500 text-xs transition-transform duration-300"
            @click="toggleFavorite" :class="{ 'animate-favorite': isFavorite }">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 transition-transform duration-300"
              :fill="isFavorite ? 'red' : 'none'" viewBox="0 0 24 24" :stroke="isFavorite ? 'red' : 'currentColor'">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M4.318 6.318 a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682 a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318 a4.5 4.5 0 00-6.364 0z" />
            </svg>
            收藏
          </button>
          <!-- <button class="flex flex-col items-center text-gray-500 text-xs" @click="open_consult_dialog">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              class="h-6 w-6"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                stroke-linecap="round"
                stroke-linejoin="round"
                stroke-width="2"
                d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"
              />
            </svg>
            咨询
          </button> -->
        </div>
        <div class="flex items-center">
          <div v-if="!course?.is_buy" class="mr-2">
            <div v-if="course?.price !== '0.00'" class="text-red-500 font-bold">¥{{ course?.price || 0 }}</div>
            <div v-if="course?.price !== '0.00'" class="text-xs text-gray-400 line-through">
              ¥{{ Math.round((course?.price || 0) * 1.2) }}
            </div>
          </div>
          <van-button v-if="!isPurchased" @click="handlePurchase" round block
            color="linear-gradient(to right, #22c55e, #16a34a)" class="shadow-md">
            {{ course?.price !== '0.00' ? '立即' : '免费' }}购买
          </van-button>
          <van-button v-else @click="handleViewCourse" round block
            color="linear-gradient(to right, #22c55e, #16a34a)" class="shadow-md">
            查看课程
          </van-button>
        </div>
      </div>
    </div>

    <!-- Review Popup -->
    <ReviewPopup v-model:show="showReviewPopup" title="立即评价" @submit="handleReviewSubmit" />

    <!-- 打卡弹窗 -->
    <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>&nbsp;&nbsp;&nbsp;&nbsp;
            <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>

    <!-- 咨询弹窗:底部只有关闭按钮,内容支持富文本 -->
    <van-popup
        v-model:show="show_consult_dialog"
        round
        position="bottom"
        :style="{ minHeight: '30%', maxHeight: '80%', width: '100%' }"
    >
        <div class="ConsultPopup p-4">
            <!-- 标题与关闭图标 -->
            <div class="flex justify-between items-center mb-3">
                <h3 class="font-medium">咨询信息</h3>
                <van-icon name="cross" @click="close_consult_dialog" />
            </div>

            <!-- 电话信息:点击直接拨打 -->
            <div class="bg-gray-50 border border-gray-200 rounded-lg p-3 mb-4">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 text-green-500 mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5a2 2 0 012-2h2.28a2 2 0 011.789 1.106l1.152 2.305a2 2 0 01-.42 2.317L9.384 10.09a16.001 16.001 0 006.526 6.526l1.356-1.102a2 2 0 012.317-.42l2.305 1.152A2 2 0 0121 18.72V21a2 2 0 01-2 2h-1a18 18 0 01-17-17V5z" />
                        </svg>
                        <span class="text-gray-700">联系电话</span>
                    </div>
                    <a class="text-green-600 font-medium" :href="`tel:${consult_phone}`" @click.prevent="call_phone">{{ consult_phone }}</a>
                </div>
            </div>

            <!-- 富文本咨询信息:点击复制到剪切板 -->
            <div class="bg-white border border-gray-100 rounded-lg p-3">
                <div class="text-gray-700 text-sm leading-6" v-html="consult_html" @click="copy_consult_info"></div>
                <div class="text-xs text-gray-400 mt-2">提示:点击上方任意文字即可复制咨询内容</div>
            </div>

            <!-- 底部关闭按钮(唯一操作) -->
            <div class="mt-4">
                <button class="w-full bg-gradient-to-r from-green-500 to-green-600 text-white py-2 rounded-lg" @click="close_consult_dialog">关闭</button>
            </div>
        </div>
    </van-popup>
    <van-back-top right="5vw" bottom="25vh" offset="600" />
  </AppLayout>
</template>

<script setup lang="jsx">
import { ref, onMounted, onUnmounted, defineComponent, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCart } from '@/contexts/cart'
import { useAuth } from '@/contexts/auth'
import { useTitle } from '@vueuse/core';
import { wxInfo } from '@/utils/tools';
import { startWxAuth } from '@/router/guards'
import { getAuthInfoAPI } from '@/api/auth'
import { showToast, showDialog, showImagePreview } from 'vant';
import { formatDate } from '@/utils/tools'
import { sharePage } from '@/composables/useShare.js'

import AppLayout from '@/components/layout/AppLayout.vue'
import FrostedGlass from '@/components/ui/FrostedGlass.vue'

// 导入接口
import { getCourseDetailAPI, getGroupCommentListAPI, addGroupCommentAPI } from "@/api/course";
import { addFavoriteAPI, cancelFavoriteAPI } from "@/api/favorite";
import { checkinTaskAPI } from '@/api/checkin';

//
// Open Graph 元标签:进入课程详情页时动态插入,离开页面时移除
//
// 原始 og:description 内容缓存(用于离开页面时恢复)
let original_og_desc_content = null;

/**
 * @function build_og_image_url
 * @description 构建 og:image 地址;若为 cdn.ipadbiz.cn 域名,则追加图片压缩参数。
 * @param {string} src 原始图片地址
 * @returns {string} 处理后的图片地址
 */
function build_og_image_url(src) {
    // 若无地址,直接返回空字符串
    if (!src) return '';
    // 若为指定 CDN 域名,追加压缩参数(遵循项目图片规则)
    if (src.includes('cdn.ipadbiz.cn')) {
        const compress_param = 'imageMogr2/thumbnail/200x/strip/quality/70';
        if (src.includes('?')) {
            if (!src.includes(compress_param)) {
                return src + '&' + compress_param;
            }
        } else {
            return src + '?' + compress_param;
        }
    }
    return src;
}

/**
 * @function set_og_meta
 * @description 在页面 head 中插入或更新 4 个 Open Graph 元标签。
 * @param {Object} payload 载荷对象
 * @param {string} payload.title 主标题(og:title)
 * @param {string} payload.description 副标题/描述(og:description)
 * @param {string} payload.image 图片地址(og:image)
 * @param {string} payload.url 当前页面URL(og:url)
 * @returns {void}
 */
function set_og_meta(payload) {
    const head = document.head || document.getElementsByTagName('head')[0];
    if (!head) return;
    const titleEl = head.querySelector('title');
    // 1) 直接修改 index.html 中现有的 og:description(不新建,避免重复)
    const descMeta = head.querySelector('meta[property="og:description"]');
    if (descMeta) {
        // 首次保存原始内容用于恢复
        if (original_og_desc_content === null) {
            original_og_desc_content = descMeta.getAttribute('content') || '';
        }
        descMeta.setAttribute('content', payload.description || '');
    }

    // 2) 其余标签按需创建(若不存在则插入到 <title> 前)
    const others = [
        { id: 'og-title', property: 'og:title', content: payload.title || '' },
        { id: 'og-image', property: 'og:image', content: build_og_image_url(payload.image || '') },
        { id: 'og-url', property: 'og:url', content: payload.url || window.location.href }
    ];
    others.forEach(item => {
        let meta = head.querySelector(`meta#${item.id}`);
        if (!meta) {
            meta = document.createElement('meta');
            meta.setAttribute('id', item.id);
            meta.setAttribute('property', item.property);
            if (titleEl) {
                head.insertBefore(meta, titleEl);
            } else if (head.firstChild) {
                head.insertBefore(meta, head.firstChild);
            } else {
                head.appendChild(meta);
            }
        }
        meta.setAttribute('content', item.content);
    });
}

/**
 * @function remove_og_meta
 * @description 从页面 head 中移除进入详情页时插入的 Open Graph 元标签。
 * @returns {void}
 */
function remove_og_meta() {
    // 恢复 index.html 中现有的 og:description 原始内容
    const head = document.head || document.getElementsByTagName('head')[0];
    if (head) {
        const descMeta = head.querySelector('meta[property="og:description"]');
        if (descMeta && original_og_desc_content !== null) {
            descMeta.setAttribute('content', original_og_desc_content);
        }
    }
    // 移除运行时创建的其它 OG 标签
    ['og-title', 'og-image', 'og-url', 'og-description'].forEach(id => {
        const meta = document.querySelector(`meta#${id}`);
        if (meta && meta.parentNode) {
            meta.parentNode.removeChild(meta);
        }
    });
}

const $route = useRoute();
const $router = useRouter();

const route = useRoute()
const router = useRouter()
const { currentUser } = useAuth()

const course = ref(null)
const lecturers = ref([])
const activeTab = ref('课程介绍')
// 是否收藏状态
const isFavorite = ref(false)
// 是否已购买状态
const isPurchased = ref(false)
// 是否已评论状态
const isReviewed = ref(false)
const showReviewPopup = ref(false)

// 处理富文本点击事件,实现图片预览
const handleIntroduceClick = (event) => {
  const target = event.target;
  if (target.tagName === 'IMG') {
    // 阻止默认行为(如果需要)
    event.preventDefault();

    // 调用 vant 的图片预览
    showImagePreview({
      images: [target.src],
      closeable: true,
      showIndex: false, // 单张图片不显示索引
    });
  }
};

// 打卡相关状态
const task_list = ref([])
const timeout_task_list = ref([])
const default_list = ref([])
const showTaskList = ref(true)
const showTimeoutTaskList = ref(false)
const showCheckInDialog = ref(false)
const selectedCheckIn = ref(null)
const isCheckingIn = ref(false)
const checkInSuccess = ref(false)

// 咨询弹窗相关状态
/**
 * 展示咨询弹窗的显隐状态
 * @type {import('vue').Ref<boolean>}
 */
const show_consult_dialog = ref(false)

/**
 * 咨询联系电话(Mock 数据)
 * @type {import('vue').Ref<string>}
 */
const consult_phone = ref('400-888-8888')

/**
 * 咨询富文本内容(Mock 数据)
 * 说明:示例中包含来自 cdn.ipadbiz.cn 的图片,带有压缩参数
 * @type {import('vue').Ref<string>}
 */
const consult_html = ref(
    '<p><strong>课程咨询说明:</strong>如需了解课程安排、报名流程、发票开具等信息,请联系课程顾问。</p>' +
    '<p>可通过电话或复制下方咨询信息进行沟通。</p>' +
    '<p><img src="https://cdn.ipadbiz.cn/images/consult_demo.png?imageMogr2/thumbnail/200x/strip/quality/70" alt="咨询示例" style="max-width:100%;border-radius:8px;"/></p>'
)

/**
 * 打开咨询弹窗
 * @returns {void}
 */
const open_consult_dialog = () => {
    show_consult_dialog.value = true
}

/**
 * 关闭咨询弹窗
 * @returns {void}
 */
const close_consult_dialog = () => {
    show_consult_dialog.value = false
}

/**
 * 直接拨打咨询电话
 * @returns {void}
 */
const call_phone = () => {
    const phone = consult_phone.value || ''
    if (phone) {
        window.location.href = `tel:${phone}`
    }
}

/**
 * 将富文本内容转换为纯文本
 * @param {string} html 原始富文本 HTML 字符串
 * @returns {string} 纯文本内容
 */
const strip_html = (html) => {
    const text = (html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
    return text
}

/**
 * 复制咨询富文本信息为纯文本
 * @returns {Promise<void>}
 */
const copy_consult_info = async () => {
    const text = strip_html(consult_html.value)
    try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            await navigator.clipboard.writeText(text)
        } else {
            const textarea = document.createElement('textarea')
            textarea.value = text
            textarea.style.position = 'fixed'
            textarea.style.top = '-1000px'
            document.body.appendChild(textarea)
            textarea.focus()
            textarea.select()
            document.execCommand('copy')
            document.body.removeChild(textarea)
        }
        showToast('咨询信息已复制')
    } catch (err) {
        console.error('复制失败: ', err)
        showToast('复制失败,请稍后重试')
    }
}

const { addToCart, proceedToCheckout } = useCart()


// Handle favorite toggle
// 收藏/取消收藏操作
const toggleFavorite = async () => {
  if (isFavorite.value) {
    const { code, msg } = await cancelFavoriteAPI({
      group_id: course.value.id
    })
    if (code) {
      isFavorite.value = !isFavorite.value
      showToast('取消收藏')
    }
  } else {
    const { code, msg } = await addFavoriteAPI({
      group_id: course.value.id
    })
    if (code) {
      isFavorite.value = !isFavorite.value
      showToast('收藏成功')
    }
  }
}

// Curriculum items
const curriculumItems = computed(() => {
  if (!course.value) return [];

  return [
    { title: '课程介绍', active: activeTab.value === '课程介绍', show: !!course.value.introduce },
    { title: '主讲教师', active: activeTab.value === '主讲教师', show: !!(lecturers.value && lecturers.value.length > 0) },
    { title: '课程大纲', active: activeTab.value === '课程大纲', show: !!(course.value.schedule && course.value.schedule.length > 0) },
    // { title: '课程亮点', active: activeTab.value === '课程亮点', show: !!course.value.highlights },
    // { title: '学习目标', active: activeTab.value === '学习目标', show: !!course.value.learning_goal },
    { title: '打卡互动', active: activeTab.value === '打卡互动', show: !!course.value.is_buy && task_list.value.length > 0 },
  ].filter(item => item.show);
});

// Handle image error
const handleImageError = (e) => {
  e.target.src = ''
}

// Right content component
const RightContent = defineComponent({
  setup() {
    return () => (
      <button class="p-2">
        <svg
          xmlns="http://www.w3.org/2000/svg"
          class="h-6 w-6 text-gray-700"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"
          />
        </svg>
      </button>
    )
  },
})

const rightContent = h(RightContent)

/**
 * @function handlePurchase
 * @description 立即购买操作:
 * 1. 检查登录状态;未登录跳转到登录页。
 * 2. 非微信环境(生产)对非免费课程进行环境拦截提示。
 * 3. 微信环境内检查是否已完成授权;未授权则自动发起一次微信授权流程。
 * 4. 将课程加入购物车并进入结算页。
 * @returns {void}
 */
const handlePurchase = async () => {
  // 检查用户是否已登录
  if (!currentUser.value) {
    showToast('请先登录')
    router.replace({ path: '/login', query: { redirect: $route.fullPath } })
    return
  }

  // 检查是否在微信环境(生产环境下强制要求)
  /**
   * 判断是否为微信内置浏览器环境
   * 非微信环境提示用户在微信内打开;免费课程跳过校验
   */
  const is_free = (course.value?.price === '0.00' || Number(course.value?.price) === 0)
  if (!is_free && !import.meta.env.DEV && !wxInfo().isWeiXin) {
        showToast('请在微信内打开进行购买')
        return
  }

  // 微信环境内授权检查:未授权自动触发一次授权流程
  if (!import.meta.env.DEV && wxInfo().isWeiXin) {
        try {
            const { code, data } = await getAuthInfoAPI();
            if (code && !data.openid_has) {
                showToast('正在进行微信授权,请稍后...')
                await startWxAuth()
                return
            }
        } catch (e) {
            // 探测失败也尝试触发授权
            await startWxAuth()
            return
        }
  }

  if (course.value) {
    // 调试日志:检查course.value.form_url的值
    console.log('CourseDetailPage - course.value.form_url:', course.value.form_url)
    console.log('CourseDetailPage - 完整course数据:', course.value)

    const cartItem = {
      id: course.value.id,
      type: 'course',
      title: course.value.title,
      price: course.value.price,
      imageUrl: course.value.imageUrl,
      form: course.value.form, // 报名关联的表单
      cover: course.value.cover, // 课程封面
    }

    // 只有当form_url存在且不为空时才添加该字段
    if (course.value.form_url && course.value.form_url.trim() !== '') {
      cartItem.form_url = window.location.origin + course.value.form_url // 课程关联的表单的 URL
    }

    // 调试日志:检查传递给addToCart的数据
    console.log('CourseDetailPage - 传递给addToCart的数据:', cartItem)

    addToCart(cartItem)
    proceedToCheckout()
  }
}

// 提交评论操作
const handleReviewSubmit = async (review) => {
  const { code, msg } = await addGroupCommentAPI({
    group_id: course.value?.id,
    note: review.note,
    score: review.rating
  })
  if (code) {
    showToast('评论提交成功')
    isReviewed.value = true
    await fetchCommentList()
  }
}

const commentList = ref([])
const commentScore = ref(0)
const commentTotal = ref(0)

// 获取评论列表
const fetchCommentList = async () => {
  const { code, data } = await getGroupCommentListAPI({
    group_id: course.value?.id,
    page: 0,
    limit: 5
  })
  if (code) {
    commentList.value = data.comment_list
    commentScore.value = data.comment_score || 0
    commentTotal.value = data.comment_count || 0
  }
}

// 初始化
onMounted(async () => {
  const id = route.params.id
  // 调用接口获取课程详情
  const { code, data } = await getCourseDetailAPI({ i: id });
  if (code) {
    const foundCourse = data;
    if (foundCourse) {
      course.value = foundCourse;
      lecturers.value = foundCourse.lecturer;
      isFavorite.value = foundCourse.is_favorite;
      isPurchased.value = foundCourse.is_buy;
      isReviewed.value = foundCourse.is_comment;

      useTitle(`${course.value.title || '课程详情'}`);

      // 设置默认选中的 tab,确保选中的 tab 有内容
      const availableTabs = curriculumItems.value;
      if (availableTabs.length > 0 && !availableTabs.some(item => item.title === activeTab.value)) {
        activeTab.value = availableTabs[0].title;
      }

      // 获取评论列表
      await fetchCommentList()

      // 处理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
              });
          });
      }

      default_list.value = task_list.value;

      // 进入详情页时写入 Open Graph 元标签,提升分享预览效果
      set_og_meta({
          title: course.value?.title || '',
          description: course.value?.subtitle || '',
          image: course.value?.cover || '',
          url: window.location.href
      });
    }
  }
  else {
    // 课程不存在,跳转到课程主页面
    showToast('课程不存在')
    router.push('/courses')
  }

  // TAG: 录入个人信息表单的标记, 进入页面时清理所有info_entry_completed_开头的localStorage标记
  const keysToRemove = []
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i)
    if (key && key.startsWith('info_entry_completed_')) {
      keysToRemove.push(key)
    }
  }
  keysToRemove.forEach(key => {
    localStorage.removeItem(key)
    console.log('清理历史个人信息录入标记:', key)
  })
})

// 离开页面时清理 Open Graph 元标签
onUnmounted(() => {
    remove_og_meta();
})


const isScheduleExpanded = ref(false)

// 计算显示的课程大纲列表
const displayedSchedule = computed(() => {
  if (!course.value?.schedule) return []
  return isScheduleExpanded.value || course.value.schedule.length <= 4
    ? course.value.schedule
    : course.value.schedule.slice(0, 4)
})

// 切换课程大纲展开/收起状态
const toggleSchedule = () => {
  isScheduleExpanded.value = !isScheduleExpanded.value
}

/**
 * 处理查看课程按钮点击
 */
const handleViewCourse = () => {
  // 检查课程审核状态
  if (!course.value.is_approval_enable) {
    showDialog({
      title: '温馨提示',
      message: '购买的课程正在审核中,请稍后再试',
      confirmButtonText: '知道了',
      confirmButtonColor: '#4caf50',
    })
    return;
  }
  router.push(`/profile/studyCourse/${course.value.id}`);
};

// 跳转课程大纲
const goToStudyDetail = (item) => {
  console.warn(course.value);
  // 如果没有购买过, 禁止操作
  if (!course.value.is_buy) {
    return;
  }
  // 检查课程审核状态
  if (!course.value.is_approval_enable) {
    showDialog({
      title: '温馨提示',
      message: '购买的课程正在审核中,请稍后再试',
      confirmButtonText: '知道了',
      confirmButtonColor: '#4caf50',
    })
    return;
  }
  // 检查课程是否在开课时间内, course_start_time 开课时间, course_end_time 停课时间
  if (!course.value.is_in_course_time) {
    showDialog({
      title: '温馨提示',
      message: `请在指定课程时间: ${course.value.course_start_time} - ${course.value.course_end_time}内操作!`,
      confirmButtonText: '知道了',
      confirmButtonColor: '#4caf50',
    })
    return;
  }
  // 跳转详情
  router.push(`/studyDetail/${item.id}`)
}

// 打卡相关方法
/**
 * 处理打卡选择
 * @param {Object} type - 打卡类型对象
 */
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 (!course.value.is_approval_enable) {
    showDialog({
      title: '温馨提示',
      message: '购买的课程正在审核中,请稍后再试',
      confirmButtonText: '知道了',
      confirmButtonColor: '#4caf50',
    })
    return;
  }
  if(!default_list.value.length) {
    showToast('暂无打卡任务');
    return;
  }
  showCheckInDialog.value = true;
};

/**
 * 切换打卡任务类型
 * @param {string} type - 任务类型 ('today' | 'timeout')
 */
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;
}

setTimeout(() => {
  // TAG:微信分享
  // 自定义分享内容
  sharePage({ title: `${course.value.title}`, desc: `${course.value.subtitle}`, imgUrl: course.value.cover });
}, 1000)
</script>

<style lang="less">
.ConsultPopup {
    // 咨询弹窗样式容器(使用 less 层级嵌套)
    h3 {
        // 标题样式
        font-weight: 500;
    }
}
  .animate-favorite {
    animation: favorite-animation 0.5s ease;
  }

@keyframes favorite-animation {
  0% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.3);
  }

  100% {
    transform: scale(1);
  }
}

.van-back-top {
  background-color: #4caf50;
}
</style>