StudyDetailPage.vue 75 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 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
<!--
  * @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="aspect-ratio: 16/9;">
                        <img :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-24 h-24 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-show="isPlaying" ref="videoPlayerRef"
                        :video-url="courseFile?.list?.length ? courseFile['list'][0]['url'] : ''" :autoplay="false"
                        :video-id="courseFile?.list?.length ? courseFile['list'][0]['meta_id'] : ''"
                        @onPlay="handleVideoPlay" @onPause="handleVideoPause" />
                </div>
                <div v-if="course.course_type === 'audio'" class="w-full relative"
                    style="border-bottom: 1px solid #F3F4F6;">
                    <!-- 音频播放器 -->
                    <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 @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 @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"
                        @click="showMaterialsPopup = true">
                        <div class="flex items-center justify-between">
                            <div class="flex items-center gap-3">
                                <div class="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                                    <van-icon name="notes" class="text-green-600" 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>

                <div id="comment" class="py-4 px-4 space-y-4" :style="{ paddingBottom: bottomWrapperHeight }">
                    <div class="flex justify-between items-center mb-4">
                        <div class="text-gray-900 font-medium text-sm">评论 ({{ commentCount }})</div>
                        <div class="text-gray-500 cursor-pointer text-sm" @click="showCommentPopup = true">查看更多</div>
                    </div>
                    <!-- 显示几条评论 -->
                    <div v-for="comment in commentList" :key="comment.id"
                        class="border-b border-gray-100 last:border-b-0 py-4">
                        <div class="flex">
                            <img :src="comment.avatar || 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'"
                                class="w-10 h-10 rounded-full flex-shrink-0" style="margin-right: 0.5rem;" />
                            <div class="flex-1 ml-3">
                                <div class="flex justify-between items-center mb-1">
                                    <span class="font-medium text-gray-900">{{ comment.name }}</span>
                                    <div class="flex items-center space-x-1">
                                        <span class="text-sm text-gray-500">{{ comment.like_count }}</span> &nbsp;
                                        <van-icon :name="comment.is_like ? 'like' : 'like-o'"
                                            :class="{ 'text-red-500': comment.is_like, 'text-gray-400': !comment.is_like }"
                                            @click="toggleLike(comment)" class="text-lg cursor-pointer" />
                                    </div>
                                </div>
                                <p class="text-gray-700 text-sm mb-1">{{ comment.note }}</p>
                                <div class="text-gray-400 text-xs">{{ formatDate(comment.updated_time) }}</div>
                            </div>
                        </div>
                    </div>
                    <van-popup v-model:show="showCommentPopup" position="bottom" round closeable safe-area-inset-bottom
                        style="height: 80%">
                        <div class="flex flex-col h-full">
                            <!-- 固定头部 -->
                            <div class="flex-none px-4 py-3 border-b bg-white sticky top-0 z-10">
                                <div class="text-lg font-medium">全部评论 ({{ commentCount }})</div>
                            </div>

                            <!-- 可滚动的评论列表 -->
                            <div class="flex-1 overflow-y-auto">
                                <van-list v-model:loading="popupLoading" :finished="popupFinished"
                                    finished-text="没有更多评论了" @load="onPopupLoad" class="px-4 py-2 pb-16">
                                    <div v-for="comment in popupCommentList" :key="comment.id"
                                        class="border-b border-gray-100 last:border-b-0 py-4">
                                        <div class="flex">
                                            <img :src="comment.avatar || 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'"
                                                class="w-10 h-10 rounded-full flex-shrink-0"
                                                style="margin-right: 0.5rem;" />
                                            <div class="flex-1 ml-3">
                                                <div class="flex justify-between items-center mb-1">
                                                    <span class="font-medium text-gray-900">{{ comment.name }}</span>
                                                    <div class="flex items-center space-x-1">
                                                        <span class="text-sm text-gray-500">{{ comment.like_count
                                                        }}</span>
                                                        &nbsp;
                                                        <van-icon :name="comment.is_like ? 'like' : 'like-o'"
                                                            :class="{ 'text-red-500': comment.is_like, 'text-gray-400': !comment.is_like }"
                                                            @click="toggleLike(comment)"
                                                            class="text-lg cursor-pointer" />
                                                    </div>
                                                </div>
                                                <p class="text-gray-700 text-sm mb-1">{{ comment.note }}</p>
                                                <div class="text-gray-400 text-xs">{{ formatDate(comment.updated_time)
                                                }}</div>
                                            </div>
                                        </div>
                                    </div>
                                </van-list>
                            </div>

                            <!-- 固定底部输入框 -->
                            <div class="flex-none border-t px-4 py-2 bg-white fixed bottom-0 left-0 right-0 z-10">
                                <div class="flex items-center space-x-2">
                                    <van-field v-model="popupComment" rows="1" autosize type="textarea"
                                        placeholder="请输入评论" class="flex-1 bg-gray-100 rounded-lg" />
                                    <van-button type="primary" size="small" @click="submitPopupComment">发送</van-button>
                                </div>
                            </div>
                        </div>
                    </van-popup>
                </div>
            </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>
                </div>
                <van-button type="primary" size="small" @click="submitComment">发送</van-button>
            </div>
        </div>

        <!-- 图片预览组件 -->
        <van-image-preview
            v-model:show="showPreview"
            :images="previewImages"
            :close-on-click-image="true"
            :show-index="true"
            closeable
        >
            <template #image="{ src, style, onLoad }">
                <img :src="src" :style="[{ width: '100%' }, style]" @load="onLoad" />
            </template>
        </van-image-preview>

        <!-- 课程目录弹出层 -->
        <van-popup v-model:show="showCatalog" position="bottom" round closeable safe-area-inset-bottom
            style="height: 80%">
            <div class="flex flex-col h-full">
                <!-- 固定头部 -->
                <div class="flex-none px-4 py-3 border-b bg-white sticky top-0 z-10">
                    <div class="text-lg font-medium">课程目录</div>
                </div>

                <!-- 可滚动的目录列表 -->
                <div ref="scrollContainer" class="flex-1 overflow-y-auto px-4 py-2" style="overflow-y: scroll;">
                    <div v-if="course_lessons.length" class="space-y-4">
                        <div v-for="(lesson, index) in course_lessons" :key="index" @click="handleLessonClick(lesson)"
                            class="bg-white p-4 cursor-pointer hover:bg-gray-50 transition-colors border-b border-gray-200 relative">
                            <div v-if="lesson.progress > 0 && lesson.progress < 100"
                                class="absolute top-2 right-2 px-2 py-1 bg-green-100 text-green-600 text-xs rounded">
                                上次看到</div>
                            <div class="text-black text-base mb-2" :class="{ 'text-green-600 font-medium' : courseId == lesson.id }">{{ 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>
        </van-popup>

        <!-- PDF预览 -->
        <PdfPreview v-model:show="pdfShow" :url="pdfUrl" :title="pdfTitle" @onLoad="onPdfLoad" />

        <!-- 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"
                        class="w-full h-full"
                        @play="handlePopupVideoPlay"
                        @pause="handlePopupVideoPause"
                    />
                </div>
            </div>
        </van-popup>

        <!-- 打卡弹窗 -->
        <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" />
                                <van-icon v-if="checkInType.task_type === 'upload'" name="tosend" size="1.5rem" />
                            </div>
                            <span class="text-xs">{{ checkInType.title }}</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="showDownloadFailDialog"
            position="center"
            round
            closeable
            :style="{ width: '85%', maxWidth: '400px' }"
        >
            <div class="p-6">
                <div class="text-center mb-4">
                    <van-icon name="warning-o" size="48" color="#ff6b6b" class="mb-2" />
                    <h3 class="text-lg font-medium text-gray-800">下载失败</h3>
                </div>

                <div class="text-center text-gray-600 mb-4">
                    <p class="mb-2">暂时无法自动下载文件</p>
                    <p class="text-sm">请复制下方链接手动下载</p>
                </div>

                <div class="mb-4">
                    <div class="text-sm text-gray-500 mb-2">文件名:</div>
                    <div class="bg-gray-50 p-3 rounded-lg text-sm break-all">
                        {{ downloadFailInfo.fileName }}
                    </div>
                </div>

                <div class="mb-6">
                    <div class="text-sm text-gray-500 mb-2">文件链接:</div>
                    <div class="bg-gray-50 p-3 rounded-lg text-sm break-all max-h-20 overflow-y-auto">
                        {{ downloadFailInfo.fileUrl }}
                    </div>
                </div>

                <div class="flex gap-3">
                    <van-button
                        block
                        type="default"
                        @click="showDownloadFailDialog = false"
                        class="flex-1"
                    >
                        关闭
                    </van-button>
                    <van-button
                        block
                        type="primary"
                        @click="copyToClipboard(downloadFailInfo.fileUrl)"
                        class="flex-1"
                    >
                        复制链接
                    </van-button>
                </div>
            </div>
        </van-popup>

        <!-- 学习资料全屏弹窗 -->
        <van-popup
            v-model:show="showMaterialsPopup"
            position="bottom"
            :style="{ width: '100%', height: '100%' }"
            :close-on-click-overlay="true"
            :lock-scroll="true"
        >
            <div class="flex flex-col h-full bg-gray-50">
                <!-- 头部导航栏 -->
                <div class="bg-white shadow-sm border-b border-gray-100">
                    <div class="flex items-center justify-between px-4 py-3">
                        <div class="flex items-center gap-3">
                            <!-- <van-button
                                @click="showMaterialsPopup = false"
                                type="default"
                                size="small"
                                round
                                class="w-8 h-8 p-0 bg-gray-100 border-0"
                            >
                                <van-icon name="cross" size="16" class="text-gray-600" />
                            </van-button> -->
                            <div class="px-1">
                                <h2 class="text-lg font-medium text-gray-900">学习资料</h2>
                                <p class="text-xs text-gray-500">
                                    共 {{ courseFile?.list ? courseFile.list.length : 0 }} 个文件
                                </p>
                            </div>
                        </div>
                        <div class="px-2 py-1 bg-blue-50 rounded-full">
                            <!-- <span class="text-blue-600 text-sm font-medium">
                                {{ courseFile?.list ? courseFile.list.length : 0 }}
                            </span> -->
                            <van-button
                                @click="showMaterialsPopup = false"
                                type="default"
                                size="small"
                                round
                                class="w-8 h-8 p-0 bg-gray-100 border-0"
                            >
                                <van-icon name="cross" size="16" class="text-gray-600" />
                            </van-button>
                        </div>
                    </div>
                </div>

                <!-- 文件列表 -->
                <div class="flex-1 overflow-y-auto p-4 pb-safe">
                    <div v-if="courseFile?.list && courseFile.list.length > 0" class="space-y-4">
                        <FrostedGlass
                            v-for="(file, index) in courseFile.list"
                            :key="index"
                            :bgOpacity="70"
                            blurLevel="md"
                            className="p-5 hover:bg-white/80 transition-all duration-300 hover:shadow-xl hover:scale-[1.02] transform"
                        >
                            <!-- 文件信息 -->
                            <div class="flex items-start gap-4 mb-4 p-2">
                                <div class="w-12 h-12 bg-gradient-to-br from-blue-50 to-indigo-100 rounded-xl flex items-center justify-center flex-shrink-0 shadow-sm">
                                    <van-icon
                                        :name="getFileIcon(file.title || file.name)"
                                        class="text-blue-600"
                                        :size="22"
                                    />
                                </div>
                                <div class="flex-1 min-w-0">
                                    <h3 class="text-base font-semibold text-gray-900 mb-2 line-clamp-2">{{ file.title || file.name }}</h3>
                                    <div class="flex items-center justify-between gap-4 text-sm text-gray-600">
                                        <div class="flex items-center gap-1">
                                            <van-icon name="label-o" size="12" style="margin-right: 0.25rem;"/>
                                            <span>{{ getFileType(file.title || file.name) }}</span>
                                        </div>
                                        <!-- 复制地址按钮 -->
                                        <button
                                            @click="copyFileUrl(file.url)"
                                            class="flex items-center gap-1 px-2 py-1 text-xs text-gray-500 hover:text-gray-700 hover:bg-gray-50 rounded transition-colors"
                                            title="复制文件地址"
                                        >
                                            <van-icon name="link" size="12" />
                                            <span>复制地址</span>
                                        </button>
                                    </div>
                                </div>
                            </div>

                            <!-- 操作按钮 -->
                            <div class="flex gap-2" style="margin: 1rem;">
                                <!-- 桌面端:显示在线查看、新窗口打开和下载文件按钮 -->
                                <template v-if="isDesktop">
                                    <!-- 新窗口打开按钮 - 只对图片、音频、视频和PDF文件显示 -->
                                    <button
                                        v-if="canOpenInNewWindow(file.title)"
                                        @click="openFileInNewWindow(file)"
                                        class="btn-primary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="eye-o" size="16" />
                                        在线查看
                                    </button>
                                    <!-- 所有文件都显示下载按钮 -->
                                    <button
                                        @click="downloadFile(file)"
                                        class="btn-secondary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="down" size="16" />
                                        下载文件
                                    </button>
                                </template>

                                <!-- 移动端:根据文件类型显示不同的预览按钮 -->
                                <template v-else>
                                    <!-- Office 文档显示预览按钮 -->
                                    <button
                                        v-if="isOfficeFile(file.url)"
                                        @click="showOfficeDocument(file)"
                                        class="btn-primary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="description" size="16" />
                                        文档预览
                                    </button>
                                    <!-- PDF文件显示在线查看按钮 -->
                                    <button
                                        v-else-if="file.url && file.url.toLowerCase().includes('.pdf')"
                                        @click="showPdf(file)"
                                        class="btn-primary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="eye-o" size="16" />
                                        在线查看
                                    </button>
                                    <!-- 音频文件显示音频播放按钮 -->
                                    <button
                                        v-else-if="isAudioFile(file.url)"
                                        @click="showAudio(file)"
                                        class="btn-primary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="music-o" size="16" />
                                        音频播放
                                    </button>
                                    <!-- 视频文件显示视频播放按钮 -->
                                    <button
                                        v-else-if="isVideoFile(file.url)"
                                        @click="showVideo(file)"
                                        class="btn-primary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="video-o" size="16" />
                                        视频播放
                                    </button>
                                    <!-- 图片文件显示图片预览按钮 -->
                                    <button
                                        v-else-if="isImageFile(file.url)"
                                        @click="showImage(file)"
                                        class="btn-primary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="photo-o" size="16" />
                                        图片预览
                                    </button>
                                    <!-- 其他文件显示下载按钮 -->
                                    <button
                                        @click="downloadFile(file)"
                                        class="btn-secondary flex-1 py-2.5 text-sm font-medium flex items-center justify-center gap-2"
                                    >
                                        <van-icon name="down" size="16" />
                                        下载文件
                                    </button>
                                </template>
                            </div>
                        </FrostedGlass>
                    </div>

                    <!-- 空状态 -->
                    <div v-else class="flex flex-col items-center justify-center py-16 px-4">
                        <div class="w-16 h-16 sm:w-20 sm:h-20 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                            <van-icon name="folder-o" :size="28" class="text-gray-400" />
                        </div>
                        <p class="text-gray-500 text-base sm:text-lg mb-2 text-center">暂无学习资料</p>
                        <p class="text-gray-400 text-sm text-center">请联系老师上传相关资料</p>
                    </div>
                </div>
            </div>
        </van-popup>
    </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/ui/VideoPlayer.vue';
import AudioPlayer from '@/components/ui/AudioPlayer.vue';
import FrostedGlass from '@/components/ui/FrostedGlass.vue';
import OfficeViewer from '@/components/ui/OfficeViewer.vue';
import dayjs from 'dayjs';
import { formatDate, wxInfo } from '@/utils/tools'
import axios from 'axios';
import { v4 as uuidv4 } from "uuid";
import { useIntersectionObserver } from '@vueuse/core';
import PdfPreview from '@/components/ui/PdfPreview.vue';
import { showToast } from 'vant';

// 导入接口
import { getScheduleCourseAPI, getGroupCommentListAPI, addGroupCommentAPI, addGroupCommentLikeAPI, delGroupCommentLikeAPI, getCourseDetailAPI } from '@/api/course';
import { addStudyRecordAPI } from "@/api/record";
import { checkinTaskAPI } from '@/api/checkin';

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

// 设备检测
const deviceInfo = wxInfo();
const isDesktop = deviceInfo.isPC;
const isMobile = deviceInfo.isMobile;

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

const scrollContainer = ref(null);

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

// 开始播放视频
const startPlay = async () => {
    isPlaying.value = true;
    await nextTick();
    if (videoPlayerRef.value) {
        videoPlayerRef.value.play();
    }
};

// 处理视频播放状态
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 popupCommentList = ref([]);
const popupLoading = ref(false);
const popupFinished = ref(false);
const popupLimit = ref(5);
const popupPage = ref(0);

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 commentCount = ref(0);
const commentList = ref([]);
const courseFile = ref({});

const handleLessonClick = async (lesson) => {
    showCatalog.value = false; // 关闭目录弹窗
    isPlaying.value = false; // 重置播放状态

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

    // 重新获取课程数据
    const { code, data } = await getScheduleCourseAPI({ i: lesson.id });
    if (code) {
        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 = [];
        }

        // 获取评论列表
        const comment = await getGroupCommentListAPI({ group_id: data.group_id, schedule_id: data.id });
        if (comment.code) {
            commentList.value = comment.data.comment_list;
            commentCount.value = comment.data.comment_count;
        }

        // 重新计算顶部和底部容器的高度
        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);
        }
    }
};

