KnowledgeBase.vue 69 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 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208
<template>
  <div class="knowledge-base-root">
    <!-- 左侧文件夹区域 -->
    <div class="kb-sidebar" :class="{ 'is-collapsed': isSidebarCollapsed }" :style="{ width: isSidebarCollapsed ? '48px' : sidebarWidth + 'px' }">
      <!-- 顶部 Tab 切换 -->
      <div class="kb-tabs">
        <div class="tabs-left">
          <div 
            class="kb-tab-item" 
            :class="{ active: currentTab === 'knowledge' }"
            @click="handleTabChange('knowledge')"
            :title="t('KnowledgeBase.knowledgeBase')"
          >
            <img :src="currentTab === 'knowledge' ? '/zhishikulight.svg' : '/zhishiku.svg'" class="tab-icon" />
          </div>
          <div 
            class="kb-tab-item" 
            :class="{ active: currentTab === 'case' }"
            @click="handleTabChange('case')"
            :title="t('KnowledgeBase.caseLibrary')"
          >
            <img :src="currentTab === 'case' ? '/bingliku_light.svg' : '/bingliku.svg'" class="tab-icon" />
          </div>
          <div 
            class="kb-tab-item" 
            :class="{ active: currentTab === 'imaging' }"
            @click="handleTabChange('imaging')"
            :title="t('KnowledgeBase.imagingLibrary')"
          >
            <img :src="currentTab === 'imaging' ? '/yingxiangku_light.svg' : '/yingxiangku.svg'" class="tab-icon" />
          </div>
        </div>
        <div class="tabs-right" @click="toggleSidebarCollapse" :title="isSidebarCollapsed ? t('common.expand') : t('common.minimize')">
          <i class="fas" :class="isSidebarCollapsed ? 'fa-angle-double-right' : 'fa-angle-double-left'"></i>
        </div>
      </div>

      <div class="kb-sidebar-content" v-show="!isSidebarCollapsed">
        <!-- 知识库侧边栏内容 -->
        <template v-if="currentTab === 'knowledge'">
          <FolderTree
            ref="folderTreeRef"
            @folder-selected="handleFolderSelected"
            @create-folder="handleCreateFolderClick"
            @rename-folder="openRenameFolder"
            @delete-folder="handleDeleteFolder"
            @upload-file="handleUploadFiles"
            @create-file="handleCreateFileClick"
            @download-folder="handleDownloadFolder"
          />
          <RecycleBin @open-recycle-bin="openRecycleBin" />
        </template>
        
        <!-- 病例库侧边栏内容 -->
        <div v-else-if="currentTab === 'case'" class="library-sidebar-content">
          <FolderTree
            ref="caseFolderTreeRef"
            @folder-selected="handleFolderSelected"
            @create-folder="handleCreateFolderClick"
            @rename-folder="openRenameFolder"
            @delete-folder="handleDeleteFolder"
            @upload-file="handleUploadFiles"
            @create-file="handleCreateFileClick"
            @download-folder="handleDownloadFolder"
            :upload-button-text="t('KnowledgeBase.uploadCase')"
          />
        </div>

        <!-- 影像库侧边栏内容 -->
        <div v-else-if="currentTab === 'imaging'" class="library-sidebar-content">
          <FolderTree
            ref="imagingFolderTreeRef"
            @folder-selected="handleFolderSelected"
            @create-folder="handleCreateFolderClick"
            @rename-folder="openRenameFolder"
            @delete-folder="handleDeleteFolder"
            @upload-file="handleUploadFiles"
            @create-file="handleCreateFileClick"
            @download-folder="handleDownloadFolder"
            :upload-button-text="t('KnowledgeBase.uploadDicom')"
          />
        </div>
      </div>
    </div>

    <!-- 可拉伸分隔线 -->
    <div
      class="resize-handle"
      @mousedown="startResize"
      @touchstart="startResize"
    ></div>

    <!-- 右侧内容区域:支持从系统文件管理器拖拽上传 -->
    <div
      class="kb-content"
      :class="{ 'kb-content-drag-over': isDragOver && !isRecycleBinMode }"
      @dragover.prevent.stop="handleContentDragOver"
      @dragenter.prevent.stop="handleContentDragEnter"
      @dragleave.stop="handleContentDragLeave"
      @drop.prevent.stop="handleContentDrop"
    >
      <template v-if="currentTab === 'knowledge'">
        <!-- 拖拽上传时的视觉反馈遮罩 -->
        <div
          v-show="isDragOver && !isRecycleBinMode"
          class="kb-drop-overlay"
        >
          <div class="kb-drop-overlay-content">
            <i class="fas fa-cloud-upload-alt kb-drop-icon"></i>
            <span class="kb-drop-text">{{ t("KnowledgeBase.dropToUpload") || "释放以上传到当前文件夹" }}</span>
          </div>
        </div>
        <FileList
          v-if="!isRecycleBinMode"
          ref="fileListRef"
          :current-folder-id="activeFolderId"
          :current-folder-name="currentFolderName"
          :current-folder-path="currentFolderPath"
          @create-file="showNewFile = true"
          @rename-file="openRenameFile"
          @file-deleted="handleFileDeleted"
          @folder-deleted="handleFolderDeletedInList"
          @upload-files="handleUploadFiles"
          @file-click="handleFileClick"
          @folder-click="handleFolderSelected"
          @rename-folder="openRenameFolder"
          @delete-folder="handleDeleteFolder"
          @download-folder="handleDownloadFolder"
          @breadcrumb-click="handleBreadcrumbClick"
          @download-file="handleDownloadFile"
        />

        <!-- 回收站列表组件,只在回收站模式下显示 -->
        <RecycleBinList
          v-if="isRecycleBinMode"
          @items-restored="handleItemsRestored"
          @items-deleted="handleItemsDeleted"
          @recycle-bin-emptied="handleRecycleBinEmptied"
        />
      </template>

      <!-- 病例库内容 -->
      <CaseLibrary v-else-if="currentTab === 'case'" current-tab="case" @upload-files="handleUploadFiles" />

      <!-- 影像库内容 -->
      <ImagingLibrary v-else-if="currentTab === 'imaging'" />

      <!-- 上传进度组件 -->
      <UploadProgress
        v-if="uploadProgressVisible"
        :upload-files="uploadingFiles"
        @close="uploadProgressVisible = false"
        @retry-upload="handleRetryUpload"
        @cancel-upload="handleCancelUpload"
        @cancel-all-uploads="handleCancelAllUploads"
      />
    </div>

    <!-- 可拉伸分隔线 (IntelligencePanel) -->
    <div
      v-if="!isIntelligencePanelMinimized"
      class="resize-handle"
      @mousedown="startGeneratorResize"
      @touchstart="startGeneratorResize"
    ></div>

    <!-- generator 区域(智能面板) -->
    <div 
      class="kb-generator-area"
      :class="{ 
        minimized: isIntelligencePanelMinimized,
        resizing: isResizingGenerator
      }"
      :style="{
        width: isIntelligencePanelMinimized ? '54px' : generatorWidth + 'px',
        minWidth: isIntelligencePanelMinimized ? '54px' : generatorWidth + 'px',
        maxWidth: isIntelligencePanelMinimized ? '54px' : generatorWidth + 'px'
      }"
    >
      <IntelligencePanel
        ref="intelligencePanelRef"
        :minimized="isIntelligencePanelMinimized"
        @minimize-changed="handleIntelligencePanelMinimize"
      />
    </div>

    <!-- 弹窗组件 -->
    <NewFolderDialog
      v-if="showNewFolder"
      :parent-folder-id="newFolderParentId"
      @close="showNewFolder = false"
      @create="handleCreateFolder"
    />
    <NewFileDialog
      v-if="showNewFile"
      :folder-id="activeFolderId"
      @close="showNewFile = false"
      @create="handleCreateFile"
    />
    <RenameFolderDialog
      v-if="showRenameFolder"
      :folder="renameFolderObj!"
      @close="showRenameFolder = false"
      @rename="handleRenameFolder"
    />
    <RenameFileDialog
      v-if="showRenameFileDialog"
      :file="renameFileObj!"
      @close="showRenameFileDialog = false"
      @rename="handleRenameFile"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, defineAsyncComponent, nextTick, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { useAppStore } from "@/stores/app";
import { ElMessage, ElMessageBox } from "element-plus";
import NewFolderDialog from "@/components/KnowledgeBase/NewFolderDialog.vue";
import NewFileDialog from "@/components/KnowledgeBase/NewFileDialog.vue";
import RenameFolderDialog from "@/components/KnowledgeBase/RenameFolderDialog.vue";
import RenameFileDialog from "@/components/KnowledgeBase/RenameFileDialog.vue";
import FolderTree from "@/components/KnowledgeBase/FolderTree.vue";
import RecycleBin from "@/components/KnowledgeBase/RecycleBin.vue";
import RecycleBinList from "@/components/KnowledgeBase/RecycleBinList.vue";
import FileList from "@/components/KnowledgeBase/FileList.vue";
import UploadProgress from "@/components/KnowledgeBase/UploadProgress.vue";
import CaseLibrary from "@/pages/CaseLibrary.vue";
import ImagingLibrary from "@/pages/ImagingLibrary.vue";
// 导入智能面板组件
const IntelligencePanel = defineAsyncComponent(
  () => import("@/layout/IntelligencePanel.vue"),
);
import { triggerNewbieTask } from "@/utils/newbieTask";
import {
  createFolder as createFolderApi,
  renameFolder as renameFolderApi,
  deleteFolder as deleteFolderApi,
  renameFile as renameFileApi,
  deleteFile as deleteFileApi,
  getFileMeta,
  getFiles,
  downloadFile,
  uploadBatchFiles,
  downloadFolder as downloadFolderApi,
  listenBatchProgress,
  registerUploadedFile,
  type FileItem,
  type FolderItem,
} from "@/api/files";
import { uploadFilesToTos, getTosDownloadUrl } from "@/utils/tosUpload";
import { useAuthStore } from "@/stores/auth";

const props = defineProps<{
  defaultTab?: string;
}>();

const { t } = useI18n();
const router = useRouter();
const appStore = useAppStore();
const authStore = useAuthStore();

// Refs
const folderTreeRef = ref();
const caseFolderTreeRef = ref();
const imagingFolderTreeRef = ref();
const fileListRef = ref();
const intelligencePanelRef = ref();

// 状态
const activeFolderId = ref<string | number>(-1);
const currentFolderName = ref(t("KnowledgeBase.allFiles"));
const currentFolderPath = ref<FolderItem[]>([]);
const isRecycleBinMode = ref(false);
const isFirstFolderSelection = ref(true);
const currentTab = ref(props.defaultTab || 'knowledge'); // 'knowledge', 'case', 'imaging'
const isSidebarCollapsed = ref(false);
const lastSidebarWidth = ref(244);

// 处理 Tab 切换
const handleTabChange = (tab: string) => {
  currentTab.value = tab;
  // 如果当前是收起状态,切换 Tab 时自动展开
  if (isSidebarCollapsed.value) {
    isSidebarCollapsed.value = false;
    sidebarWidth.value = lastSidebarWidth.value;
  }
  // 如果切换回知识库,可能需要重置一些状态
  if (tab === 'knowledge') {
    nextTick(() => {
      folderTreeRef.value?.setCurrentFolder(activeFolderId.value);
    });
  }
};

// 切换侧边栏收起/展开
const toggleSidebarCollapse = () => {
  if (isSidebarCollapsed.value) {
    // 展开
    sidebarWidth.value = lastSidebarWidth.value;
    isSidebarCollapsed.value = false;
  } else {
    // 收起
    lastSidebarWidth.value = sidebarWidth.value;
    sidebarWidth.value = 48; // 收起后的宽度,仅容纳图标
    isSidebarCollapsed.value = true;
  }
};

// 对话框状态
const showNewFolder = ref(false);
const showNewFile = ref(false);
const showRenameFolder = ref(false);
const showRenameFileDialog = ref(false);
const renameFolderObj = ref<FolderItem | null>(null);
const renameFileObj = ref<FileItem | null>(null);
const newFolderParentId = ref<string | number | null>(null); // 新建文件夹的父文件夹ID

// 上传相关
const uploadProgressVisible = ref(false);
const uploadingFiles = ref<any[]>([]);
const activeListeners = ref(new Map<string, { close: () => void }>());
// 拖拽上传:从系统文件管理器拖入时的悬停状态
const isDragOver = ref(false);
const dragEnterCounter = ref(0); // 用于处理 dragenter/dragleave 在子元素上的冒泡

// 处理取消单个文件上传
const handleCancelUpload = (id: string | number) => {
  const index = uploadingFiles.value.findIndex(f => f.id === id);
  if (index !== -1) {
    const file = uploadingFiles.value[index];
    file.status = "cancelled";
    file.statusText = "已取消上传";
    
    // 检查该文件所属的批次是否还有其他正在上传的文件
    const batchId = file.uploadId?.split("-").pop(); // 提取真实的 uploadId
    if (batchId) {
      const hasOtherUploading = uploadingFiles.value.some(f => 
        f.id !== id && 
        f.uploadId?.endsWith(batchId) && 
        f.status === "uploading"
      );
      
      // 如果没有其他文件在该批次上传,关闭该批次的监听器
      if (!hasOtherUploading && activeListeners.value.has(batchId)) {
        activeListeners.value.get(batchId)?.close();
        activeListeners.value.delete(batchId);
      }
    }
    
    // 如果所有文件都已处理(完成、错误或取消),延迟关闭进度窗
    const allProcessed = uploadingFiles.value.every(f => 
      ["completed", "error", "cancelled"].includes(f.status)
    );
    if (allProcessed) {
      setTimeout(() => {
        uploadProgressVisible.value = false;
      }, 3000);
    }
  }
};

// 处理取消全部上传
const handleCancelAllUploads = () => {
  uploadingFiles.value.forEach(file => {
    if (file.status === "uploading") {
      file.status = "cancelled";
      file.statusText = "已取消上传";
    }
  });

  // 关闭所有监听器
  activeListeners.value.forEach(listener => listener.close());
  activeListeners.value.clear();

  // 延迟关闭进度窗
  setTimeout(() => {
    uploadProgressVisible.value = false;
  }, 2000);
};

// 侧边栏宽度调整
const sidebarWidth = ref(244);
const isResizing = ref(false);
const startX = ref(0);
const startWidth = ref(0);

// generator 宽度调整
const generatorWidth = ref(350);
const isResizingGenerator = ref(false);
const startXGenerator = ref(0);
const startWidthGenerator = ref(0);

// 获取文件夹路径(改用异步方式通过 API 获取)
const updateBreadcrumbPath = async (folder: FolderItem) => {
  if (folder.id === -1 || folder.id === "root") {
    currentFolderPath.value = [folder];
    return;
  }

  try {
    const path: FolderItem[] = [folder];
    let currentParentId = (folder as any).parentId;

    while (currentParentId && currentParentId !== -1 && currentParentId !== "root") {
      const res = await getFileMeta(currentParentId);
      if (res && res.data) {
        const parentFolder: FolderItem = {
          id: res.data.id,
          name: res.data.name || res.data.folderName,
          parentId: res.data.parentId || res.data.folderId,
        } as any;
        path.unshift(parentFolder);
        currentParentId = parentFolder.parentId;
      } else {
        break;
      }
    }

    // 最后加上根目录
    path.unshift({
      id: -1,
      name: "我的文档",
    } as any);

    currentFolderPath.value = path;
  } catch (error) {
    console.error("获取面包屑路径失败:", error);
    currentFolderPath.value = [folder];
  }
};

// 处理文件夹选择
const handleFolderSelected = async (folder: FolderItem) => {
  activeFolderId.value = folder.id;

  // 同步更新文件夹树的选中状态
  folderTreeRef.value?.setCurrentFolder(folder.id);

  // 如果是初始化时的第一次自动选择,且用户之前在回收站模式,则保持回收站模式
  if (isFirstFolderSelection.value) {
    isFirstFolderSelection.value = false;
    const savedRecycleBinMode = localStorage.getItem("kb_is_recycle_bin_mode");
    if (savedRecycleBinMode === "true") {
      isRecycleBinMode.value = true;
      currentFolderName.value = t("KnowledgeBase.recycleBin");
      await updateBreadcrumbPath(folder);
      return;
    }
  }

  currentFolderName.value = folder.name;
  isRecycleBinMode.value = false;
  // 更新面包屑路径
  await updateBreadcrumbPath(folder);
};

// 处理面包屑点击
const handleBreadcrumbClick = async (data: { folder: FolderItem; index: number }) => {
  // 点击面包屑项时,导航到对应的文件夹
  activeFolderId.value = data.folder.id;
  currentFolderName.value = data.folder.name;
  isRecycleBinMode.value = false;
  // 同步更新文件夹树的选中状态
  folderTreeRef.value?.setCurrentFolder(data.folder.id);
  // 更新面包屑路径
  await updateBreadcrumbPath(data.folder);
};