const pdfShow = ref(false);
const pdfTitle = ref('');
const pdfUrl = ref('');

// 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 }) => {
    pdfTitle.value = title;
    pdfUrl.value = url;
    pdfShow.value = true;
    // 新增记录
    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);
};

/**
 * 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 || '';
});

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) {
            course.value = data;
            courseFile.value = data.file;

            // 音频列表处理
            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'
                })
            }

            // 获取评论列表
            const comment = await getGroupCommentListAPI({ group_id: course.value.group_id, schedule_id: course.value.id });
            if (comment.code) {
                commentList.value = comment.data.comment_list;
                commentCount.value = comment.data.comment_count;
            }

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

// 提交评论
// 切换点赞状态
const toggleLike = async (comment) => {
    try {
        if (!comment.is_like) {
            const { code } = await addGroupCommentLikeAPI({ i: comment.id });
            if (code) {
                comment.is_like = true;
                comment.like_count += 1;
            }
        } else {
            const { code } = await delGroupCommentLikeAPI({ i: comment.id });
            if (code) {
                comment.is_like = false;
                comment.like_count -= 1;
            }
        }
    } catch (error) {
        console.error('点赞操作失败:', error);
    }
};

// 发送按钮,提交评论
const submitComment = async () => {
    if (!newComment.value.trim()) return;

    try {
        const { code, data } = await addGroupCommentAPI({
            group_id: course.value.group_id,
            schedule_id: course.value.id,
            note: newComment.value
        });

        if (code) {
            // 刷新评论列表
            const comment = await getGroupCommentListAPI({
                group_id: course.value.group_id,
                schedule_id: course.value.id,
            });
            if (comment.code) {
                commentList.value = comment.data.comment_list;
                commentCount.value = comment.data.comment_count;
            }
            newComment.value = '';
        }
    } catch (error) {
        console.error('提交评论失败:', error);
    }
};

// 处理标签页切换
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;
        }
    });
};


// 加载更多弹框评论
const onPopupLoad = async () => {
    const nextPage = popupPage.value;
    try {
        const res = await getGroupCommentListAPI({
            group_id: course.value.group_id,
            schedule_id: course.value.id,
            limit: popupLimit.value,
            page: nextPage
        });
        if (res.code) {
            // 使用Set进行去重处理
            const newComments = res.data.comment_list;
            const existingIds = new Set(popupCommentList.value.map(comment => comment.id));
            const uniqueNewComments = newComments.filter(comment => !existingIds.has(comment.id));
            popupCommentList.value = [...popupCommentList.value, ...uniqueNewComments];
            popupFinished.value = res.data.comment_list.length < popupLimit.value;
            popupPage.value = nextPage + 1;
        }
    } catch (error) {
        console.error('加载评论失败:', error);
    }
    popupLoading.value = false;
};

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

// 提交弹窗中的评论
const submitPopupComment = async () => {
    if (!popupComment.value.trim()) return;

    try {
        const { code, data } = await addGroupCommentAPI({
            group_id: course.value.group_id,
            schedule_id: course.value.id,
            note: popupComment.value
        });

        if (code) {
            // 重置弹框评论列表并重新加载
            popupCommentList.value = [];
            popupPage.value = 0;
            popupFinished.value = false;
            await onPopupLoad();

            // 更新评论数量和清空输入
            commentCount.value = data.comment_count;
            // 更新弹框标题中的评论总数
            const comment = await getGroupCommentListAPI({
                group_id: course.value.group_id,
                schedule_id: course.value.id
            });
            if (comment.code) {
                commentList.value = comment.data.comment_list;
                commentCount.value = comment.data.comment_count;
            }
            popupComment.value = '';
        }
    } catch (error) {
        console.error('提交评论失败:', error);
    }
};
// 监听弹窗显示状态变化
watch(showCommentPopup, async (newVal) => {
    if (newVal) {
        // 打开弹窗时重置状态
        popupCommentList.value = [];
        popupPage.value = 0;
        popupFinished.value = false;
        popupLoading.value = true;

        // 获取最新的评论总数
        const comment = await getGroupCommentListAPI({
            group_id: course.value.group_id,
            schedule_id: course.value.id
        });
        if (comment.code) {
            commentList.value = comment.data.comment_list;
            commentCount.value = comment.data.comment_count;
        }

        // 加载第一页数据
        onPopupLoad();
    }
});

// 下载文件失败提示弹窗状态
const showDownloadFailDialog = ref(false);
const downloadFailInfo = ref({
    fileName: '',
    fileUrl: ''
});

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

/**
 * 复制文件地址到剪贴板
 * @param {string} url - 要复制的文件地址
 */
const copyFileUrl = async (url) => {
    try {
        if (navigator.clipboard && window.isSecureContext) {
            // 现代浏览器支持的方式
            await navigator.clipboard.writeText(url);
            showToast('文件地址已复制到剪贴板');
        } else {
            // 兼容旧浏览器的方式
            const textArea = document.createElement('textarea');
            textArea.value = url;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                document.execCommand('copy');
                showToast('文件地址已复制到剪贴板');
            } catch (err) {
                console.error('复制失败:', err);
                showToast('复制失败,请手动复制地址');
            } finally {
                document.body.removeChild(textArea);
            }
        }
    } catch (err) {
        console.error('复制到剪贴板失败:', err);
        showToast('复制失败,请手动复制地址');
    }
};

/**
 * 复制到剪贴板
 * @param {string} url - 要复制的URL
 */
const copyToClipboard = async (url) => {
    try {
        if (navigator.clipboard && window.isSecureContext) {
            // 现代浏览器支持的方式
            await navigator.clipboard.writeText(url);
            showToast('文件链接已复制到剪贴板');
        } else {
            // 兼容旧浏览器的方式
            const textArea = document.createElement('textarea');
            textArea.value = url;
            textArea.style.position = 'fixed';
            textArea.style.left = '-999999px';
            textArea.style.top = '-999999px';
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();

            try {
                document.execCommand('copy');
                showToast('文件链接已复制到剪贴板');
            } catch (err) {
                console.error('复制失败:', err);
                showToast('复制失败,请手动复制链接');
            } finally {
                document.body.removeChild(textArea);
            }
        }
    } catch (err) {
        console.error('复制到剪贴板失败:', err);
        showToast('复制失败,请手动复制链接');
    }
};