// 处理创建文件夹按钮点击
const handleCreateFolderClick = (parent: FolderItem | null) => {
  renameFolderObj.value = parent;
  // 设置父文件夹ID
  if (parent) {
    // 如果传入了父文件夹,使用该文件夹ID
    newFolderParentId.value = parent.id;
  } else {
    // 如果没有传入父文件夹,使用当前选中的文件夹ID
    newFolderParentId.value = activeFolderId.value;
  }
  showNewFolder.value = true;
};

// 处理创建文件按钮点击
const handleCreateFileClick = (parent: FolderItem | null) => {
  if (parent) {
    activeFolderId.value = parent.id;
  }
  showNewFile.value = true;
};

// 查找文件夹(辅助方法)
const findFolderById = (folderId: string | number): FolderItem | null => {
  const treeData = currentTab.value === 'knowledge' 
    ? (folderTreeRef.value?.treeData || [])
    : currentTab.value === 'case'
      ? (caseFolderTreeRef.value?.treeData || [])
      : (imagingFolderTreeRef.value?.treeData || []);

  const find = (
    folders: FolderItem[],
    id: string | number,
  ): FolderItem | null => {
    for (const folder of folders) {
      if (folder && folder.id === id) return folder;
      if (
        folder &&
        Array.isArray(folder.children) &&
        folder.children.length > 0
      ) {
        const found = find(folder.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  return find(treeData, folderId);
};

// 处理删除文件夹
const handleDeleteFolder = async (folderId: string | number) => {
  // 确保 folderId 是有效的
  if (typeof folderId === "object" && folderId !== null) {
    folderId = (folderId as any).id || (folderId as any).folderId;
  }

  if (!folderId) {
    return;
  }

  // 查找要删除的文件夹
  const folder = findFolderById(folderId);
  if (!folder) {
    ElMessage.error(t("KnowledgeBase.folderNotFound"));
    return;
  }

  try {
    // 二次确认删除
    await ElMessageBox.confirm(
      t("KnowledgeBase.confirmDeleteFolder", { name: folder.name }),
      t("common.warning"),
      {
        confirmButtonText: t("common.confirm"),
        cancelButtonText: t("common.cancel"),
        type: "warning",
      },
    );

    // 调用删除API
    const response = await deleteFolderApi(folderId);

    // 记录父文件夹ID以便刷新
    const parentId = folder.parentId;

    // 检查API响应状态(response.data 是实际的响应数据)
    const responseData = (response as any)?.data;
    if (response && response.status === 200) {
      ElMessage.success(t("KnowledgeBase.deleteFolderSuccess"));

      // 刷新文件夹树,尝试刷新其父节点
      const currentTreeRef = currentTab.value === 'knowledge' 
        ? folderTreeRef.value 
        : currentTab.value === 'case'
          ? caseFolderTreeRef.value
          : imagingFolderTreeRef.value;
      await currentTreeRef?.refresh(parentId);
      // 同时也刷新当前文件列表,以移除已删除的文件夹
      fileListRef.value?.refresh();
      // 发送全局刷新信号
      appStore.triggerRefreshFileHierarchy(parentId);

      // 如果删除的是当前选中的文件夹,或者是当前路径上的父文件夹,清空当前选中状态并跳转
      const currentPath = currentFolderPath.value;
      const deleteIdx = currentPath.findIndex(
        (f) => String(f.id) === String(folderId),
      );

      if (deleteIdx !== -1) {
        // 如果删除了当前或父级,跳到被删除文件夹的父级,或者跳到根目录
        if (deleteIdx > 0) {
          const parentFolder = currentPath[deleteIdx - 1];
          activeFolderId.value = parentFolder.id;
          currentFolderName.value = parentFolder.name;
          updateBreadcrumbPath(parentFolder);
        } else {
          // 删除了顶级文件夹,跳到根目录
          const currentTreeRef = currentTab.value === 'knowledge' 
            ? folderTreeRef.value 
            : currentTab.value === 'case'
              ? caseFolderTreeRef.value
              : imagingFolderTreeRef.value;
          const treeData = currentTreeRef?.treeData || [];
          if (treeData.length > 0 && treeData[0]) {
            activeFolderId.value = treeData[0].id;
            currentFolderName.value = treeData[0].name;
            updateBreadcrumbPath(treeData[0]);
          } else {
            activeFolderId.value = -1;
            currentFolderName.value = t("KnowledgeBase.allFiles");
            currentFolderPath.value = [];
          }
        }
        // 跳转后再次刷新列表
        fileListRef.value?.refresh();
      }
    } else {
      // API返回错误状态
      const errorMsg =
        responseData?.message || t("KnowledgeBase.deleteFolderFailed");
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    if (error === "cancel") {
      // 用户取消删除
      console.log("用户取消删除");
      return;
    }

    let errorMessage = t("KnowledgeBase.deleteFolderFailed");
    if ((error as any)?.response?.data?.message) {
      errorMessage += `: ${(error as any).response.data.message}`;
    } else if ((error as any)?.message) {
      errorMessage += `: ${(error as any).message}`;
    }
    ElMessage.error(errorMessage);
  }
};

// 处理失败文件重试上传
const handleRetryUpload = async (fileId: string | number) => {
  try {
    // 定位条目
    const entry = uploadingFiles.value.find(
      (f) =>
        String(f.id) === String(fileId) || String(f.fileId) === String(fileId),
    );
    if (!entry) return;

    // 拉取原文件 Blob
    const resp = await downloadFile(entry.fileId || fileId);
    const blob: Blob = (resp as any)?.data || (resp as any);
    if (!(blob instanceof Blob)) {
      throw new Error("重试失败:下载原文件失败");
    }

    // 还原 File 对象
    const file = new File([blob], entry.name, {
      type: blob.type || "application/octet-stream",
    });

    // 先删除旧文件(软删除)
    try {
      await deleteFileApi(entry.fileId || fileId);
      fileListRef.value?.refresh?.();
    } catch (delErr: any) {
      throw new Error(
        delErr?.response?.data?.message || delErr?.message || "删除旧文件失败",
      );
    }

    // 将条目标记为上传中并重置文案(不清零进度,保留已展示的最小值)
    entry.status = "uploading";
    entry.statusText = "重新上传中...";
    if (!entry.progress || entry.progress < 5) entry.progress = 5;
    (entry as any).requestProgress = 0;
    (entry as any).serverProgress = 0;

    // 复用批量上传逻辑(单文件当批量)
    let lastOverall = 0;
    let newUploadId: string | null = null;
    const REQUEST_WEIGHT = 40;
    const SERVER_WEIGHT = 60;
    const response = await uploadBatchFiles([file], activeFolderId.value, {
      onUploadId: (id) => {
        newUploadId = id;
        entry.uploadId = `auto-0-${id}`;

        // 监听新批次进度(仅影响该条目),尽早启动避免进度跳变
        listenBatchProgress(
          id,
          (progress, eventType) => {
          if (eventType === "batch-progress" && progress.fileProgresses) {
            const fp =
              progress.fileProgresses[entry.uploadId] ||
              progress.fileProgresses[entry.name];
            if (fp) {
              const nextPct = Math.round(fp.percentage || 0);
              (entry as any).serverProgress = Math.max(
                (entry as any).serverProgress || 0,
                nextPct,
              );
              const reqRaw = Number((entry as any).requestProgress || 0);
              const req = Math.max(0, Math.min(100, Math.floor(reqRaw || 0)));
              const server = Math.max(0, Math.min(100, nextPct));
              const effectiveReq = req > 0 ? req : server;
              const composed = Math.floor(
                (effectiveReq * REQUEST_WEIGHT + server * SERVER_WEIGHT) / 100,
              );
              entry.progress = Math.max(entry.progress || 0, composed);
              entry.status = "uploading";
              if (entry.statusText !== "上传完成") {
                entry.statusText = fp.message || entry.statusText || "";
              }
              if (fp.status === "COMPLETED" || nextPct >= 100) {
                (entry as any).requestProgress = 100;
                (entry as any).serverProgress = 100;
                entry.progress = 100;
                entry.status = "completed";
                entry.statusText = "上传完成";
              }
            } else if (progress.overallPercentage != null) {
              const overall = Math.round(progress.overallPercentage);
              if (
                overall > 0 &&
                overall >= lastOverall &&
                overall > (entry.progress || 0)
              ) {
                (entry as any).serverProgress = Math.max(
                  (entry as any).serverProgress || 0,
                  overall,
                );
                const reqRaw = Number((entry as any).requestProgress || 0);
                const req = Math.max(0, Math.min(100, Math.floor(reqRaw || 0)));
                const server = Math.max(0, Math.min(100, overall));
                const effectiveReq = req > 0 ? req : server;
                const composed = Math.floor(
                  (effectiveReq * REQUEST_WEIGHT + server * SERVER_WEIGHT) / 100,
                );
                entry.progress = Math.max(entry.progress || 0, composed);
              }
              lastOverall = Math.max(lastOverall, overall);
            }
          }
          // file-complete / stage-changed 属于解析/入库阶段,这里不再处理
          if (eventType === "file-error") {
            entry.status = "error";
            entry.statusText = (progress as any)?.message || "处理失败";
            if (!entry.progress || entry.progress < 5) entry.progress = 5;
            fileListRef.value?.refresh?.();
          }
          // ignore stage-changed
          },
          () => {
          // 完成回调(保持当前条目状态)
          if (entry.status !== "error") {
            entry.status = "completed";
            entry.progress = 100;
            entry.statusText = "上传完成";
          }
          fileListRef.value?.refresh?.();
          },
          (err) => {
          entry.status = "error";
          entry.statusText = err?.message || "重试失败";
          if (!entry.progress || entry.progress < 5) entry.progress = 5;
          fileListRef.value?.refresh?.();
          },
        );
      },
      onRequestUploadProgress: ({ percent }) => {
        const req = Math.max(0, Math.min(100, Math.floor(percent || 0)));
        (entry as any).requestProgress = Math.max(
          (entry as any).requestProgress || 0,
          req,
        );
        const server = Math.max(
          0,
          Math.min(100, Math.floor((entry as any).serverProgress || 0)),
        );
        const effectiveReq = (entry as any).requestProgress > 0 ? (entry as any).requestProgress : server;
        const composed = Math.floor(
          (effectiveReq * REQUEST_WEIGHT + server * SERVER_WEIGHT) / 100,
        );
        entry.progress = Math.max(entry.progress || 0, composed);
      },
    });

    // 兜底:如果回调未触发,尝试从响应获取 uploadId(此时进度可能仍会跳,但至少不阻断流程)
    if (!newUploadId) {
      newUploadId = (response as any)?.uploadId ?? null;
      if (newUploadId) {
        entry.uploadId = `auto-0-${newUploadId}`;
      }
    }

    // 请求结束后补齐 requestProgress=100
    (entry as any).requestProgress = Math.max((entry as any).requestProgress || 0, 100);
  } catch (e: any) {
    ElMessage.error(e?.message || "重试上传失败");
  }
};

// 打开回收站
const openRecycleBin = () => {
  isRecycleBinMode.value = true;
  currentFolderName.value = t("KnowledgeBase.recycleBin");
};

// 关闭回收站
// const closeRecycleBin = () => {
//   isRecycleBinMode.value = false;
//   currentFolderName.value = t("KnowledgeBase.allFiles");
// };

// 打开重命名文件夹对话框
const openRenameFolder = (folder: FolderItem) => {
  renameFolderObj.value = folder;
  showRenameFolder.value = true;
};

// 打开重命名文件对话框
const openRenameFile = (file: FileItem) => {
  renameFileObj.value = file;
  showRenameFileDialog.value = true;
};

// 创建文件夹
const handleCreateFolder = async (data: {
  folderName: string;
  parentId: string | number | null;
}) => {
  try {
    await createFolderApi({
      name: data.folderName,
      parentId: data.parentId ?? undefined,
    });
    ElMessage.success(t("KnowledgeBase.createFolderSuccess"));
    showNewFolder.value = false;
    
    // 刷新文件夹树,传入父目录ID以进行局部刷新
    // 如果 parentId 为 null 或 undefined,传入 -1 刷新根目录
    const refreshId = (data.parentId === null || data.parentId === undefined) ? -1 : data.parentId;
    
    // 延迟一小段时间刷新,确保后端数据同步完成
    setTimeout(async () => {
      const currentTreeRef = currentTab.value === 'knowledge' 
        ? folderTreeRef.value 
        : currentTab.value === 'case'
          ? caseFolderTreeRef.value
          : imagingFolderTreeRef.value;
      await currentTreeRef?.refresh(refreshId);
      // 同时刷新文件列表,以显示新创建的文件夹(如果当前就在该目录下)
      fileListRef.value?.refresh();
      // 发送全局刷新信号
      appStore.triggerRefreshFileHierarchy(refreshId);
    }, 300);
  } catch (error) {
    console.error("创建文件夹失败:", error);
    ElMessage.error(t("KnowledgeBase.createFolderFailed"));
  }
};

// 重命名文件夹
const handleRenameFolder = async (data: {
  id: string | number;
  name: string;
}) => {
  try {
    // 查找要重命名的文件夹
    const oldFolder = findFolderById(data.id);
    if (!oldFolder) {
      console.error("找不到要重命名的文件夹:", data.id);
      ElMessage.error(t("KnowledgeBase.folderNotFound"));
      return;
    }

    // 直接调用重命名 API(不再需要二次确认)
    const response = await renameFolderApi(data.id, data.name);

    // 检查 API 响应状态
    if (response && response.status === 200) {
      ElMessage.success(t("KnowledgeBase.renameFolderSuccess"));

      // 关闭对话框
      showRenameFolder.value = false;

      // 刷新文件夹树,传入父目录ID以更新显示
      const parentId = oldFolder.parentId;
      const refreshId = (parentId === null || parentId === undefined) ? -1 : parentId;
      const currentTreeRef = currentTab.value === 'knowledge' 
        ? folderTreeRef.value 
        : currentTab.value === 'case'
          ? caseFolderTreeRef.value
          : imagingFolderTreeRef.value;
      await currentTreeRef?.refresh(refreshId);
      // 发送全局刷新信号
      appStore.triggerRefreshFileHierarchy(refreshId);

      // 如果重命名的是当前选中的文件夹,更新显示名称
      if (activeFolderId.value === data.id) {
        currentFolderName.value = data.name;
        // 更新面包屑路径
        const updatedFolder = findFolderById(data.id);
        if (updatedFolder) {
          updateBreadcrumbPath(updatedFolder);
        }
      }
    } else {
      // API 返回错误状态
      const errorMsg =
        (response as any)?.data?.message ||
        t("KnowledgeBase.renameFolderFailed");
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    if (error === "cancel") {
      return;
    }
    let errorMessage = t("KnowledgeBase.renameFolderFailed");
    if ((error as any)?.response?.data?.message) {
      errorMessage += `: ${(error as any).response.data.message}`;
    } else if ((error as any)?.message) {
      errorMessage += `: ${(error as any).message}`;
    }
    ElMessage.error(errorMessage);
  }
};

// 创建文件
const handleCreateFile = async (data: {
  name: string;
  folderId?: string | number;
  type?: string;
}) => {
  try {
    // 创建 md 文件,添加初始内容
    const fileName = data.name;
    const fileContent = "# " + fileName.replace(".md", "") + "\n\n"; // 添加标题作为初始内容

    // 创建 Blob 对象
    const blob = new Blob([fileContent], { type: "text/markdown" });

    // 创建 File 对象
    const file = new File([blob], fileName, {
      type: "text/markdown",
      lastModified: Date.now(),
    });

    // 使用上传 API 上传新建的文件
    const folderId = data.folderId || activeFolderId.value;

    const response = await uploadBatchFiles([file], folderId);

    // console.log("新建文件上传 API 响应:", response);

    ElMessage.success(t("KnowledgeBase.createFileSuccess"));

    // 关闭对话框
    showNewFile.value = false;

    // 刷新文件列表
    await fileListRef.value?.refresh();
    // 发送全局刷新信号
    appStore.triggerRefreshFileHierarchy(folderId);

    // 等待文件列表更新后,查找并打开新创建的文件
    await nextTick();
    
    // 通过文件名查找并打开文件
    const findAndOpenFile = async (retryCount = 0) => {
      try {
        // 获取当前文件夹的文件列表
        const folderIdToSearch = folderId || activeFolderId.value;
        const filesResponse = await getFiles(folderIdToSearch);
        
        if (filesResponse && filesResponse.data) {
          const files = filesResponse.data.files || filesResponse.data || [];
          // 通过文件名查找新创建的文件
          const newFile = files.find((f: FileItem) => f.name === fileName && f.type !== 'folder');
          
          if (newFile) {
            // 找到文件,直接打开
            await handleFileClick(newFile);
          } else if (retryCount < 3) {
            // 如果找不到文件,可能是后端还在同步,延迟重试
            console.log(`未找到文件 ${fileName},${500 * (retryCount + 1)}ms 后重试...`);
            setTimeout(() => {
              findAndOpenFile(retryCount + 1);
            }, 500 * (retryCount + 1));
          } else {
            console.warn(`多次重试后仍未找到文件: ${fileName}`);
          }
        }
      } catch (error) {
        console.error("查找并打开文件失败:", error);
      }
    };
    
    // 延迟一点时间确保文件列表已更新
    setTimeout(() => {
      findAndOpenFile();
    }, 300);
  } catch (error) {
    let errorMessage = t("KnowledgeBase.createFileFailed");
    if ((error as any)?.response?.data?.message) {
      errorMessage += `: ${(error as any).response.data.message}`;
    } else if ((error as any)?.message) {
      errorMessage += `: ${(error as any).message}`;
    }
    ElMessage.error(errorMessage);
  }
};

// 重命名文件
const handleRenameFile = async (data: Partial<FileItem>) => {
  try {
    if (!data.id || !data.name) {
      throw new Error("文件ID或名称缺失");
    }
    await renameFileApi(data.id, data.name);
    ElMessage.success(t("KnowledgeBase.renameFileSuccess"));
    showRenameFileDialog.value = false;
    fileListRef.value?.refresh();
    // 发送全局刷新信号
    appStore.triggerRefreshFileHierarchy(activeFolderId.value);
  } catch (error) {
    console.error("重命名文件失败:", error);
    ElMessage.error(t("KnowledgeBase.renameFileFailed"));
  }
};

// 处理文件上传(TOS 直传路径)
const handleUploadFilesViaTos = async (files: File[]) => {
  uploadProgressVisible.value = true;

  const newUploadFiles = files.map((file) => ({
    id: Math.random().toString(36).substring(7),
    name: file.name,
    size: file.size,
    progress: 0,
    status: "uploading" as const,
    uploadId: null as string | null,
    fileIndex: 0,
    requestProgress: 0,
    serverProgress: 0,
  }));
  uploadingFiles.value = [...uploadingFiles.value, ...newUploadFiles];
  const startIdx = uploadingFiles.value.length - files.length;

  try {
    const results = await uploadFilesToTos(files, {
      userId: (authStore as any).userId ?? (authStore as any).user?.id ?? "u",
      onFileProgress: (fileIndex, percent) => {
        const entry = uploadingFiles.value[startIdx + fileIndex];
        if (entry && entry.status === "uploading") {
          entry.progress = Math.max(entry.progress, percent);
        }
      },
    });

    // 逐个注册文件元信息
    for (let i = 0; i < results.length; i++) {
      const r = results[i];
      const entry = uploadingFiles.value[startIdx + i];
      try {
        let parentId: number | null = null;
        const pid = activeFolderId.value;
        if (pid !== -1 && pid !== "root" && pid !== "-1") {
          parentId = Number(pid);
        }

        await registerUploadedFile({
          id: null,
          parentId,
          originalFileName: r.originalFileName,
          storageKey: r.storageKey,
          storageUrl: r.storageUrl,
          fileSize: r.fileSize,
          mimeType: r.mimeType,
        });

        if (entry) {
          entry.progress = 100;
          entry.status = "completed";
        }
      } catch (err: any) {
        if (entry) {
          entry.status = "error";
          entry.progress = Math.max(entry.progress, 5);
        }
        console.error(`注册文件 ${r.originalFileName} 失败:`, err);
      }
    }

    ElMessage.success(t("KnowledgeBase.uploadSuccess"));
    fileListRef.value?.refresh();
    appStore.triggerRefreshFileHierarchy(activeFolderId.value);

    // 触发新手任务:文件上传
    triggerNewbieTask("file_upload");

    setTimeout(() => {
      if (uploadingFiles.value.every((f) => ["completed", "error", "cancelled"].includes(f.status))) {
        uploadProgressVisible.value = false;
      }
    }, 1000);
  } catch (error: any) {
    uploadingFiles.value.slice(startIdx).forEach((f) => {
      if (f.status === "uploading") f.status = "error";
    });
    ElMessage.error(error?.message || t("KnowledgeBase.uploadFailed"));
  }
};

// 支持的文件类型(与 FolderTree 上传按钮一致)
const ACCEPTABLE_FILE_EXTENSIONS =
  ".pdf,.doc,.docx,.txt,.md,.xls,.xlsx,.ppt,.pptx,.jpg,.jpeg,.png,.gif,.mp3,.mp4,.wav,.m4a,.ogg,.webm,.avi,.mov"
    .split(",")
    .map((ext) => ext.trim().toLowerCase());

const isAcceptableFile = (file: File): boolean => {
  const name = file.name.toLowerCase();
  const hasValidExt = ACCEPTABLE_FILE_EXTENSIONS.some((ext) =>
    name.endsWith(ext)
  );
  // 排除文件夹(从系统拖入的文件夹通常 size 为 0 且无扩展名、无 type)
  if (file.size === 0 && !hasValidExt && !file.type) return false;
  return hasValidExt || file.type !== "";
};

// 从系统文件管理器拖拽上传:拖入内容区域时
// preventDefault + stopPropagation 避免浏览器默认打开文件、不关闭系统文件管理器
const handleContentDragOver = (e: DragEvent) => {
  if (isRecycleBinMode.value) return;
  e.preventDefault();
  e.stopPropagation();
  if (e.dataTransfer) e.dataTransfer.dropEffect = "copy";
};

const handleContentDragEnter = (e: DragEvent) => {
  if (isRecycleBinMode.value) return;
  e.preventDefault();
  e.stopPropagation();
  dragEnterCounter.value++;
  // 仅当拖入的是文件时显示遮罩(排除从页面内部拖拽的文本等)
  if (e.dataTransfer?.types?.includes("Files")) {
    isDragOver.value = true;
  }
};

// 拖回系统文件管理器(dragleave)视为取消,仅清除悬停状态,不触发上传
const handleContentDragLeave = (e: DragEvent) => {
  if (isRecycleBinMode.value) return;
  e.stopPropagation();
  dragEnterCounter.value--;
  if (dragEnterCounter.value <= 0) {
    dragEnterCounter.value = 0;
    isDragOver.value = false;
  }
};

const handleContentDrop = (e: DragEvent) => {
  if (isRecycleBinMode.value) return;
  e.preventDefault();
  e.stopPropagation();
  dragEnterCounter.value = 0;
  isDragOver.value = false;

  const files = e.dataTransfer?.files;
  if (!files || files.length === 0) return;

  const validFiles = Array.from(files).filter(isAcceptableFile);
  if (validFiles.length === 0) {
    ElMessage.warning(
      t("KnowledgeBase.dropOnlyFiles") ||
        "请拖入支持的文件类型(如 PDF、Word、图片等)"
    );
    return;
  }
  handleUploadFiles(validFiles);
};

// 处理文件上传
const handleUploadFiles = async (files: File[]) => {
  const useTos = import.meta.env.VITE_USE_TOS_DIRECT_UPLOAD === "true";
  if (useTos) {
    return handleUploadFilesViaTos(files);
  }
  // 检查文件大小限制(100MB)
  const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
  const oversizedFiles: File[] = [];
  
  files.forEach((file) => {
    if (file.size > MAX_FILE_SIZE) {
      oversizedFiles.push(file);
    }
  });
  
  if (oversizedFiles.length > 0) {
    const errorMessages = oversizedFiles.map(
      (file) => `${file.name}: ${t("KnowledgeBase.fileSizeExceeded")}`
    );
    ElMessage.warning(errorMessages.join("\n"));
    return;
  }
  
  uploadProgressVisible.value = true;

  // 将新文件添加到上传列表(保留历史记录)
  const newUploadFiles = files.map((file, index) => ({
    id: Math.random().toString(36).substring(7),
    name: file.name,
    size: file.size,
    progress: 0,
    status: "uploading" as const,
    uploadId: null as string | null, // 用于匹配 SSE 进度
    fileIndex: index, // 用于匹配文件顺序
    // 两段式:request(浏览器->后端) + server(后端接收/存储)
    requestProgress: 0,
    serverProgress: 0,
  }));

  // 追加到现有列表,而不是替换
  uploadingFiles.value = [...uploadingFiles.value, ...newUploadFiles];

  let progressListener: { close: () => void } | null = null;

  try {
    // 1. 一拿到 uploadId 就启动 SSE 进度监听(避免等 /upload/batch 响应后才监听导致进度跳变)
    const startIdx = Math.max(0, uploadingFiles.value.length - files.length);
    const REQUEST_WEIGHT = 40;
    const SERVER_WEIGHT = 60;
    let uploadId: string | null = null;
    let lastOverallBatchProgress = 0;

    const response = await uploadBatchFiles(files, activeFolderId.value, {
      onUploadId: (id) => {
        uploadId = id;

        // 将本批次新文件的 uploadId 与后端保持一致(auto-{index}-{uploadId}),用于匹配 SSE 进度
        try {
          for (let i = 0; i < files.length; i++) {
            const listItem = uploadingFiles.value[startIdx + i];
            if (listItem) {
              listItem.uploadId = `auto-${i}-${uploadId}`;
            }
          }
        } catch (e) {
          console.warn("设置文件uploadId失败,但不影响上传流程", e);
        }

        progressListener = listenBatchProgress(
          uploadId,
        // 进度回调
        (progress, eventType) => {
          // 如果文件已被取消,则不更新其状态
          if (eventType === "batch-progress" && progress.fileProgresses) {
            // 更新每个文件的进度
            let matchedAny = false;
            Object.entries(progress.fileProgresses).forEach(
              ([fileUploadId, fileProgress]: [string, any]) => {
                // 尝试通过文件名匹配(因为后端可能返回文件名作为 key)
                const matchedFile = uploadingFiles.value.find(
                  (f) => f.uploadId === fileUploadId || f.name === fileUploadId,
                );

                if (matchedFile && matchedFile.status !== "cancelled") {
                  matchedAny = true;
                  const nextPct = Math.round(fileProgress.percentage || 0);
                  // 记录 server 进度(不回退)
                  (matchedFile as any).serverProgress = Math.max(
                    (matchedFile as any).serverProgress || 0,
                    nextPct,
                  );
                  // 保存后端返回的 fileId,便于后续通过 fileId 精确匹配
                  if (fileProgress.fileId != null) {
                    matchedFile.fileId = fileProgress.fileId;
                  }
                  // 两段式合成:request + server(只用于展示,不改变后端语义)
                  const reqRaw = Number((matchedFile as any).requestProgress || 0);
                  const req = Math.max(0, Math.min(100, Math.floor(reqRaw || 0)));
                  const server = Math.max(0, Math.min(100, nextPct));
                  const effectiveReq = req > 0 ? req : server; // request 未上报时用 server 兜底
                  const composed = Math.floor(
                    (effectiveReq * REQUEST_WEIGHT + server * SERVER_WEIGHT) / 100,
                  );
                  matchedFile.progress = Math.max(matchedFile.progress || 0, composed);
                  matchedFile.status = "uploading";
                  matchedFile.statusText = fileProgress.message || "";
                  // 若已完成,强制置为 100
                  if (fileProgress.status === "COMPLETED" || nextPct >= 100) {
                    (matchedFile as any).requestProgress = 100;
                    (matchedFile as any).serverProgress = 100;
                    matchedFile.progress = 100;
                    matchedFile.status = "completed";
                  }
                }
              },
            );

            // 如果没有匹配到具体文件,使用整体进度
            if (
              (Object.keys(progress.fileProgresses).length === 0 ||
                matchedAny === false) &&
              progress.overallPercentage !== undefined
            ) {
              const avgProgress = Math.round(progress.overallPercentage);
              // 忽略无效或回退的整体进度
              if (avgProgress > 0 && avgProgress >= lastOverallBatchProgress) {
                uploadingFiles.value.forEach((f) => {
                  if (f.status === "uploading" && avgProgress > f.progress) {
                    // 整体进度作为 server 兜底
                    (f as any).serverProgress = Math.max(
                      (f as any).serverProgress || 0,
                      avgProgress,
                    );
                    const reqRaw = Number((f as any).requestProgress || 0);
                    const req = Math.max(0, Math.min(100, Math.floor(reqRaw || 0)));
                    const server = Math.max(0, Math.min(100, avgProgress));
                    const effectiveReq = req > 0 ? req : server;
                    const composed = Math.floor(
                      (effectiveReq * REQUEST_WEIGHT + server * SERVER_WEIGHT) /
                        100,
                    );
                    f.progress = Math.max(f.progress || 0, composed);
                  }
                });
                lastOverallBatchProgress = Math.max(
                  lastOverallBatchProgress,
                  avgProgress,
                );
              }
            }
          }

          // 单文件错误:标记失败、展示错误信息、不回退进度,并刷新列表
          if (eventType === "file-error") {
            const fileId = (progress as any)?.fileId;
            const message = (progress as any)?.message || "处理失败";
            const target = uploadingFiles.value.find(
              (f) => String(f.fileId) === String(fileId),
            );
            if (target && target.status !== "cancelled") {
              // 如果文件已上传完成(落盘完成),忽略后续解析阶段的 error,避免“上传成功却变失败”
              const serverPct = Number((target as any).serverProgress ?? target.progress ?? 0);
              if (serverPct >= 100 || target.status === "completed") return;
              target.status = "error";
              if (!target.progress || target.progress < 5) {
                target.progress = 5; // 显示为失败但不为 0
              }
              target.statusText = message;
            }
            try {
              fileListRef.value?.refresh?.();
            } catch (e) {
              // ignore
            }
          }
        },
        // 完成回调
        (progress) => {
          // 标记所有文件为成功
          uploadingFiles.value.forEach((f) => {
            if (f.status === "uploading") {
              f.status = "completed";
              f.progress = 100;
              f.statusText = "上传完成";
            }
          });

          ElMessage.success(
            activeFolderId.value === -1 || !activeFolderId.value
              ? t("KnowledgeBase.uploadToRootSuccess") || "文件已保存至知识库根目录"
              : t("KnowledgeBase.uploadSuccess") || "上传成功",
          );
          fileListRef.value?.refresh();
          // 发送全局刷新信号
          appStore.triggerRefreshFileHierarchy(activeFolderId.value);

          // 触发新手任务:文件上传
          triggerNewbieTask("file_upload");

          // 移除监听器
          activeListeners.value.delete(uploadId);

          // 延迟 1 秒关闭,以便用户看清“上传完成”状态
          setTimeout(() => {
            // 检查是否还有正在上传的其他批次
            if (activeListeners.value.size === 0) {
              uploadProgressVisible.value = false;
            }
          }, 1000);
        },
        // 错误回调
        (error) => {
          console.error("上传失败:", error);

          uploadingFiles.value.forEach((f) => {
            if (f.status === "uploading") {
              f.status = "error";
            }
          });

          ElMessage.error(error.message || t("KnowledgeBase.uploadFailed"));
          
          // 移除监听器
          activeListeners.value.delete(uploadId);
        },
      );

      // 存储监听器以便取消
      activeListeners.value.set(uploadId, progressListener);
      },
      onRequestUploadProgress: ({ percent }) => {
        // request(浏览器->后端)进度:占用前半段比例,不再直接等同于 progress
        const req = Math.max(0, Math.min(100, Math.floor(percent || 0)));
        for (let i = 0; i < files.length; i++) {
          const item = uploadingFiles.value[startIdx + i] as any;
          if (!item) continue;
          if (item.status !== "uploading") continue;
          item.requestProgress = Math.max(item.requestProgress || 0, req);
          const server = Math.max(0, Math.min(100, Math.floor(item.serverProgress || 0)));
          const effectiveReq = item.requestProgress > 0 ? item.requestProgress : server;
          const composed = Math.floor(
            (effectiveReq * REQUEST_WEIGHT + server * SERVER_WEIGHT) / 100,
          );
          item.progress = Math.max(item.progress || 0, composed);
          if (!item.statusText) item.statusText = "上传中...";
        }
      },
    });

    // 极端情况下(回调未触发),用响应兜底
    if (!uploadId) {
      uploadId = (response as any)?.uploadId ?? null;
    }

    // 请求结束后补齐 requestProgress=100(有些浏览器/代理可能不触发最后一次 100% 进度事件)
    for (let i = 0; i < files.length; i++) {
      const item = uploadingFiles.value[startIdx + i] as any;
      if (!item) continue;
      if (item.status !== "uploading") continue;
      item.requestProgress = Math.max(item.requestProgress || 0, 100);
      const server = Math.max(0, Math.min(100, Math.floor(item.serverProgress || 0)));
      const composed = Math.floor((100 * REQUEST_WEIGHT + server * SERVER_WEIGHT) / 100);
      item.progress = Math.max(item.progress || 0, composed);
    }

    // 如果没有 uploadId,采用降级处理
    if (!uploadId) {
      // 如果没有 uploadId,采用降级处理
      console.warn("未获取到 uploadId,无法监听进度");

      // 等待一段时间后标记为完成
      setTimeout(() => {
        uploadingFiles.value.forEach((f) => {
          f.status = "completed";
          f.progress = 100;
        });

        ElMessage.success(t("KnowledgeBase.uploadSuccess"));
        fileListRef.value?.refresh();
        // 发送全局刷新信号
        appStore.triggerRefreshFileHierarchy(activeFolderId.value);

        // 延迟 1 秒关闭,以便用户看清“上传完成”状态
        setTimeout(() => {
          uploadProgressVisible.value = false;
        }, 1000);
      }, 2000);
    }
  } catch (error) {
    console.error("文件上传失败:", error);

    // 关闭进度监听
    if (progressListener) {
      progressListener.close();
    }

    uploadingFiles.value.forEach((f) => {
      if (f.status === "uploading") {
        f.status = "error";
      }
    });

    let errorMessage = t("KnowledgeBase.uploadFailed");
    if ((error as any)?.response?.data?.message) {
      errorMessage += `: ${(error as any).response.data.message}`;
    } else if ((error as any)?.message) {
      errorMessage += `: ${(error as any).message}`;
    }
    ElMessage.error(errorMessage);
  }
};

// 处理下载文件夹
const handleDownloadFolder = async (folder: FolderItem) => {
  if (!folder) return;

  try {
    // 调用下载API
    const response = await downloadFolderApi(folder.id);

    // 处理响应对象,提取 blob 数据
    let blob: Blob;
    if (response && (response as any).data) {
      blob = (response as any).data;
    } else {
      blob = response as any;
    }

    if (blob instanceof Blob) {
      // 创建下载链接
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${folder.name}_${new Date().getTime()}.zip`;
      a.click();
      window.URL.revokeObjectURL(url);

      ElMessage.success(t("KnowledgeBase.folderDownloadSuccess"));
    } else {
      throw new Error(`响应不是有效的 Blob 对象,实际类型: ${typeof blob}`);
    }
  } catch (error) {
    console.error("下载文件夹失败:", error);
    let errorMessage = t("KnowledgeBase.folderDownloadFail");
    if ((error as any)?.message) {
      errorMessage += `: ${(error as any).message}`;
    }
    ElMessage.error(errorMessage);
  }
};

// 处理下载单个文件
const handleDownloadFile = async (file: FileItem) => {
  if (!file) return;

  try {
    // 根据 storageType 决定下载路径
    if ((file as any).storageType === "OSS") {
      const url = await getTosDownloadUrl((file as any).storageKey, file.name);
      const a = document.createElement("a");
      a.href = url;
      a.download = file.name;
      a.click();
      ElMessage.success(t("KnowledgeBase.downloadSuccess") || "下载成功");
      triggerNewbieTask("doc_download_save");
      return;
    }

    const response = await downloadFile(file.id);

    // 处理响应对象,提取 blob 数据
    let blob: Blob;
    if (response && (response as any).data) {
      blob = (response as any).data;
    } else {
      blob = response as any;
    }

    if (blob instanceof Blob) {
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = file.name || "download";
      a.click();
      window.URL.revokeObjectURL(url);
      ElMessage.success(t("KnowledgeBase.downloadSuccess") || "下载成功");
      triggerNewbieTask("doc_download_save");
    } else {
      console.error("响应不是 Blob 类型:", blob);
      ElMessage.error(
        t("KnowledgeBase.downloadFormatError") || "下载失败:响应格式错误",
      );
    }
  } catch (error) {
    console.error("下载文件失败:", error);
    let errorMessage = t("KnowledgeBase.downloadFail") || "下载失败";
    if ((error as any)?.response?.status === 401) {
      errorMessage =
        t("KnowledgeBase.downloadUnauthorized") ||
        "下载失败:未授权,请重新登录";
    } else if ((error as any)?.message) {
      errorMessage += `: ${(error as any).message}`;
    }
    ElMessage.error(errorMessage);
  }
};


// 处理文件夹删除
// const handleFolderDeleted = () => {
//   fileListRef.value?.refresh();
// };

// 处理文件删除
const handleFileDeleted = () => {
  // 可以添加其他逻辑
};

// 处理文件列表中删除文件夹后的同步
const handleFolderDeletedInList = () => {
  folderTreeRef.value?.refresh();
  caseFolderTreeRef.value?.refresh();
  imagingFolderTreeRef.value?.refresh();
  // 发送全局刷新信号
  appStore.triggerRefreshFileHierarchy();
};

// 处理回收站项目还原
const handleItemsRestored = () => {
  folderTreeRef.value?.refresh();
  caseFolderTreeRef.value?.refresh();
  imagingFolderTreeRef.value?.refresh();
  if (!isRecycleBinMode.value) {
    fileListRef.value?.refresh();
  }
  // 发送全局刷新信号
  appStore.triggerRefreshFileHierarchy();
};

// 处理回收站项目删除
const handleItemsDeleted = () => {
  // 发送全局刷新信号
  appStore.triggerRefreshFileHierarchy();
};

// 处理回收站清空
const handleRecycleBinEmptied = () => {
  // 发送全局刷新信号
  appStore.triggerRefreshFileHierarchy();
};

// 处理文件点击(双击文件跳转到工作台)
// 从文件名推断文件类型
const getFileTypeFromName = (fileName: string): string => {
  if (!fileName) return "unknown";

  const ext = fileName.split(".").pop()?.toLowerCase();

  const typeMap: Record<string, string> = {
    md: "md",
    pdf: "pdf",
    doc: "word",
    docx: "word",
    xls: "spreadsheet",
    xlsx: "spreadsheet",
    csv: "spreadsheet",
    ppt: "presentation",
    pptx: "presentation",
    txt: "text",
    json: "text",
    xml: "text",
    html: "text",
    css: "text",
    js: "text",
    py: "text",
    java: "text",
    c: "text",
    cpp: "text",
    jpg: "image",
    jpeg: "image",
    png: "image",
    gif: "image",
    svg: "image",
    webp: "image",
    bmp: "image",
    mp3: "audio",
    wav: "audio",
    ogg: "audio",
    flac: "audio",
    aac: "audio",
    mp4: "video",
    webm: "video",
    ogv: "video",
    mov: "video",
  };

  return typeMap[ext || ""] || "unknown";
};

const handleFileClick = async (file: FileItem) => {
  // 使用 getFileTypeFromName 来正确映射文件类型
  const fileType = file.type || getFileTypeFromName(file.name);

  // 构建路由参数
  const routeParams = {
    name: "Workspace",
    query: {
      fileId: String(file.id),
      fileName: file.name,
      fileType: fileType,
      fromKnowledgeBase: "true", // 标记来自知识库,需要重新加载历史记录
    },
  };

  // 跳转到工作台编辑文件,添加标记以触发历史记录重新加载
  try {
    await router.push(routeParams);
  } catch (error) {
    // 忽略导航取消错误
    if (
      error instanceof Error &&
      error.message.includes("Navigation cancelled")
    ) {
      console.log("路由导航被取消,忽略此错误");
    } else {
      console.error("❌ 路由导航失败:", error);
      ElMessage.error(
        `打开文件失败: ${error instanceof Error ? error.message : "未知错误"}`,
      );
    }
  }
};

// 侧边栏拉伸相关
const startResize = (e: MouseEvent | TouchEvent) => {
  isResizing.value = true;
  const clientX = e instanceof MouseEvent ? e.clientX : e.touches[0]?.clientX ?? 0;
  startX.value = clientX;
  startWidth.value = sidebarWidth.value;
  document.body.style.cursor = "col-resize";
  document.body.style.userSelect = "none";
};

const startGeneratorResize = (e: MouseEvent | TouchEvent) => {
  isResizingGenerator.value = true;
  const clientX = e instanceof MouseEvent ? e.clientX : e.touches[0]?.clientX ?? 0;
  startXGenerator.value = clientX;
  startWidthGenerator.value = generatorWidth.value;
  document.body.style.cursor = "col-resize";
  document.body.style.userSelect = "none";
};

const handleMouseMove = (e: MouseEvent | TouchEvent) => {
  const clientX = e instanceof MouseEvent ? e.clientX : e.touches[0]?.clientX ?? 0;

  if (isResizing.value) {
    const delta = clientX - startX.value;
    const newWidth = startWidth.value + delta;

    const minSidebarWidth = window.innerWidth <= 1024 ? 150 : 200;
    // 限制最小和最大宽度
    if (newWidth >= minSidebarWidth && newWidth <= 600) {
      sidebarWidth.value = newWidth;
    } else if (newWidth < minSidebarWidth) {
      sidebarWidth.value = minSidebarWidth;
    } else if (newWidth > 600) {
      sidebarWidth.value = 600;
    }
  } else if (isResizingGenerator.value) {
    const delta = startXGenerator.value - clientX;
    const newWidth = startWidthGenerator.value + delta;

    const minGeneratorWidth = window.innerWidth <= 1024 ? 200 : 300;
    // 限制最小和最大宽度
    if (newWidth >= minGeneratorWidth && newWidth <= 600) {
      generatorWidth.value = newWidth;
    } else if (newWidth < minGeneratorWidth) {
      generatorWidth.value = minGeneratorWidth;
    } else if (newWidth > 600) {
      generatorWidth.value = 600;
    }
  }
};

const handleMouseUp = () => {
  if (isResizing.value || isResizingGenerator.value) {
    isResizing.value = false;
    isResizingGenerator.value = false;
    document.body.style.cursor = "";
    document.body.style.userSelect = "";
  }
};

// IntelligencePanel 最小化状态
const isIntelligencePanelMinimized = ref(false);

// 处理智能面板最小化状态变化
const handleIntelligencePanelMinimize = (minimized: boolean) => {
  console.log('[KnowledgeBase] 智能面板最小化状态变化:', minimized);
  isIntelligencePanelMinimized.value = minimized;
};

// 监听 props.defaultTab 变化
watch(() => props.defaultTab, (newTab) => {
  if (newTab) {
    currentTab.value = newTab;
  }
});

// 生命周期
onMounted(() => {
  document.addEventListener("mousemove", handleMouseMove);
  document.addEventListener("mouseup", handleMouseUp);
  document.addEventListener("touchmove", handleMouseMove, { passive: false });
  document.addEventListener("touchend", handleMouseUp);

  // 恢复回收站模式状态
  const savedRecycleBinMode = localStorage.getItem("kb_is_recycle_bin_mode");
  if (savedRecycleBinMode === "true") {
    isRecycleBinMode.value = true;
    currentFolderName.value = t("KnowledgeBase.recycleBin");
  }
});

// 监听回收站模式变化并保存到 localStorage
watch(isRecycleBinMode, (newVal) => {
  localStorage.setItem("kb_is_recycle_bin_mode", String(newVal));
});

onBeforeUnmount(() => {
  document.removeEventListener("mousemove", handleMouseMove);
  document.removeEventListener("mouseup", handleMouseUp);
  document.removeEventListener("touchmove", handleMouseMove);
  document.removeEventListener("touchend", handleMouseUp);
});
</script>

<style scoped lang="scss">
.knowledge-base-root {
  display: flex;
  height: 100%;
  width: 100%;
  background: var(--color-bg);
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.kb-sidebar {
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
  background: var(--color-card);
  transition: width 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  min-width: 48px;
  max-width: 600px;
  border-right: 1px solid var(--color-border);

  &.is-collapsed {
    .kb-tabs {
      flex-direction: column;
      height: auto;
      padding: 12px 0;
      gap: 16px;
      border-bottom: none;

      .tabs-left {
        flex-direction: column;
        gap: 12px;
      }

      .tabs-right {
        order: -1; // 展开按钮放在最上面
        margin-bottom: 8px;
      }
    }
  }
}

.kb-tabs {
  display: flex;
  height: 40px;
  padding: 0 8px;
  align-items: center;
  justify-content: space-between;
  background: var(--color-card);
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;
  overflow: hidden;

  .tabs-left {
    display: flex;
    gap: 4px;
    align-items: center;
  }

  .tabs-right {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 4px;
    color: var(--color-text-secondary);
    transition: all 0.2s ease;

    &:hover {
      background: var(--color-hover);
      color: var(--color-text);
    }

    i {
      font-size: 14px;
    }
  }

  .kb-tab-item {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.2s ease;
    color: var(--color-text-secondary);

    &:hover {
      background: var(--color-hover);
    }

    &.active {
      background: var(--tab-selected);
      color: var(--color-text);

      .tab-icon {
        filter: brightness(0) saturate(100%) invert(35%) sepia(94%) saturate(4612%) hue-rotate(215deg) brightness(101%) contrast(101%) !important;
      }
    }

    .tab-icon {
      width: 18px;
      height: 18px;
      object-fit: contain;
      transition: all 0.2s ease;
      filter: var(--icon-filter);
    }
  }
}

.kb-sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.library-sidebar-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.library-sidebar-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 16px 14px;
  border-bottom: 1px solid var(--color-border);
  background: rgba(255, 255, 255, 0.02);

  .folder-action-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 16px;
    background: #1e6fff;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;
    width: 100%;
    height: 36px;

    &:hover {
      background: #175ceb;
    }
  }

  .folder-action-btn1 {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 12px 16px;
    background: var(--color-bg);
    color: var(--color-text);
    border-radius: 4px;
    font-size: 14px;
    font-weight: 400;
    cursor: pointer;
    transition: all 0.3s ease;
    white-space: nowrap;
    width: 100%;
    height: 36px;
    border: 1px solid var(--color-border);

    &:hover {
      background: var(--color-hover);
    }

    &.more-btn {
      justify-content: space-between;
      padding: 0 16px;
      
      i {
        font-size: 12px;
        color: var(--color-text-secondary);
      }
    }
  }

  .sidebar-more-dropdown {
    width: 100%;
  }
}

.library-placeholder {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: var(--color-text-secondary);
  font-size: 14px;
  text-align: center;
}

.library-content-placeholder {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: var(--color-bg);
  color: var(--color-text-secondary);

  .placeholder-icon {
    width: 120px;
    height: 120px;
    margin-bottom: 24px;
    opacity: 0.4;
  }

  h2 {
    font-size: 24px;
    margin-bottom: 12px;
    color: var(--color-text);
  }

  p {
    font-size: 16px;
  }
}

.resize-handle {
  width: 0; // 改为 0,避免物理间距
  flex-shrink: 0;
  height: 100%;
  align-self: stretch;
  background: transparent;
  cursor: col-resize;
  position: relative;
  z-index: 10;

  // 增大抓取区域 (透明)
  &::before {
    content: "";
    position: absolute;
    left: -12px;
    right: -12px;
    top: 0;
    bottom: 0;
    background: transparent;
  }

  // 视觉上的高亮线 (细线)
  &::after {
    content: "";
    position: absolute;
    left: 0;
    width: 1px;
    top: 0;
    bottom: 0;
    background: var(--color-border); // 默认显示边框线
    transition: all 0.15s ease;
    pointer-events: none;
  }

  &:hover::after,
  &:active::after {
    background: var(--color-primary);
    width: 2px; // 减小 hover 宽度到 2px
    left: 0;
    z-index: 1;
  }
}

.kb-generator-area {
  flex-shrink: 0;
  flex-grow: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--color-bg);
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  overflow: visible; // 改为 visible,确保恢复按钮可见
  transition: width 0.35s cubic-bezier(0.4, 0, 0.2, 1),
              min-width 0.35s cubic-bezier(0.4, 0, 0.2, 1),
              max-width 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  
  &.resizing {
    transition: none !important; // 正在拖动时禁用过渡动画
  }
  
  &.minimized {
    width: 54px !important;
    min-width: 54px !important;
    max-width: 54px !important;
    overflow: visible; // 最小化时确保可见
  }
  
  :deep(.intelligence-panel-container) {
    height: 100%;
    display: flex;
    flex-direction: column;
    width: 100%;
    overflow: visible; // 确保容器不隐藏恢复按钮
    position: relative; // 为绝对定位的恢复按钮提供定位上下文
  }
  
  :deep(.intelligence-panel) {
    height: 100%;
    display: flex;
    flex-direction: column;
    width: 100% !important;
    min-width: 100% !important;
    max-width: 100% !important;
    flex: 1;
    border: none !important;
  }
  
  // 确保最小化后的恢复按钮正确显示
  :deep(.restore-chat-btn) {
    width: 54px !important; // 固定宽度
    height: 100% !important;
    position: absolute !important; // 使用绝对定位
    right: 0 !important;
    top: 0 !important;
    z-index: 100 !important; // 确保在最上层
    flex-shrink: 0;
  }
}

.kb-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  position: relative;

  &.kb-content-drag-over {
    pointer-events: auto;
  }
}

/* 拖拽上传时的遮罩层 */
.kb-drop-overlay {
  position: absolute;
  inset: 0;
  z-index: 100;
  background: rgba(30, 111, 255, 0.08);
  border: 2px dashed var(--color-primary);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  pointer-events: none;
  animation: kb-drop-pulse 1.5s ease-in-out infinite;
}

@keyframes kb-drop-pulse {
  0%,
  100% {
    opacity: 1;
  }
  50% {
    opacity: 0.85;
  }
}

.kb-drop-overlay-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.kb-drop-icon {
  font-size: 48px;
  color: var(--color-primary);
  opacity: 0.9;
}

.kb-drop-text {
  font-size: 16px;
  color: var(--color-primary);
  font-weight: 500;
}
</style>