/**
 * 尝试直接下载文件(适用于同源或支持CORS的文件)
 * @param {string} fileUrl - 文件URL
 * @param {string} fileName - 文件名
 */
const tryDirectDownload = (fileUrl, fileName) => {
    try {
        const a = document.createElement('a');
        a.href = fileUrl;
        a.download = fileName;
        a.style.display = 'none';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        return true;
    } catch (error) {
        console.error('直接下载失败:', error);
        return false;
    }
};

// 下载文件
const downloadFile = ({ title, url, meta_id }) => {
    // 获取文件URL和文件名
    const fileUrl = url;
    const fileName = title;

    // 根据文件URL后缀获取MIME类型
    const getMimeType = (url) => {
        const extension = url.split('.').pop().toLowerCase();
        const mimeTypes = {
            'pdf': 'application/pdf',
            'doc': 'application/msword',
            'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'xls': 'application/vnd.ms-excel',
            'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'ppt': 'application/vnd.ms-powerpoint',
            'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
            'txt': 'text/plain',
            'zip': 'application/zip',
            'rar': 'application/x-rar-compressed',
            '7z': 'application/x-7z-compressed',
            'mp3': 'audio/mpeg',
            'acc': 'audio/aac',  // 添加对 acc 格式的支持
            'aac': 'audio/aac',  // 添加对 aac 格式的支持
            'wav': 'audio/wav',  // 添加对 wav 格式的支持
            'ogg': 'audio/ogg',  // 添加对 ogg 格式的支持
            'mp4': 'video/mp4',
            'jpg': 'image/jpeg',
            'jpeg': 'image/jpeg',
            'png': 'image/png',
            'gif': 'image/gif'
        };
        return mimeTypes[extension] || 'application/octet-stream';
    };

    // 首先尝试直接下载(适用于同源文件或支持下载的链接)
    const directDownloadSuccess = tryDirectDownload(fileUrl, fileName);

    // 如果直接下载可能成功,等待一段时间后检查是否真的成功
    if (directDownloadSuccess) {
        // 记录下载行为
        let paramsObj = {
            schedule_id: courseId.value,
            meta_id
        }
        addRecord(paramsObj);
        return;
    }

    // 如果直接下载失败,尝试通过axios下载
    axios({
        method: 'get',
        url: fileUrl,
        responseType: 'blob', // 表示返回的数据类型是Blob
        timeout: 30000 // 设置30秒超时
    }).then((response) => {
        try {
            const blob = new Blob([response.data], { type: getMimeType(fileUrl) });
            const blobUrl = window.URL.createObjectURL(blob);

            const a = document.createElement('a');
            a.href = blobUrl;
            a.download = fileName;
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

            // 延迟释放URL,确保下载完成
            setTimeout(() => {
                window.URL.revokeObjectURL(blobUrl);
            }, 1000);

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

            showToast('文件下载已开始');
        } catch (blobError) {
            console.error('创建下载链接失败:', blobError);
            // 显示下载失败提示
            downloadFailInfo.value = {
                fileName: fileName,
                fileUrl: fileUrl
            };
            showDownloadFailDialog.value = true;
        }
    }).catch((error) => {
        console.error('下载文件出错:', error);

        // 根据错误类型提供不同的处理方式
        let errorMessage = '下载失败';
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
            errorMessage = '下载超时';
        } else if (error.response && error.response.status === 404) {
            errorMessage = '文件不存在';
        } else if (error.response && error.response.status === 403) {
            errorMessage = '无权限访问文件';
        } else if (error.message.includes('CORS') || error.message.includes('cross-origin')) {
            errorMessage = '跨域访问限制';
        }

        console.log(`${errorMessage},显示手动下载提示`);

        // 显示下载失败提示弹窗
        downloadFailInfo.value = {
            fileName: fileName,
            fileUrl: fileUrl
        };
        showDownloadFailDialog.value = true;
    });
}

/**
 * 在新窗口中打开文件
 * @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);
}

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

    const extension = fileName.split('.').pop().toLowerCase();
    const audioTypes = ['mp3', 'aac', 'wav', 'ogg'];
    return audioTypes.includes(extension);
}

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

    const extension = fileName.split('.').pop().toLowerCase();
    const videoTypes = ['mp4', 'avi', 'mov'];
    return videoTypes.includes(extension);
}

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

    const extension = fileName.split('.').pop().toLowerCase();
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif'];
    return imageTypes.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 videoDuration = ref(0);
const currentPosition = ref(0);

// 记录音频时长和当前播放位置的变量
const audioDuration = ref(0);
const audioPosition = ref(0);

/**
 * 开始操作
 * @param action
 * @param item
 */
const startAction = (item) => {
    // 先清除可能存在的定时器
    if (window.actionTimer) {
        clearInterval(window.actionTimer);
    }

    // 获取视频总时长(如果是视频播放)
    if (videoPlayerRef.value && videoPlayerRef.value.getPlayer()) {
        videoDuration.value = videoPlayerRef.value.getPlayer().duration();
    }

    // 获取音频总时长(如果是音频播放)
    if (audioPlayerRef.value && audioPlayerRef.value.getPlayer()) {
        audioDuration.value = audioPlayerRef.value.getPlayer().duration;
    }

    // 生成唯一标识符
    let uuid = uuidv4();
    console.warn('开始操作', uuid);

    // 设置定时器,持续执行操作
    window.actionTimer = setInterval(() => {
        console.warn('持续操作中', uuid);

        let paramsObj = {
            schedule_id: courseId.value,
            meta_id: item?.meta_id,
        }

        // 更新当前播放位置(如果是视频播放)
        if (videoPlayerRef.value && videoPlayerRef.value.getPlayer()) {
            currentPosition.value = videoPlayerRef.value.getPlayer().currentTime();
            console.log('视频总时长:', videoDuration.value, '当前位置:', currentPosition.value, 'id:', videoPlayerRef.value.getId());
            paramsObj = {
                schedule_id: courseId.value,
                meta_id: videoPlayerRef.value.getId(),
                media_duration: videoDuration.value,
                playback_position: currentPosition.value,
                playback_id: uuid,
            }
        }

        // 更新当前播放位置(如果是音频播放)
        if (audioPlayerRef.value && audioPlayerRef.value.getPlayer()) {
            audioPosition.value = audioPlayerRef.value.getPlayer().currentTime;
            console.log('音频总时长:', audioDuration.value, '当前位置:', audioPosition.value, 'id:', item?.meta_id);
            paramsObj = {
                schedule_id: courseId.value,
                meta_id: item?.meta_id,
                media_duration: audioDuration.value,
                playback_position: audioPosition.value,
                playback_id: uuid,
            }
        }

        // 新增记录
        addRecord(paramsObj);

        // 这里可以添加需要持续执行的具体操作
    }, 3000); // 3秒执行一次,可以根据需求调整时间间隔
}

/**
 * 结束操作
 * @param action
 * @param item
 */
const endAction = (item) => {
    // 在结束前记录最后的播放位置
    if (videoPlayerRef.value && videoPlayerRef.value.player) {
        currentPosition.value = videoPlayerRef.value.player.currentTime();
        console.log('结束时 - 视频总时长:', videoDuration.value, '最终位置:', currentPosition.value);
    }

    // 在结束前记录最后的音频播放位置
    if (course.value?.course_type === 'audio' && document.querySelector('audio')) {
        const audioElement = document.querySelector('audio');
        audioPosition.value = audioElement.currentTime || 0;
        console.log('结束时 - 音频总时长:', audioDuration.value, '最终位置:', audioPosition.value);
    }

    // 清除定时器,停止执行startAction
    if (window.actionTimer) {
        clearInterval(window.actionTimer);
        window.actionTimer = null;
        console.warn('操作已停止');
    }
}

/**
 * 添加学习记录
 * @param paramsObj
 */
const addRecord = async (paramsObj) => {
    await addStudyRecordAPI(paramsObj);
}

// 监听目录弹框显示状态,当打开时滚动到当前课程位置
watch(showCatalog, (newVal) => {
    if (newVal) {
        // 等待DOM更新后执行滚动
        nextTick(() => {
            // 查找当前选中的课程元素
            const selectedLesson = document.querySelector('.text-green-600')?.closest('.bg-white');
            if (selectedLesson) {
                // 获取滚动容器
                const scrollContainer = document.querySelector('.van-popup .overflow-y-auto');
                if (scrollContainer) {
                    // 计算滚动位置,使选中元素位于容器中间
                    const containerHeight = scrollContainer.clientHeight;
                    const lessonTop = selectedLesson.offsetTop;
                    const lessonHeight = selectedLesson.clientHeight;
                    const scrollTop = lessonTop - (containerHeight / 2) + (lessonHeight / 2);

                    // 平滑滚动到指定位置
                    scrollContainer.scrollTo({
                        top: scrollTop,
                        behavior: 'smooth'
                    });
                }
            }
        });
    }
});

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

// 处理打卡选择
const handleCheckInSelect = (type) => {
    if (type.is_gray && type.task_type === 'checkin') {
        showToast('您已经完成了今天的打卡');
        return;
    }
    if (type.task_type === 'upload') {
        router.push({
            path: '/checkin/index',
            query: {
                id: type.id
            }
        });
        showCheckInDialog.value = false;
        return;
    } else {
        selectedCheckIn.value = type;
    }
};

// 处理打卡提交
const handleCheckInSubmit = async () => {
    if (!selectedCheckIn.value) {
        showToast('请选择打卡项目');
        return;
    }

    isCheckingIn.value = true;
    try {
        const { code } = await checkinTaskAPI({ task_id: selectedCheckIn.value.id });
        if (code) {
            checkInSuccess.value = true;
            // 重置表单
            setTimeout(() => {
                checkInSuccess.value = false;
                selectedCheckIn.value = null;
                showCheckInDialog.value = false;
            }, 1500);
        }
    } catch (error) {
        console.error('打卡失败:', error);
        showToast('打卡失败,请重试');
    } finally {
        isCheckingIn.value = false;
    }
};

const goToCheckin = () => {
    if(!default_list.value.length) {
        showToast('暂无打卡任务');
        return;
    }
    showCheckInDialog.value = true;
};

const toggleTask = (type) => {
    if(type === 'today') {
        showTaskList.value = true;
        showTimeoutTaskList.value = false;
        default_list.value = task_list.value;
    } else {
        showTaskList.value = false;
        showTimeoutTaskList.value = true;
        default_list.value = timeout_task_list.value;
    }
}

const closeCheckInDialog = () => {
    showCheckInDialog.value = false;
    // 切换到今日任务
    showTaskList.value = true;
    showTimeoutTaskList.value = false;
    default_list.value = task_list.value;
}

/**
 * 格式化文件大小
 * @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]}`;
}

/**
 * 根据文件名获取文件图标
 * @param {string} fileName - 文件名
 * @returns {string} 图标名称
 */
const getFileIcon = (fileName) => {
    // 添加空值检查
    if (!fileName || typeof fileName !== 'string') {
        return 'description'; // 默认图标
    }

    const extension = fileName.split('.').pop().toLowerCase();
    const iconMap = {
        'pdf': 'description',
        'doc': 'description',
        'docx': 'description',
        'xls': 'description',
        'xlsx': 'description',
        'ppt': 'description',
        'pptx': 'description',
        'txt': 'description',
        'zip': 'bag-o',
        'rar': 'bag-o',
        '7z': 'bag-o',
        'mp3': 'music-o',
        'aac': 'music-o',
        'wav': 'music-o',
        'ogg': 'music-o',
        'mp4': 'video-o',
        'avi': 'video-o',
        'mov': 'video-o',
        'jpg': 'photo-o',
        'jpeg': 'photo-o',
        'png': 'photo-o',
        'gif': 'photo-o'
    };
    return iconMap[extension] || 'description';
}

/**
 * 根据文件名获取文件类型描述
 * @param {string} fileName - 文件名
 * @returns {string} 文件类型描述
 */
const getFileType = (fileName) => {
    // 添加空值检查
    if (!fileName || typeof fileName !== 'string') {
        return '未知文件'; // 默认类型
    }

    const extension = fileName.split('.').pop().toLowerCase();
    const typeMap = {
        'pdf': 'PDF文档',
        'doc': 'Word文档',
        'docx': 'Word文档',
        'xls': 'Excel表格',
        'xlsx': 'Excel表格',
        'ppt': 'PPT演示',
        'pptx': 'PPT演示',
        'txt': '文本文件',
        'zip': '压缩文件',
        'rar': '压缩文件',
        '7z': '压缩文件',
        'mp3': '音频文件',
        'aac': '音频文件',
        'wav': '音频文件',
        'ogg': '音频文件',
        'mp4': '视频文件',
        'avi': '视频文件',
        'mov': '视频文件',
        'jpg': '图片文件',
        'jpeg': '图片文件',
        'png': '图片文件',
        'gif': '图片文件'
    };
    return typeMap[extension] || '未知文件';
}
</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;
}
</style>