VditorEditor.vue 168 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 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774
<template>
  <div class="vditor-markdown-editor">
    <!-- 编辑器区域 -->
    <div class="vditor-wrapper" :style="{ height: editorHeight }">
      <div ref="vditorContainer" class="vditor-container"></div>
      <!-- 加载状态 -->
      <div v-if="isLoading || !vditorInstance" class="editor-loading">
        <i class="fas fa-spinner fa-spin loading-icon"></i>
        <span class="loading-text">{{
          t("reference.loading") || "加载中..."
        }}</span>
      </div>
    </div>

    <!-- 引用标记下拉菜单 -->
    <div
      v-if="showCitationMenu"
      class="citation-menu-wrapper"
      :style="{
        position: 'fixed',
        left: citationMenuPosition.x + 'px',
        top: citationMenuPosition.y + 'px',
        zIndex: 9999,
      }"
    >
      <div ref="citationMenuRef" class="citation-menu">
        <div class="citation-menu-header">
          <span class="header-title">{{ t("reference.selectReference") }}</span>
          <div class="header-search">
            <i class="fas fa-search search-icon"></i>
            <input
              v-model="citationMenuSearch"
              type="text"
              :placeholder="t('reference.searchReferences')"
              class="search-input"
              @click.stop
            />
          </div>
        </div>
        <div class="citation-menu-list">
          <div
            v-for="reference in filteredCitationMenuReferences"
            :key="reference.workId"
            class="citation-menu-item"
            @click.stop="replaceCitation(reference)"
          >
            <span class="menu-item-note">{{
              reference.note || reference.title
            }}</span>
            <span class="menu-item-meta"
              >{{ reference.authorsText }} ({{
                reference.publicationYear
              }})</span
            >
          </div>
          <div
            v-if="
              filteredCitationMenuReferences.length === 0 &&
              references.length > 0
            "
            class="citation-menu-empty"
          >
            {{ t("reference.noMatchingReferences") }}
          </div>
          <div v-if="references.length === 0" class="citation-menu-empty">
            {{ t("reference.noReferences") }}
          </div>
        </div>
      </div>
    </div>

    <!-- 可拖拽的分割条 -->
    <div
      v-if="props.showReferences"
      class="resize-handle"
      @mousedown="startResize"
      @touchstart="startResize"
    ></div>

    <!-- 参考文献管理区域 -->
    <div
      v-if="props.showReferences"
      class="reference-section"
      :style="{ height: referenceHeight }"
    >
      <!-- 工具栏 -->
      <div class="reference-toolbar">
        <!-- 左侧按钮组 -->
        <div class="toolbar-left">
          <button
            class="toolbar-btn"
            :title="t('reference.addReference')"
            @click="openImportDialog"
          >
            <i class="fas fa-file-alt"></i>
          </button>
        </div>

        <!-- 搜索框 -->
        <div class="search-input-wrapper">
          <i class="fas fa-search search-icon"></i>
          <input
            v-model="searchQuery"
            type="text"
            placeholder="All Fields & Tags"
            class="search-input"
            @input="handleSearch"
          />
        </div>
      </div>

      <!-- 参考文献表格 -->
      <div class="reference-table-container">
        <!-- 加载状态 -->
        <div v-if="isLoadingReferences" class="reference-loading">
          <i class="fas fa-spinner fa-spin loading-icon"></i>
          <span class="loading-text">{{ t("reference.loading") }}</span>
        </div>

        <!-- 空状态 - 没有任何文献 -->
        <div v-else-if="references.length === 0" class="reference-empty">
          <i class="fas fa-book-open empty-icon"></i>
          <span class="empty-text">{{ t("reference.noReferences") }}</span>
        </div>

        <!-- 搜索无结果 -->
        <div
          v-else-if="searchQuery.trim() && filteredReferences.length === 0"
          class="reference-empty"
        >
          <i class="fas fa-search empty-icon"></i>
          <span class="empty-text">{{
            t("reference.noMatchingQuery", { query: searchQuery })
          }}</span>
          <span class="empty-hint">{{ t("reference.tryOtherSearch") }}</span>
        </div>

        <!-- 有数据时显示表格 -->
        <table v-else class="reference-table">
          <thead>
            <tr>
              <th>{{ t("reference.serialNumber") }}</th>
              <th>{{ t("reference.name") }}</th>
              <th>{{ t("reference.alias") }}</th>
              <th>{{ t("reference.author") }}</th>
              <th>{{ t("reference.year") }}</th>
              <th>{{ t("reference.details") }}</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="reference in filteredReferences"
              :key="reference.workId"
              :class="{ highlighted: selectedReferenceId === reference.workId }"
              :draggable="true"
              @click="selectReference(reference.workId)"
              @dragstart="handleReferenceDragStart($event, reference)"
            >
              <td>{{ reference.serialNumber }}</td>
              <td class="title-cell">
                <span class="title-text" :title="reference.title">{{
                  reference.title
                }}</span>
              </td>
              <td>
                <!-- 非编辑状态:显示别名文本和编辑按钮 -->
                <div
                  v-if="editingReferenceId !== reference.workId"
                  class="alias-display"
                >
                  <span class="alias-text">{{ reference.note || "-" }}</span>
                  <button
                    class="edit-alias-btn"
                    @click="startEditAlias(reference)"
                    :title="t('reference.editAlias')"
                  >
                    <i class="fas fa-edit"></i>
                  </button>
                </div>
                <!-- 编辑状态:显示输入框 -->
                <div v-else class="alias-edit">
                  <input
                    v-model="editingAlias"
                    type="text"
                    class="alias-input"
                    :placeholder="t('reference.enterAlias')"
                    @keydown.enter="handleEnterKey(reference)"
                    @blur="handleBlur(reference)"
                  />
                </div>
              </td>
              <td>{{ reference.authorsText }}</td>
              <td>{{ reference.publicationYear }}</td>
              <td class="details-cell">
                <div class="detail-icons">
                  <el-popover
                    placement="top-end"
                    :width="400"
                    trigger="click"
                    popper-class="reference-detail-popover"
                  >
                    <template #reference>
                      <i
                        class="fas fa-file-alt icon-b"
                        :title="t('reference.viewDocument')"
                        @click="viewReferenceDetail(reference, $event)"
                      ></i>
                    </template>
                    <div
                      v-if="currentDetailReference?.workId === reference.workId"
                      class="reference-detail-content"
                    >
                      <!-- 加载状态 -->
                      <div v-if="isLoadingDetail" class="detail-loading">
                        <i class="fas fa-spinner fa-spin"></i>
                        <span>{{ t("reference.loading") }}</span>
                      </div>

                      <!-- 详情内容 -->
                      <template v-else-if="currentDetailReference">
                        <div class="detail-item">
                          <div class="detail-label">
                            {{ t("reference.detailLabels.title") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.title }}
                          </div>
                        </div>
                        <div class="detail-item">
                          <div class="detail-label">
                            {{ t("reference.detailLabels.authors") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.authorsText }}
                          </div>
                        </div>
                        <div class="detail-item">
                          <div class="detail-label">
                            {{ t("reference.detailLabels.publicationYear") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.publicationYear }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.publicationDate"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.publicationDate") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.publicationDate }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.itemType"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.type") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.itemType }}
                          </div>
                        </div>
                        <div class="detail-item">
                          <div class="detail-label">
                            {{ t("reference.detailLabels.doi") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.doi || "-" }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.abstractText"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.abstract") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.abstractText }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.venueName"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.venueName") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.venueName }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.journalAbbr"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.journalAbbr") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.journalAbbr }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.issn"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.issn") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.issn }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.volume"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.volume") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.volume }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.issue"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.issue") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.issue }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.pages"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.pages") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.pages }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.language"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.language") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.language }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.landingUrl"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.landingUrl") }}
                          </div>
                          <div class="detail-value">
                            <a
                              :href="currentDetailReference.landingUrl"
                              target="_blank"
                              class="detail-link"
                              >{{ currentDetailReference.landingUrl }}</a
                            >
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.pdfUrl"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.pdfUrl") }}
                          </div>
                          <div class="detail-value">
                            <a
                              :href="currentDetailReference.pdfUrl"
                              target="_blank"
                              class="detail-link"
                              >{{ currentDetailReference.pdfUrl }}</a
                            >
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.source"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.source") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.source }}
                          </div>
                        </div>
                        <div
                          v-if="currentDetailReference.note"
                          class="detail-item"
                        >
                          <div class="detail-label">
                            {{ t("reference.detailLabels.note") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.note }}
                          </div>
                        </div>
                        <div class="detail-item">
                          <div class="detail-label">
                            {{ t("reference.detailLabels.updatedAt") }}
                          </div>
                          <div class="detail-value">
                            {{ currentDetailReference.updatedAt }}
                          </div>
                        </div>
                      </template>
                    </div>
                  </el-popover>
                  <i
                    class="fas fa-copy icon-a"
                    :title="t('reference.copyCitation')"
                    @click="handleCopyReference(reference)"
                  ></i>

                  <i
                    class="far fa-trash-alt icon-delete"
                    :title="t('reference.deleteReference')"
                    @click="handleDeleteReference(reference)"
                  ></i>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 导出文档对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      :title="t('reference.exportDocument')"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="export-dialog-content">
        <!-- 输出格式选择 -->
        <div class="export-option-section">
          <label class="option-label">{{ t("reference.outputFormat") }}</label>
          <el-radio-group v-model="exportOutputFormat" class="option-group">
            <el-radio label="markdown">Markdown</el-radio>
            <el-radio label="html">HTML</el-radio>
            <el-radio label="text">纯文本</el-radio>
          </el-radio-group>
        </div>

        <!-- 引用格式选择 -->
        <div class="export-option-section">
          <label class="option-label">{{
            t("reference.citationFormat")
          }}</label>
          <el-radio-group v-model="exportCitationFormat" class="option-group">
            <el-radio label="apa">APA</el-radio>
            <el-radio label="ieee">IEEE</el-radio>
          </el-radio-group>
          <div class="option-hint">
            <span v-if="exportCitationFormat === 'apa'">{{
              t("reference.exampleApa")
            }}</span>
            <span v-else>{{ t("reference.exampleIeee") }}</span>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            @click="exportDialogVisible = false"
            :disabled="isExporting"
            >{{ t("reference.cancel") }}</el-button
          >
          <el-button
            type="primary"
            @click="handleExportDocument"
            :loading="isExporting"
            :disabled="isExporting"
          >
            {{
              isExporting ? t("reference.generating") : t("reference.export")
            }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入参考文献对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      :title="t('reference.importReference')"
      width="600px"
      :close-on-click-modal="false"
      @close="closeImportDialog"
    >
      <div class="import-dialog-content">
        <!-- 导入方式选择 -->
        <div class="import-method-section">
          <label class="section-label">{{ t("reference.importMethod") }}</label>
          <el-radio-group v-model="importMethod" class="import-method-group">
            <el-radio label="title">{{
              t("reference.importByTitle")
            }}</el-radio>
            <el-radio label="doi">{{ t("reference.importByDoi") }}</el-radio>
          </el-radio-group>
        </div>

        <!-- 搜索区域(左右布局) -->
        <div class="import-search-section">
          <label class="section-label-inline">
            {{
              importMethod === "title" ? t("reference.literatureTitle") : "DOI"
            }}
          </label>
          <div class="search-input-wrapper-inline">
            <el-input
              ref="importInputRef"
              v-model="importInput"
              :placeholder="
                importMethod === 'title'
                  ? t('reference.enterLiteratureTitle')
                  : t('reference.enterDoi')
              "
              clearable
              @keyup.enter="handleImportSearch"
            >
              <template #append>
                <el-button @click="handleImportSearch" :loading="isSearching">
                  {{ t("reference.search") }}
                </el-button>
              </template>
            </el-input>
          </div>
        </div>

        <!-- 搜索结果列表 -->
        <div v-if="searchResults.length > 0" class="search-results-section">
          <div class="results-header">
            <span class="results-count">{{
              t("reference.foundResults", { count: searchResults.length })
            }}</span>
          </div>
          <div class="results-list">
            <div
              v-for="result in searchResults"
              :key="result.workId"
              class="result-item"
            >
              <div class="result-content">
                <div class="result-info">
                  <div class="result-title">{{ result.title }}</div>
                  <div class="result-meta">
                    <!-- 第一行:作者、年份 -->
                    <div class="meta-row">
                      <span v-if="result.authorsText" class="result-authors">{{
                        result.authorsText
                      }}</span>
                      <span class="result-year"
                        >({{ result.publicationYear }})</span
                      >
                    </div>

                    <!-- 第二行:类型、期刊/会议信息 -->
                    <div
                      v-if="
                        result.itemType ||
                        result.venueName ||
                        result.journalAbbr
                      "
                      class="meta-row"
                    >
                      <span v-if="result.itemType" class="result-type"
                        >[{{ result.itemType }}]</span
                      >
                      <span v-if="result.venueName" class="result-venue">{{
                        result.venueName
                      }}</span>
                      <span
                        v-if="result.journalAbbr"
                        class="result-journal-abbr"
                        >({{ result.journalAbbr }})</span
                      >
                    </div>

                    <!-- 第三行:卷期号、页码、ISSN -->
                    <div
                      v-if="
                        result.volume ||
                        result.issue ||
                        result.pages ||
                        result.issn
                      "
                      class="meta-row"
                    >
                      <span v-if="result.volume" class="result-volume"
                        >Vol. {{ result.volume }}</span
                      >
                      <span v-if="result.issue" class="result-issue"
                        >No. {{ result.issue }}</span
                      >
                      <span v-if="result.pages" class="result-pages"
                        >pp. {{ result.pages }}</span
                      >
                      <span v-if="result.issn" class="result-issn"
                        >ISSN: {{ result.issn }}</span
                      >
                    </div>

                    <!-- 第四行:DOI -->
                    <div v-if="result.doi" class="meta-row">
                      <span class="result-doi">DOI: {{ result.doi }}</span>
                    </div>
                  </div>
                </div>

                <!-- 按钮组:放在右下角 -->
                <div class="result-actions">
                  <a
                    v-if="result.landingUrl"
                    :href="result.landingUrl"
                    target="_blank"
                    class="action-link"
                    @click.stop
                  >
                    <i class="fas fa-external-link-alt"></i>
                    {{ t("reference.viewOriginal") }}
                  </a>
                  <a
                    v-if="result.pdfUrl"
                    :href="result.pdfUrl"
                    target="_blank"
                    download
                    class="action-link action-pdf"
                    @click.stop
                  >
                    <i class="fas fa-file-pdf"></i>
                    {{ t("reference.downloadPdf") }}
                  </a>
                  <el-button
                    type="primary"
                    size="small"
                    @click="importReference(result)"
                    :loading="result.importing"
                  >
                    {{ t("reference.import") }}
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态提示 -->
        <div v-else-if="hasSearched && !isSearching" class="empty-results">
          <i class="fas fa-search empty-icon"></i>
          <p class="empty-text">{{ t("reference.noRelatedLiterature") }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  onMounted,
  onBeforeUnmount,
  onActivated,
  onDeactivated,
  nextTick,
  computed,
  watch,
} from "vue";
import { useI18n } from "vue-i18n";
// @ts-ignore
import Vditor from "vditor";
import "vditor/dist/index.css";
import {
  ElMessage,
  ElMessageBox,
  ElPopover,
  ElDialog,
  ElRadioGroup,
  ElRadio,
  ElInput,
  ElButton,
// @ts-ignore
} from "element-plus";
import * as filesApi from "@/api/files";
import { apiUpdateDraft } from "@/api/drafts";
import {
  getFileReferences,
  searchReferencesByTitle,
  searchReferencesByDoi,
  addReferenceToFile,
  getReferenceDetail,
  deleteReferenceFromFile,
  updateReferenceNote,
  getInTextCitation,
  getFormatCitation,
} from "@/api/references";
import type {
  ReferenceItem,
  ImportSearchResultItem,
  ReferenceDetail,
} from "@/api/references";
import { fileCache } from "@/utils/fileCache";
import { preprocessMathContent } from "@/utils/renderMarkdown";
import { triggerNewbieTask } from "@/utils/newbieTask";

// Props
interface Props {
  fileId: string | number;
  fileName: string;
  preloadContent?: string;
  readonly?: boolean;
  isChatAnswer?: boolean;
  folderId?: string | number;
  showReferences?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  preloadContent: "",
  readonly: false,
  isChatAnswer: false,
  showReferences: false,
});

// Emits
interface Emits {
  (
    e: "content-change",
    data: { text: string; html: string; hasChanges: boolean },
  ): void;
  (e: "outline-change", outline: OutlineItem[]): void;
  (
    e: "file-saved",
    data: {
      fileId: string | number;
      fileName: string;
      content: string;
      isAutoSave: boolean;
    },
  ): void;
  (e: "request-show-references"): void; // 请求显示参考文献区域
}

const emit = defineEmits<Emits>();

// 国际化
const { t } = useI18n();

// Types
interface OutlineItem {
  id: string;
  text: string;
  level: number;
  element?: HTMLElement | null;
}

// Reactive state
const vditorContainer = ref<HTMLDivElement>();
const vditorInstance = ref<Vditor>();
const originalContent = ref("");
const currentContent = ref("");
const lastSavedContent = ref("");
const hasChanges = ref(false);
const hasUnsavedChanges = ref(false);
const hasUserEdited = ref(false);
const isSaving = ref(false);
const isLoading = ref(false);
const isDestroying = ref(false);

// TOS 存储相关状态
const fileStorageType = ref<string>("LOCAL");
const hasPendingTosSync = ref(false);
const tosSyncTimer = ref<number | null>(null);
const TOS_SYNC_INTERVAL = 60000;
const isTosFile = computed(() => fileStorageType.value && fileStorageType.value !== "LOCAL");
const editorScrollTop = ref(0);
// KeepAlive 生命周期处理
onDeactivated(() => {});
onActivated(() => {
  tryInitVditor();
  nextTick(() => {
    const el = vditorContainer.value?.querySelector(
      ".vditor-reset",
    ) as HTMLElement | null;

    if (el) {
      el.scrollTop = editorScrollTop.value;
    }
  });
});
const isSavedToKnowledge = ref(false); // 标记智能体文件是否已保存到知识库
const outlineItems = ref<OutlineItem[]>([]);
const outlineUpdateTimer = ref<number>();
const contentWatcherInterval = ref<number>();
const citationRerenderTimer = ref<number>(); // 引用标记重新渲染的防抖定时器

// 参考文献相关状态
const editorHeight = ref("70%");
const referenceHeight = ref("30%");
const searchQuery = ref("");
const editingReferenceId = ref<number | null>(null); // 记录正在编辑的参考文献ID
const editingAlias = ref(""); // 编辑中的别名内容
const selectedReferenceId = ref<number | null>(null); // 记录选中的参考文献ID
const isHandlingEnterKey = ref(false); // 标记是否正在处理回车键
const currentDetailReference = ref<ReferenceDetail | null>(null); // 当前查看详情的参考文献
const isLoadingDetail = ref(false); // 是否正在加载详情

// 导入参考文献对话框相关状态
const importDialogVisible = ref(false); // 对话框显示状态
const importMethod = ref<"title" | "doi">("title"); // 导入方式:title 或 doi
const importInput = ref(""); // 输入内容
const importInputRef = ref<InstanceType<typeof ElInput>>(); // 输入框引用
const isSearching = ref(false); // 搜索中状态
const hasSearched = ref(false); // 是否已经搜索过
const searchResults = ref<any[]>([]); // 搜索结果列表

// 导出对话框相关状态
const exportDialogVisible = ref(false); // 导出对话框显示状态
const exportOutputFormat = ref<"text" | "html" | "markdown">("markdown"); // 输出格式
const exportCitationFormat = ref<"apa" | "ieee">("apa"); // 引用格式
const isExporting = ref(false); // 是否正在导出

// 参考文献列表相关状态
const references = ref<any[]>([]); // 参考文献列表
const isLoadingReferences = ref(false); // 是否正在加载参考文献
const referencesTotal = ref(0); // 参考文献总数

// 引用标记菜单相关状态
const showCitationMenu = ref(false); // 是否显示引用菜单
const citationMenuPosition = ref({ x: 0, y: 0 }); // 菜单位置
const currentCitationSpan = ref<HTMLElement | null>(null); // 当前点击的引用标记
const citationMenuRef = ref<HTMLElement | null>(null); // 菜单元素引用
const citationMenuSearch = ref(""); // 引用菜单搜索关键词

// 拖拽相关状态
const isResizing = ref(false);
const startY = ref(0);
const startEditorHeight = ref(0);
const startReferenceHeight = ref(0);
const autoSaveTimer = ref<number>();
const initRetryCount = ref(0);
// const maxInitRetries = 10;

// 过滤后的参考文献(用于参考文献表格)
const filteredReferences = computed(() => {
  if (!searchQuery.value.trim()) {
    return references.value;
  }

  const query = searchQuery.value.toLowerCase().trim();
  return references.value.filter(
    (ref) =>
      ref.title.toLowerCase().includes(query) ||
      ref.authorsText.toLowerCase().includes(query) ||
      (ref.note && ref.note.toLowerCase().includes(query)) ||
      ref.publicationYear.toString().includes(query) ||
      (ref.doi && ref.doi.toLowerCase().includes(query)),
  );
});

// 过滤后的引用菜单列表
const filteredCitationMenuReferences = computed(() => {
  if (!citationMenuSearch.value.trim()) {
    return references.value;
  }

  const query = citationMenuSearch.value.toLowerCase().trim();
  return references.value.filter(
    (ref) =>
      ref.title.toLowerCase().includes(query) ||
      ref.authorsText.toLowerCase().includes(query) ||
      (ref.note && ref.note.toLowerCase().includes(query)) ||
      ref.publicationYear.toString().includes(query) ||
      (ref.doi && ref.doi.toLowerCase().includes(query)),
  );
});

// 处理参考文献表格搜索
const handleSearch = () => {
  // 搜索逻辑已在 computed 中处理
};

// 选择参考文献
const selectReference = (referenceId: number) => {
  selectedReferenceId.value = referenceId;
};

// 开始编辑别名
const startEditAlias = (reference: any) => {
  editingReferenceId.value = reference.workId;
  editingAlias.value = reference.note || "";

  // 在下一帧自动聚焦到输入框
  nextTick(() => {
    const input = document.querySelector(".alias-input") as HTMLInputElement;
    if (input) {
      input.focus();
      input.select(); // 选中所有文本
    }
  });
};

// 处理回车键事件
const handleEnterKey = (reference: any) => {
  isHandlingEnterKey.value = true;
  saveAlias(reference);
};

// 处理失焦事件
const handleBlur = (reference: any) => {
  // 如果正在处理回车键,跳过失焦事件
  if (isHandlingEnterKey.value) {
    isHandlingEnterKey.value = false;
    return;
  }
  saveAlias(reference);
};

// 保存别名
const saveAlias = async (reference: any) => {
  const workId = reference.workId;
  const newNote = editingAlias.value.trim();

  try {
    // 调用API更新别名
    const response = await updateReferenceNote(props.fileId, workId, newNote);

    // 检查响应是否成功
    const isSuccess =
      response &&
      ((response as any).code === 200 || (response as any).status === 200);

    if (isSuccess) {
      // 更新本地数据
      const refIndex = references.value.findIndex((r) => r.workId === workId);
      if (refIndex !== -1 && references.value[refIndex]) {
        references.value[refIndex].note = newNote;
      }

      // 更新文档内容中所有使用该 workId 的引用标记
      if (vditorInstance.value) {
        const contentText = vditorInstance.value.getValue();
        
        // 匹配所有使用该 workId 的引用标记:{{cite:workId:任意note}}
        const citationRegex = new RegExp(
          `\\{\\{cite:${String(workId).replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:([^}]*)\\}\\}`,
          "g"
        );
        
        // 替换为新的引用标记
        const updatedContent = contentText.replace(
          citationRegex,
          `{{cite:${workId}:${newNote}}}`
        );
        
        // 如果内容有变化,更新编辑器
        if (updatedContent !== contentText) {
          vditorInstance.value.setValue(updatedContent);
          
          // 更新 currentContent,确保保存时使用最新内容
          currentContent.value = updatedContent;
          hasUnsavedChanges.value = true;
          hasUserEdited.value = true;
          
          // 触发内容变化处理,确保保存机制被触发
          setTimeout(() => {
            // 重新渲染引用标记
            renderCitationsInEditor();
            
            // 触发内容变化事件(这会触发自动保存)
            const finalContent = vditorInstance.value?.getValue() || updatedContent;
            handleContentChange(finalContent);
            
            // 立即触发保存,确保更改被保存
            if (hasUnsavedChanges.value && !isSaving.value) {
              autoSaveDocument();
            }
          }, 200);
        }
      }

      ElMessage.success("别名保存成功");
    } else {
      const errorMsg =
        (response as any)?.message ||
        (response as any)?.data?.message ||
        "保存失败";
      throw new Error(errorMsg);
    }
  } catch (error) {
    ElMessage.error(`保存失败: ${(error as Error).message || "未知错误"}`);
  } finally {
    // 退出编辑模式
    editingReferenceId.value = null;
    editingAlias.value = "";
  }
};

// 查看参考文献详情
const viewReferenceDetail = async (reference: any, event: Event) => {
  event.stopPropagation(); // 阻止事件冒泡

  try {
    isLoadingDetail.value = true;
    const response = await getReferenceDetail(reference.workId);

    if (response && response.data) {
      currentDetailReference.value = response.data;
    } else {
      ElMessage.error("获取文献详情失败");
      currentDetailReference.value = null;
    }
  } catch (error) {
    console.error("获取文献详情失败:", error);
    ElMessage.error(
      `获取文献详情失败: ${(error as Error).message || "未知错误"}`,
    );
    currentDetailReference.value = null;
  } finally {
    isLoadingDetail.value = false;
  }
};

// 加载参考文献列表
const loadReferences = async () => {
  if (!props.fileId) {
    console.warn("⚠️ 无法加载参考文献:fileId 为空");
    return;
  }

  try {
    isLoadingReferences.value = true;

    // 如果是从快问快答或深度检索创建的草稿,传递 isDraft: true
    const response = await getFileReferences(
      props.fileId,
      undefined,
      undefined,
      props.isChatAnswer,
    );

    if (response && response.data) {
      const { items, total } = response.data;

      // 直接使用 API 返回的数据,添加序列号
      references.value = items.map((item: ReferenceItem, index: number) => ({
        ...item,
        serialNumber: index + 1, // 使用数组索引+1作为序列号
      }));

      referencesTotal.value = total;
    } else {
      console.warn("⚠️ 参考文献 API 响应格式异常");
      references.value = [];
    }
  } catch (error) {
    console.error("❌ 加载参考文献失败:", error);
    ElMessage.error(
      `加载参考文献失败: ${(error as Error).message || "未知错误"}`,
    );
    references.value = [];
  } finally {
    isLoadingReferences.value = false;
  }
};

// 打开导入对话框
const openImportDialog = () => {
  importDialogVisible.value = true;
  importMethod.value = "title"; // 默认按标题导入
  importInput.value = "";
  searchResults.value = [];
  hasSearched.value = false;
};

// 关闭导入对话框
const closeImportDialog = () => {
  importDialogVisible.value = false;
  importInput.value = "";
  searchResults.value = [];
  hasSearched.value = false;
};

// 处理导入对话框的文献搜索
const handleImportSearch = async () => {
  if (!importInput.value.trim()) {
    ElMessage.warning(
      importMethod.value === "title" ? "请输入文献标题" : "请输入 DOI",
    );
    return;
  }

  try {
    isSearching.value = true;
    hasSearched.value = true;
    searchResults.value = [];

    let response;

    // 根据导入方式调用不同的接口
    if (importMethod.value === "title") {
      // 按标题搜索
      response = await searchReferencesByTitle(importInput.value.trim());
    } else {
      // 按 DOI 搜索
      response = await searchReferencesByDoi(importInput.value.trim());
    }

    if (response && response.data && response.data.items) {
      const items = response.data.items;

      // 直接使用 API 返回的数据,添加 importing 状态字段
      searchResults.value = items.map((item: ImportSearchResultItem) => ({
        ...item,
        importing: false, // 添加导入中状态
      }));
    } else {
      searchResults.value = [];
    }
  } catch (error) {
    console.error("搜索文献失败:", error);
    ElMessage.error(`搜索失败: ${(error as Error).message || "未知错误"}`);
    searchResults.value = [];
  } finally {
    isSearching.value = false;
  }
};

// 导入参考文献到文件
const importReference = async (reference: any) => {
  // 检查是否已经导入过
  if (references.value.some((ref) => ref.workId === reference.workId)) {
    ElMessage.warning("该文献已经导入");
    // 从搜索结果中移除已导入的项
    searchResults.value = searchResults.value.filter(
      (r) => r.workId !== reference.workId,
    );
    // 如果结果为空,重置已搜索状态,避免显示“没有找到匹配的文献”
    if (searchResults.value.length === 0) {
      hasSearched.value = false;
    }
    return;
  }

  try {
    // 设置导入中状态
    reference.importing = true;
    // 调用导入 API
    const response = await addReferenceToFile(
      Number(props.fileId),
      reference.workId,
    );
    // 检查响应是否成功
    const isSuccess =
      response &&
      ((response as any).code === 200 || (response as any).status === 200);

    if (isSuccess) {
      ElMessage.success(`成功导入文献`);

      // 从搜索结果中移除已导入的项(使用 workId 作为唯一标识)
      searchResults.value = searchResults.value.filter(
        (r) => r.workId !== reference.workId,
      );

      // 刷新参考文献列表(从后端重新加载数据)
      await loadReferences();

      // 关闭导入对话框
      closeImportDialog();
    } else {
      const errorMsg =
        (response as any)?.message ||
        (response as any)?.data?.message ||
        "导入失败";
      throw new Error(errorMsg);
    }
  } catch (error) {
    // ElMessage.error(`导入失败: ${(error as Error).message || "未知错误"}`);
  } finally {
    reference.importing = false;
  }
};

// 渲染引用标记为可视化标签(用于预览模式)
const renderCitations = (content: string): string => {
  // 匹配 {{cite:workId:note}} 格式
  const citationRegex = /\{\{cite:([^:]+):([^}]*)\}\}/g;

  return content.replace(citationRegex, (_match, workId, note) => {
    const displayText = note ? `cite:${note}` : `cite:${workId}`;
    return `<span class="citation-tag" data-work-id="${workId}">${displayText}</span>`;
  });
};

// 在编辑器 DOM 中渲染引用标签(用于编辑模式)
// 防抖重新渲染引用标签:用户停止编辑 3 秒后执行
const debouncedRerenderCitations = () => {
  // 清除之前的定时器
  if (citationRerenderTimer.value) {
    clearTimeout(citationRerenderTimer.value);
  }

  // 设置新的定时器:10 秒后执行 (减少频繁重绘导致的卡顿)
  citationRerenderTimer.value = window.setTimeout(() => {
    renderCitationsInEditor();
  }, 10000);
};

const renderCitationsInEditor = () => {
  if (!vditorContainer.value || !vditorInstance.value) return;

  // 查找编辑器内容区域
  const contentArea = vditorContainer.value.querySelector(
    '.vditor-wysiwyg__block, .vditor-ir__preview, [contenteditable="true"]',
  );

  if (!contentArea) return;

  // 快速检查:如果内容中根本没有引用标记,直接返回
  if (!contentArea.textContent?.includes("{{cite:")) return;

  // 查找所有包含 {{cite:}} 标记的文本节点
  const walker = document.createTreeWalker(
    contentArea,
    NodeFilter.SHOW_TEXT,
    null,
  );

  const nodesToReplace: { node: Text; matches: RegExpMatchArray[] }[] = [];
  let node: Text | null;

  while ((node = walker.nextNode() as Text)) {
    // 关键:检查该文本节点是否已经在 .citation-tag 元素内部
    // 如果是,说明已经渲染过了,跳过避免重复渲染
    if (node.parentElement?.closest(".citation-tag")) {
      continue;
    }

    const text = node.textContent || "";
    const citationRegex = /\{\{cite:([^:]+):([^}]*)\}\}/g;
    const matches = Array.from(text.matchAll(citationRegex));

    if (matches.length > 0) {
      nodesToReplace.push({ node, matches });
    }
  }

  // 替换找到的标记
  nodesToReplace.forEach(({ node, matches }) => {
    const text = node.textContent || "";
    const fragment = document.createDocumentFragment();
    let lastIndex = 0;

    matches.forEach((match) => {
      const fullMatch = match[0];
      let workId = match[1];
      let note = match[2];
      const matchIndex = match.index ?? 0;

      // 添加标记之前的文本
      if (matchIndex > lastIndex) {
        fragment.appendChild(
          document.createTextNode(text.substring(lastIndex, matchIndex)),
        );
      }

      // 🔍 智能匹配:检查 note 是否在参考文献列表中存在
      // 如果用户修改了引用标记的 note,尝试找到对应的参考文献
      let matchedReference = null;

      if (note && references.value.length > 0) {
        // 优先通过 note 精确匹配
        matchedReference = references.value.find(
          (ref) => ref.note && ref.note.toLowerCase() === note!.toLowerCase(),
        );

        // 如果 note 匹配不到,尝试通过 title 模糊匹配
        if (!matchedReference) {
          matchedReference = references.value.find(
            (ref) =>
              ref.title &&
              ref.title.toLowerCase().includes(note!.toLowerCase()),
          );
        }

        // 如果还是匹配不到,尝试通过 authorsText 匹配
        if (!matchedReference) {
          matchedReference = references.value.find(
            (ref) =>
              ref.authorsText &&
              ref.authorsText.toLowerCase().includes(note!.toLowerCase()),
          );
        }
      } else if (workId && references.value.length > 0) {
        // 如果没有 note,通过 workId 查找
        matchedReference = references.value.find(
          (ref) => String(ref.workId) === String(workId),
        );
      }

      // 如果找到匹配的参考文献,使用正确的 work_id 和 note
      if (matchedReference) {
        workId = String(matchedReference.workId);
        note = matchedReference.note || matchedReference.title || "";

        // 更新为正确的 markdown 标记
        const correctedMarkup = `{{cite:${workId}:${note}}}`;

        // 创建并添加 span 标签
        const span = document.createElement("span");
        span.className = "citation-tag";
        span.setAttribute("data-work-id", workId);
        span.setAttribute("data-citation-markup", correctedMarkup); // 保存修正后的标记
        span.contentEditable = "false"; // 不可编辑
        span.style.backgroundColor = "#e6f7ff";
        span.style.color = "#1890ff";
        span.style.padding = "2px 8px";
        span.style.borderRadius = "4px";
        span.style.display = "inline-block";
        span.style.fontSize = "13px";
        span.style.fontWeight = "500";
        span.style.whiteSpace = "nowrap";
        span.style.cursor = "pointer";

        // textContent 设置为修正后的 markdown 标记
        span.textContent = correctedMarkup;

        // 使用 ::before 伪元素来显示友好的文本
        span.setAttribute(
          "data-display-text",
          note ? `cite:${note}` : `cite:${workId}`,
        );

        // 添加点击事件监听器
        span.addEventListener("click", (e: MouseEvent) => {
          openCitationMenu(span, e);
        });

        fragment.appendChild(span);
      } else {
        // ⚠️ 如果在参考文献列表中找不到匹配项,保持为纯文本,不渲染样式
        // 这样用户可以看到并修正错误的引用标记
        fragment.appendChild(document.createTextNode(fullMatch));

        console.warn(`引用标记未找到匹配的参考文献: ${fullMatch}`);
      }

      lastIndex = matchIndex + fullMatch.length;
    });

    // 添加剩余的文本
    if (lastIndex < text.length) {
      fragment.appendChild(document.createTextNode(text.substring(lastIndex)));
    }

    // 替换原始文本节点
    node.parentNode?.replaceChild(fragment, node);
  });
};

// 处理粘贴事件,检测 JSON 格式并转换为引用标记
const handlePaste = (event: Event) => {
  const clipboardEvent = event as ClipboardEvent;
  if (!clipboardEvent.clipboardData) return;

  // 获取剪贴板中的纯文本内容
  const text = clipboardEvent.clipboardData.getData("text/plain");

  // 尝试解析 JSON 格式的引用数据
  let isReferenceData = false;
  let parsedData: any = null;

  try {
    parsedData = JSON.parse(text);
    // 检查是否是有效的引用数据格式
    if (parsedData && parsedData.work_id !== undefined) {
      isReferenceData = true;
    }
  } catch (error) {
    // 不是 JSON 格式,让 Vditor 处理默认粘贴行为
    return;
  }

  // 如果是引用数据,立即阻止所有默认行为
  if (isReferenceData) {
    // 立即阻止所有默认行为
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();

    const workId = parsedData.work_id;
    const note = parsedData.note || "";

    // 构建 Markdown 标记(这样可以被保存)
    const citationMarkup = `{{cite:${workId}:${note}}}`;

    // 直接在当前光标位置插入带样式的 span 标签
    if (vditorInstance.value) {
      const selection = window.getSelection();
      if (selection && selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);

        // 创建 span 元素
        const span = document.createElement("span");
        span.className = "citation-tag";
        span.setAttribute("data-work-id", String(workId));
        span.setAttribute("data-citation-markup", citationMarkup); // 保存原始标记
        span.contentEditable = "false"; // 不可编辑
        span.style.backgroundColor = "#e6f7ff";
        span.style.color = "#1890ff";
        span.style.padding = "2px 8px";
        span.style.borderRadius = "4px";
        span.style.display = "inline-block";
        span.style.fontSize = "13px";
        span.style.fontWeight = "500";
        span.style.whiteSpace = "nowrap";
        span.style.cursor = "pointer";

        // 关键修改:textContent 设置为完整的 markdown 标记
        // 这样即使 span 被 Vditor 清理,也会保留 markdown 文本
        span.textContent = citationMarkup; // 直接使用 {{cite:11:note}} 格式

        // 使用 ::before 伪元素来显示友好的文本,而不是修改 textContent
        // 通过 data 属性传递显示文本
        span.setAttribute(
          "data-display-text",
          note ? `cite:${note}` : `cite:${workId}`,
        );

        // 添加点击事件监听器
        span.addEventListener("click", (e: MouseEvent) => {
          openCitationMenu(span, e);
        });

        // 插入 span 元素
        range.insertNode(span);

        // 在 span 后面插入一个空格
        const space = document.createTextNode("\u00A0");
        range.setStartAfter(span);
        range.insertNode(space);

        // 将光标移动到空格之后
        range.setStartAfter(space);
        range.collapse(true);
        selection.removeAllRanges();
        selection.addRange(range);

        // 触发内容变化
        setTimeout(() => {
          if (vditorInstance.value) {
            const currentValue = vditorInstance.value.getValue();
            handleContentChange(currentValue);
          }
        }, 50);
      }
    }

    return false;
  }
};

// 复制引用 - 复制 JSON 格式
const handleCopyReference = async (reference: any) => {
  try {
    const workId = reference.workId;
    const note = reference.note || "";

    // 构建 JSON 格式数据
    const citationData = {
      work_id: String(workId),
      note: note,
    };

    const jsonString = JSON.stringify(citationData);

    // 复制 JSON 字符串到剪贴板
    await navigator.clipboard.writeText(jsonString);

    ElMessage.success("引用已复制到剪贴板");
  } catch (error) {
    console.error("复制引用失败:", error);
    ElMessage.error(`复制失败: ${(error as Error).message || "未知错误"}`);
  }
};

// 处理参考文献拖拽开始
const handleReferenceDragStart = (event: DragEvent, reference: any) => {
  if (!event.dataTransfer) return;

  const workId = reference.workId;
  const note = reference.note || "";

  // 构建 JSON 格式数据(和复制时一样的格式)
  const citationData = {
    work_id: String(workId),
    note: note,
  };

  const jsonString = JSON.stringify(citationData);

  // 设置拖拽数据
  event.dataTransfer.effectAllowed = "copy";
  event.dataTransfer.setData("text/plain", jsonString);
  event.dataTransfer.setData("application/json", jsonString);

  // 创建自定义拖拽预览元素 - 只显示别名
  const dragText = note ? `cite:${note}` : `cite:${workId}`;
  const dragPreview = document.createElement("div");
  dragPreview.className = "reference-drag-preview";
  dragPreview.textContent = dragText;
  dragPreview.style.position = "absolute";
  dragPreview.style.top = "-1000px";
  dragPreview.style.left = "-1000px";
  dragPreview.style.padding = "6px 12px";
  dragPreview.style.backgroundColor = "#e6f7ff";
  dragPreview.style.color = "#1890ff";
  dragPreview.style.borderRadius = "4px";
  dragPreview.style.fontSize = "13px";
  dragPreview.style.fontWeight = "500";
  dragPreview.style.whiteSpace = "nowrap";
  dragPreview.style.boxShadow = "0 2px 8px rgba(0, 0, 0, 0.15)";
  dragPreview.style.border = "1px solid #91d5ff";
  dragPreview.style.zIndex = "9999";

  document.body.appendChild(dragPreview);

  // 设置自定义拖拽图像
  event.dataTransfer.setDragImage(dragPreview, 0, 0);

  // 拖拽结束后移除预览元素
  setTimeout(() => {
    document.body.removeChild(dragPreview);
  }, 0);
};

// 阻止编辑器内文本拖拽启动,防止从右到左选择时被误判为拖拽
const handleEditorDragStart = (event: Event) => {
  const dragEvent = event as DragEvent;
  const target = dragEvent.target as HTMLElement;
  // 仅允许显式设置 draggable="true" 的元素(如参考文献条目)发起拖拽
  if (!target?.closest?.('[draggable="true"]')) {
    dragEvent.preventDefault();
  }
};

// 处理编辑器区域的拖拽悬停
const handleEditorDragOver = (event: Event) => {
  const dragEvent = event as DragEvent;
  // 只在拖拽引用数据时才阻止默认行为(引用拖拽会携带 application/json 类型)
  // 无条件 preventDefault 会破坏浏览器原生的文本选择功能(尤其是从右到左选择)
  if (dragEvent.dataTransfer && dragEvent.dataTransfer.types.includes("application/json")) {
    dragEvent.preventDefault();
    dragEvent.dataTransfer.dropEffect = "copy";
  }
};

// 处理编辑器区域的拖拽放置
const handleEditorDrop = (event: Event) => {
  const dragEvent = event as DragEvent;

  if (!dragEvent.dataTransfer || !vditorInstance.value) return;

  // 获取拖拽数据
  const jsonString = dragEvent.dataTransfer.getData("text/plain");

  // 尝试解析 JSON 格式的引用数据
  let parsedData: any = null;
  let isReferenceData = false;

  try {
    parsedData = JSON.parse(jsonString);
    // 检查是否是有效的引用数据格式
    if (parsedData && parsedData.work_id !== undefined) {
      isReferenceData = true;
    }
  } catch (error) {
    // 不是 JSON 格式,让 Vditor 处理
    return;
  }

  // 只有当是引用数据时才阻止默认行为
  if (!isReferenceData) return;

  // 立即阻止所有默认行为和事件传播
  dragEvent.preventDefault();
  dragEvent.stopPropagation();
  dragEvent.stopImmediatePropagation();

  const workId = parsedData.work_id;
  const note = parsedData.note || "";

  // 构建 Markdown 标记
  const citationMarkup = `{{cite:${workId}:${note}}}`;

  // 获取放置位置 - 使用 Vditor 的可编辑区域
  const editableElement = vditorContainer.value?.querySelector(
    '[contenteditable="true"]',
  );
  if (!editableElement) return;

  // 获取准确的拖放位置
  const range = document.caretRangeFromPoint(
    dragEvent.clientX,
    dragEvent.clientY,
  );
  if (!range) return;

  // 确保 range 在编辑器内
  if (!editableElement.contains(range.startContainer)) {
    console.warn("拖放位置不在编辑器内");
    return;
  }

  // 清除当前选区,避免干扰
  const selection = window.getSelection();
  if (selection) {
    selection.removeAllRanges();
  }

  // 创建 span 元素
  const span = document.createElement("span");
  span.className = "citation-tag";
  span.setAttribute("data-work-id", String(workId));
  span.setAttribute("data-citation-markup", citationMarkup);
  span.contentEditable = "false";
  span.style.backgroundColor = "#e6f7ff";
  span.style.color = "#1890ff";
  span.style.padding = "2px 8px";
  span.style.borderRadius = "4px";
  span.style.display = "inline-block";
  span.style.fontSize = "13px";
  span.style.fontWeight = "500";
  span.style.whiteSpace = "nowrap";
  span.style.cursor = "pointer";

  // 关键修改:textContent 设置为完整的 markdown 标记
  // 这样即使 span 被 Vditor 清理,也会保留 markdown 文本
  span.textContent = citationMarkup; // 直接使用 {{cite:11:note}} 格式

  // 使用 ::before 伪元素来显示友好的文本,而不是修改 textContent
  // 通过 data 属性传递显示文本
  span.setAttribute(
    "data-display-text",
    note ? `cite:${note}` : `cite:${workId}`,
  );

  // 添加点击事件监听器
  span.addEventListener("click", (e: MouseEvent) => {
    openCitationMenu(span, e);
  });

  // 在放置位置插入 span 元素
  try {
    range.deleteContents(); // 删除选中的内容(如果有)
    range.insertNode(span);

    // 在 span 后面插入一个空格
    const space = document.createTextNode("\u00A0");
    range.setStartAfter(span);
    range.insertNode(space);

    // 将光标移动到空格之后
    range.setStartAfter(space);
    range.collapse(true);

    // 恢复选区
    if (selection) {
      selection.removeAllRanges();
      selection.addRange(range);
    }

    // 触发内容变化
    setTimeout(() => {
      if (vditorInstance.value) {
        const currentValue = vditorInstance.value.getValue();
        handleContentChange(currentValue);
      }
    }, 100);

    ElMessage.success("引用已添加到文档");
  } catch (error) {
    console.error("插入引用标记失败:", error);
    ElMessage.error("插入引用标记失败");
  }
};

// 打开引用标记菜单
const openCitationMenu = (span: HTMLElement, event: MouseEvent) => {
  event.preventDefault();
  event.stopPropagation();

  currentCitationSpan.value = span;

  // 计算初始菜单位置
  const rect = span.getBoundingClientRect();
  citationMenuPosition.value = {
    x: rect.left,
    y: rect.bottom + 5, // 默认在标记下方 5px
  };

  showCitationMenu.value = true;

  // 使用 nextTick 等待菜单渲染后精细调整位置,防止溢出屏幕
  nextTick(() => {
    if (!citationMenuRef.value) return;

    const menuRect = citationMenuRef.value.getBoundingClientRect();
    const viewportHeight = window.innerHeight;
    const viewportWidth = window.innerWidth;

    let x = rect.left;
    let y = rect.bottom + 5;

    // 检查底部溢出
    if (y + menuRect.height > viewportHeight) {
      // 如果下方空间不足,尝试显示在上方
      const topY = rect.top - menuRect.height - 5;
      if (topY > 0) {
        y = topY;
      } else {
        // 如果上方也不够,尽量靠底部显示,但不超出屏幕
        y = Math.max(5, viewportHeight - menuRect.height - 10);
      }
    }

    // 检查右侧溢出
    if (x + menuRect.width > viewportWidth) {
      x = Math.max(10, viewportWidth - menuRect.width - 10);
    }

    citationMenuPosition.value = { x, y };
  });
};

// 替换引用标记
const replaceCitation = (reference: any) => {
  if (!currentCitationSpan.value) return;

  const workId = reference.workId;
  const note = reference.note || "";
  const citationMarkup = `{{cite:${workId}:${note}}}`;
  const displayText = note ? `cite:${note}` : `cite:${workId}`;

  // 更新 span 的内容和属性
  // textContent 设置为完整的 markdown 标记,用于保存
  currentCitationSpan.value.textContent = citationMarkup;
  // data-display-text 用于 ::before 伪元素显示友好的文本
  currentCitationSpan.value.setAttribute("data-display-text", displayText);
  currentCitationSpan.value.setAttribute("data-work-id", String(workId));
  currentCitationSpan.value.setAttribute(
    "data-citation-markup",
    citationMarkup,
  );

  // 关闭菜单
  showCitationMenu.value = false;
  currentCitationSpan.value = null;

  // 触发内容变化
  if (vditorInstance.value) {
    const currentValue = vditorInstance.value.getValue();
    handleContentChange(currentValue);
  }

  ElMessage.success("引用已更换");
};

// 关闭引用菜单
const closeCitationMenu = () => {
  showCitationMenu.value = false;
  currentCitationSpan.value = null;
  citationMenuSearch.value = ""; // 清空搜索关键词
};

// 点击外部关闭引用菜单
const handleClickOutside = (event: MouseEvent) => {
  if (!showCitationMenu.value) return;

  const target = event.target as HTMLElement;
  if (!target || !target.closest) {
    closeCitationMenu();
    return;
  }

  // 如果点击的是引用标记或菜单内部,不关闭
  if (target.closest(".citation-tag") || target.closest(".citation-menu-wrapper")) {
    return;
  }

  // 关闭菜单
  closeCitationMenu();
};

// 滚动时关闭引用菜单
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement;
  if (!target) return;

  if (target.classList && target.classList.contains("vditor-reset")) {
    editorScrollTop.value = target.scrollTop;
  }
  if (!showCitationMenu.value) return;

  // 如果滚动事件发生在引用菜单内部,不关闭菜单
  if (target.closest && target.closest(".citation-menu-wrapper")) {
    return;
  }

  // 只有在页面或编辑器滚动时才关闭菜单
  closeCitationMenu();
};

// 打开导出对话框
const openExportDialog = () => {
  exportDialogVisible.value = true;
  exportOutputFormat.value = "markdown"; // 默认 Markdown
  exportCitationFormat.value = "apa"; // 默认 APA
};

// 提取文档中的引用标记并构建citationGroups
const extractCitationGroups = (
  content: string,
): { groups: number[][]; positions: { start: number; end: number }[] } => {
  const groups: number[][] = [];
  const positions: { start: number; end: number }[] = [];

  // 首先找到所有单个引用标记及其位置
  const singleCiteRegex = /\{\{cite:([^:]+):([^}]*)\}\}/g;
  const allCitations: { workId: number; start: number; end: number }[] = [];

  let match;
  while ((match = singleCiteRegex.exec(content)) !== null) {
    const workIdStr = match[1];
    if (workIdStr) {
      const workId = parseInt(workIdStr, 10);
      if (!isNaN(workId)) {
        allCitations.push({
          workId,
          start: match.index,
          end: match.index + match[0].length,
        });
      }
    }
  }
  // 将连续的引用标记分组
  if (allCitations.length === 0) {
    return { groups, positions };
  }

  const firstCitation = allCitations[0];
  if (!firstCitation) {
    return { groups, positions };
  }

  let currentGroup: number[] = [firstCitation.workId];
  let groupStart = firstCitation.start;
  let groupEnd = firstCitation.end;

  for (let i = 1; i < allCitations.length; i++) {
    const prev = allCitations[i - 1];
    const curr = allCitations[i];

    if (!prev || !curr) continue;

    // 计算两个引用标记之间的距离
    const distance = curr.start - prev.end;

    // 检查是否连续:
    // 1. 紧邻(distance = 0)
    // 2. 中间只有少量空白字符(distance <= 5,允许空格、换行等)
    const isContinuous = distance >= 0 && distance <= 5;

    if (isContinuous) {
      // 连续的引用标记,加入当前组
      currentGroup.push(curr.workId);
      groupEnd = curr.end;
    } else {
      // 不连续,保存当前组并开始新组
      groups.push(currentGroup);
      positions.push({ start: groupStart, end: groupEnd });

      currentGroup = [curr.workId];
      groupStart = curr.start;
      groupEnd = curr.end;
    }
  }

  // 保存最后一组
  if (currentGroup.length > 0) {
    groups.push(currentGroup);
    positions.push({ start: groupStart, end: groupEnd });
  }

  return { groups, positions };
};

// 处理文档导出
const handleExportDocument = async () => {
  if (!vditorInstance.value) {
    ElMessage.error("编辑器未初始化");
    return;
  }

  // 设置导出状态,阻止所有内容变化监听
  isExporting.value = true;

  // 清除所有定时器,暂停自动保存
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }
  if (contentWatcherInterval.value) {
    clearInterval(contentWatcherInterval.value);
  }

  // 禁用编辑器的input事件,防止触发内容变化
  const vditorOptions = vditorInstance.value.vditor?.options;
  const originalInputCallback = vditorOptions?.input;

  try {
    if (vditorOptions) {
      vditorOptions.input = () => {}; // 临时禁用
    }
    const outputFormat = exportOutputFormat.value;
    const citationFormat = exportCitationFormat.value;

    // 先触发一次内容转换,确保包含最新的引用标记
    const rawContent = vditorInstance.value.getValue();
    const convertedContent = convertSpanToMarkdown(rawContent);

    // 使用转换后的内容
    let markdownContent = convertedContent || currentContent.value;

    // 检查是否包含引用标记的特征字符串
    const hasCiteKeyword = markdownContent.includes("{{cite:");

    // 如果没有找到引用标记,尝试从currentContent获取
    if (!hasCiteKeyword && currentContent.value) {
      const hasInCurrent = currentContent.value.includes("{{cite:");

      if (hasInCurrent) {
        markdownContent = currentContent.value;
      }
    }

    // 提取引用标记并构建citationGroups
    const { groups: citationGroups, positions } =
      extractCitationGroups(markdownContent);

    // 如果有引用标记,显示加载提示并调用API获取格式化文本
    let formattedTexts: string[] = [];
    if (citationGroups.length > 0) {
      // 显示加载提示
      ElMessage.info({
        message: "正在生成引用格式...",
        duration: 0, // 不自动关闭
        showClose: false,
      });

      const response = await getInTextCitation(
        props.fileId,
        citationGroups,
        citationFormat,
        outputFormat,
      );

      // 关闭加载提示
      ElMessage.closeAll();

      // 检查响应数据结构
      if (response && response.data) {
        formattedTexts = response.data.texts || [];
      } else if (response && (response as any).texts) {
        formattedTexts = (response as any).texts;
      }

      // 验证返回的texts数量是否匹配
      if (formattedTexts.length !== citationGroups.length) {
        // console.warn(
        //   `⚠️ 返回的texts数量(${formattedTexts.length})与citationGroups数量(${citationGroups.length})不匹配`,
        // );
      }

      // 从后往前替换,避免位置偏移问题
      for (let i = positions.length - 1; i >= 0; i--) {
        const pos = positions[i];
        if (!pos) {
          console.warn(`⚠️ 位置${i}为空,跳过`);
          continue;
        }

        const formattedText = formattedTexts[i] || "";
        // const originalText = markdownContent.substring(pos.start, pos.end);

        const before = markdownContent.substring(0, pos.start);
        const after = markdownContent.substring(pos.end);

        markdownContent = before + formattedText + after;
      }

      // 额外验证:检查替换是否真的生效
      const stillHasCiteMarks = markdownContent.includes("{{cite:");
      const hasApaFormat = /\([^)]+,\s*\d{4}[^)]*\)/.test(markdownContent);

      if (stillHasCiteMarks) {
        console.error("⚠️⚠️⚠️ 警告:替换后内容中仍然包含 {{cite:}} 标记!");
        // 找出所有未替换的引用标记
        const remainingCites = markdownContent.match(/\{\{cite:[^}]+\}\}/g);
        console.error("未替换的标记:", remainingCites);
      }

      if (!hasApaFormat && citationFormat === "apa") {
        console.error("⚠️⚠️⚠️ 警告:替换后内容中没有检测到APA格式引用!");
      }
    } else {
      console.log("ℹ️ 文档中没有引用标记,直接导出");
    }

    // 根据输出格式处理内容
    let finalContent = markdownContent;

    if (outputFormat === "html") {
      // 将 markdown 转换为 HTML
      // 使用 Vditor 的静态方法转换,不触发编辑器事件
      if (
        typeof Vditor !== "undefined" &&
        typeof Vditor.preview === "function"
      ) {
        // 创建临时容器
        const tempDiv = document.createElement("div");
        await Vditor.preview(tempDiv, markdownContent, {
          mode: "light",
        });
        finalContent = tempDiv.innerHTML;
      } else {
        // 降级方案:简单的Markdown到HTML转换
        finalContent = markdownContent
          .replace(/^### (.+)$/gm, "<h3>$1</h3>")
          .replace(/^## (.+)$/gm, "<h2>$1</h2>")
          .replace(/^# (.+)$/gm, "<h1>$1</h1>")
          .replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>")
          .replace(/\*(.+?)\*/g, "<em>$1</em>")
          .replace(/\n\n/g, "</p><p>")
          .replace(/^(.+)$/gm, "<p>$1</p>");
      }
    } else if (outputFormat === "text") {
      // 先保护引用格式的文本(APA和IEEE)
      // 将 [文本](引用) 中的引用内容保留
      const citationPlaceholders: { placeholder: string; original: string }[] =
        [];
      let placeholderIndex = 0;

      // 识别并保护引用格式
      finalContent = markdownContent.replace(
        /\[([^\]]+)\]\(([^)]+(?:et al\.|,|;|\d{4}|[\u4e00-\u9fa5])[^)]*)\)/g,
        (_match, text, citation) => {
          // 如果括号内包含年份、et al.、中文等引用特征,保留完整格式
          const placeholder = `__CITATION_${placeholderIndex}__`;
          citationPlaceholders.push({
            placeholder,
            original: `${text} ${citation}`, // 保留文本和引用
          });
          placeholderIndex++;
          return placeholder;
        },
      );

      // 简单的 Markdown 到纯文本转换
      finalContent = finalContent
        .replace(/#{1,6}\s+/g, "") // 移除标题标记
        .replace(/\*\*(.+?)\*\*/g, "$1") // 移除加粗
        .replace(/\*(.+?)\*/g, "$1") // 移除斜体
        .replace(/`(.+?)`/g, "$1") // 移除行内代码
        .replace(/\[(.+?)\]\(.+?\)/g, "$1") // 移除普通链接,保留文本
        .replace(/!\[.*?\]\(.+?\)/g, "") // 移除图片
        .replace(/^>\s+/gm, "") // 移除引用标记
        .replace(/^[-*+]\s+/gm, "• ") // 列表项转为项目符号
        .replace(/^\d+\.\s+/gm, "") // 移除有序列表编号
        .replace(/```[\s\S]*?```/g, "") // 移除代码块
        .trim();

      // 恢复引用格式
      citationPlaceholders.forEach(({ placeholder, original }) => {
        finalContent = finalContent.replace(placeholder, original);
      });
    }

    // 调用API获取完整的参考文献列表
    if (citationGroups.length > 0) {
      // 显示加载提示
      ElMessage.info({
        message: "正在生成参考文献列表...",
        duration: 0,
        showClose: false,
      });

      try {
        const citationResponse = await getFormatCitation(
          props.fileId,
          citationGroups,
          citationFormat,
          outputFormat,
        );

        // 关闭加载提示
        ElMessage.closeAll();

        // 检查响应数据结构
        let entries: string[] = [];
        if (citationResponse && citationResponse.data) {
          entries = citationResponse.data.entries || [];
        } else if (citationResponse && (citationResponse as any).entries) {
          entries = (citationResponse as any).entries;
        }

        // 如果有参考文献条目,添加到文档末尾
        if (entries.length > 0) {
          // 直接使用API返回的数据,不做任何序号处理
          const processedEntries = entries.map((entry) => entry.trim());

          // 根据输出格式添加参考文献列表
          if (outputFormat === "html") {
            // HTML格式
            finalContent += `\n<h2>References</h2>\n`;
            processedEntries.forEach((entry) => {
              finalContent += `<p>${entry}</p>\n`;
            });
          } else if (outputFormat === "markdown") {
            // Markdown格式
            finalContent += `\n\n## References\n\n`;
            processedEntries.forEach((entry) => {
              // 确保每个条目后有换行符
              finalContent += entry + (entry.endsWith("\n") ? "" : "\n");
            });
          } else {
            // 纯文本格式
            finalContent += `\n\nReferences\n\n`;
            processedEntries.forEach((entry) => {
              // 确保每个条目后有换行符
              finalContent += entry + (entry.endsWith("\n") ? "" : "\n");
            });
          }
        } else {
          console.warn("⚠️ API未返回参考文献条目");
        }
      } catch (error) {
        console.error("❌ 获取参考文献列表失败:", error);
        ElMessage.closeAll();
        ElMessage.warning("获取参考文献列表失败,将继续导出文档");
      }
    }

    // 确定文件扩展名
    let extension = ".md";
    let mimeType = "text/markdown";
    if (outputFormat === "html") {
      extension = ".html";
      mimeType = "text/html";
    } else if (outputFormat === "text") {
      extension = ".txt";
      mimeType = "text/plain";
    }

    const finalHasCite = finalContent.includes("{{cite:");

    // 显示所有匹配APA格式的文本
    const apaMatches = finalContent.match(/\([^)]+,\s*\d{4}[^)]*\)/g);
    if (apaMatches && apaMatches.length > 0) {
      apaMatches.forEach((match, index) => {
        console.log(`  ${index + 1}. ${match}`);
      });
    } else if (citationFormat === "apa" && citationGroups.length > 0) {
      console.error("❌❌❌ 严重错误:应该有APA引用但未找到!");
    }

    // 如果最终内容仍有cite标记,说明替换失败
    if (finalHasCite) {
      const remainingCites = finalContent.match(/\{\{cite:[^}]+\}\}/g);
      console.error("未替换的标记:", remainingCites);
    }

    // 创建下载
    const blob = new Blob([finalContent], {
      type: `${mimeType};charset=utf-8`,
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.download = `${props.fileName.replace(/\.\w+$/, "")}${extension}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);

    ElMessage.success("文档导出成功");
    triggerNewbieTask("doc_download_save");
    exportDialogVisible.value = false;
  } catch (error) {
    console.error("❌ 导出文档失败:", error);
    ElMessage.closeAll(); // 关闭加载提示
    ElMessage.error(`导出失败: ${(error as Error).message || "未知错误"}`);
  } finally {
    // 恢复编辑器的input事件
    if (vditorOptions && originalInputCallback) {
      vditorOptions.input = originalInputCallback;
    }

    // 重置导出状态
    isExporting.value = false;

    // 恢复内容监听
    startContentWatcher();
  }
};

// 删除参考文献
const handleDeleteReference = async (reference: any) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
      `确定要删除文献《${reference.title}》吗?删除后将无法恢复。`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    );

    // 用户点击确定,调用删除 API
    const response = await deleteReferenceFromFile(
      props.fileId,
      reference.workId,
    );

    // 检查响应是否成功
    const isSuccess =
      response &&
      ((response as any).code === 200 || (response as any).status === 200);

    if (isSuccess) {
      ElMessage.success("文献删除成功");

      // 刷新参考文献列表(从后端重新加载数据)
      await loadReferences();
    } else {
      const errorMsg =
        (response as any)?.message ||
        (response as any)?.data?.message ||
        "删除失败";
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    // 用户点击取消会抛出 cancel 错误,不需要提示
    if (error === "cancel" || error === "close") {
      return;
    }
    // 其他错误提示
    ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
  }
};

// 开始拖拽调整大小
const startResize = (e: MouseEvent | TouchEvent) => {
  e.preventDefault();
  isResizing.value = true;

  const clientY = "touches" in e ? e.touches[0]?.clientY || 0 : e.clientY;
  startY.value = clientY;

  // 获取当前高度百分比
  startEditorHeight.value = parseFloat(editorHeight.value);
  startReferenceHeight.value = parseFloat(referenceHeight.value);

  // 添加全局事件监听
  document.addEventListener("mousemove", handleResize);
  document.addEventListener("mouseup", stopResize);
  document.addEventListener("touchmove", handleResize);
  document.addEventListener("touchend", stopResize);

  // 防止文本选择
  document.body.style.userSelect = "none";
  document.body.style.cursor = "ns-resize";
};

// 处理拖拽
const handleResize = (e: MouseEvent | TouchEvent) => {
  if (!isResizing.value) return;

  e.preventDefault();
  const clientY = "touches" in e ? e.touches[0]?.clientY || 0 : e.clientY;
  const deltaY = clientY - startY.value;

  // 获取容器高度
  const container = document.querySelector(
    ".vditor-markdown-editor",
  ) as HTMLElement;
  if (!container) return;

  const containerHeight = container.offsetHeight;
  const deltaPercent = (deltaY / containerHeight) * 100;

  // 计算新高度
  let newEditorHeight = startEditorHeight.value + deltaPercent;
  let newReferenceHeight = startReferenceHeight.value - deltaPercent;

  // 限制最小高度(参考文献区域最小300px,编辑器可以最小到0允许参考文献完全覆盖)
  const minReferencePercent = (300 / containerHeight) * 100;
  const maxReferencePercent = 100; // 允许参考文献覆盖整个编辑器

  newEditorHeight = Math.max(0, Math.min(100, newEditorHeight)); // 编辑器最小0%,最大100%
  newReferenceHeight = Math.max(
    minReferencePercent,
    Math.min(maxReferencePercent, newReferenceHeight),
  );

  // 更新高度
  editorHeight.value = `${newEditorHeight}%`;
  referenceHeight.value = `${newReferenceHeight}%`;
};

// 停止拖拽
const stopResize = () => {
  try {
    isResizing.value = false;

    // 移除全局事件监听
    document.removeEventListener("mousemove", handleResize);
    document.removeEventListener("mouseup", stopResize);
    document.removeEventListener("touchmove", handleResize);
    document.removeEventListener("touchend", stopResize);
  } finally {
    // 确保始终恢复样式,即使上面的代码抛异常
    document.body.style.userSelect = "";
    document.body.style.cursor = "";
  }
};

// 监听 fileId 变化,如果变为无效值,停止所有操作
watch(
  () => props.fileId,
  (newFileId, oldFileId) => {
    // 如果 fileId 变为 undefined、null 或空值,且之前有值,说明标签被关闭或文件被删除
    if (
      (!newFileId || newFileId === undefined || newFileId === null) &&
      oldFileId
    ) {
      console.warn("文件ID变为无效,停止所有操作:", oldFileId);

      // 设置销毁标志,停止所有操作
      isDestroying.value = true;

      // 清除所有定时器
      if (autoSaveTimer.value) {
        clearTimeout(autoSaveTimer.value);
        autoSaveTimer.value = undefined;
      }
      if (contentWatcherInterval.value) {
        clearInterval(contentWatcherInterval.value);
        contentWatcherInterval.value = undefined;
      }
      if (outlineUpdateTimer.value) {
        clearTimeout(outlineUpdateTimer.value);
        outlineUpdateTimer.value = undefined;
      }
      if (citationRerenderTimer.value) {
        clearTimeout(citationRerenderTimer.value);
        citationRerenderTimer.value = undefined;
      }

      // 停止 TOS 同步定时器
      stopTosSyncTimer();
    }
  },
);

// 监听 showReferences 变化,自动调整编辑器高度
// 参考文献数据已在编辑器初始化时加载,此处只控制显示/隐藏
watch(
  () => props.showReferences,
  (newValue) => {
    if (newValue) {
      // 显示参考文献区域
      editorHeight.value = "70%";
      referenceHeight.value = "30%";
    } else {
      // 隐藏参考文献区域,编辑器占满
      editorHeight.value = "100%";
      referenceHeight.value = "0%";
    }
  },
  { immediate: true },
);

// 监听导入方式变化,清空搜索结果和输入框
watch(
  () => importMethod.value,
  () => {
    // 清空搜索结果
    searchResults.value = [];
    hasSearched.value = false;
    // 清空输入框
    importInput.value = "";
    // 自动聚焦到输入框
    nextTick(() => {
      importInputRef.value?.focus();
    });
  },
);

// Initialize editor
onMounted(async () => {
  // 启动初始化流程
  tryInitVditor();

  // 添加点击外部关闭引用菜单的事件监听器
  document.addEventListener("click", handleClickOutside);

  // 添加滚动事件监听器,关闭引用菜单
  window.addEventListener("scroll", handleScroll, true); // 使用捕获模式监听所有滚动
  document.addEventListener("scroll", handleScroll, true);
});

// Cleanup
onBeforeUnmount(() => {
  isDestroying.value = true;

  // Clear timers
  if (outlineUpdateTimer.value) {
    clearTimeout(outlineUpdateTimer.value);
  }
  if (contentWatcherInterval.value) {
    clearInterval(contentWatcherInterval.value);
  }
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }
  if (citationRerenderTimer.value) {
    clearTimeout(citationRerenderTimer.value);
  }

  // Remove paste event listener
  if (vditorContainer.value) {
    vditorContainer.value.removeEventListener("paste", handlePaste, true);
  }

  // 同时移除可编辑区域的监听器
  const editableElement = vditorContainer.value?.querySelector(
    "[contenteditable='true']",
  );
  if (editableElement) {
    editableElement.removeEventListener("paste", handlePaste, true);
  }

  // 移除拖拽事件监听器(使用相同的捕获模式参数)
  if (vditorContainer.value) {
    vditorContainer.value.removeEventListener("dragstart", handleEditorDragStart, true);
    vditorContainer.value.removeEventListener("dragover", handleEditorDragOver, true);
    vditorContainer.value.removeEventListener("drop", handleEditorDrop, true);
  }

  // 同时移除可编辑区域的拖拽监听器
  if (editableElement) {
    editableElement.removeEventListener("dragstart", handleEditorDragStart, true);
    editableElement.removeEventListener("dragover", handleEditorDragOver, true);
    editableElement.removeEventListener("drop", handleEditorDrop, true);
  }

  // 移除点击外部关闭菜单的事件监听器
  document.removeEventListener("click", handleClickOutside);

  // 移除滚动事件监听器
  window.removeEventListener("scroll", handleScroll, true);
  document.removeEventListener("scroll", handleScroll, true);

  // 确保恢复 userSelect(防止拖拽中途组件销毁导致选择功能被永久禁用)
  document.body.style.userSelect = "";
  document.body.style.cursor = "";

  // 清理 MutationObserver
  if (
    vditorContainer.value &&
    (vditorContainer.value as any)._citationObserver
  ) {
    (vditorContainer.value as any)._citationObserver.disconnect();
    delete (vditorContainer.value as any)._citationObserver;
  }

  // Auto-save before destroy
  stopTosSyncTimer();
  if (!isSaving.value) {
    if (isTosFile.value) {
      // TOS 文件:如果有未保存的编辑 或 已缓存但未同步的修改,统一直接同步远端
      if ((hasUserEdited.value && hasUnsavedChanges.value) || hasPendingTosSync.value) {
        console.log("🔄 组件销毁前同步 TOS 文件到远端");
        hasPendingTosSync.value = true;
        autoSaveDocument(true);
      }
    } else {
      // LOCAL 文件:正常保存
      if (hasUserEdited.value && hasUnsavedChanges.value) {
        autoSaveDocument();
      }
    }
  }

  // Destroy Vditor instance
  if (vditorInstance.value) {
    try {
      // 检查实例是否还有 element 属性,避免访问 undefined 的错误
      if ((vditorInstance.value as any).element) {
        vditorInstance.value.destroy();
      }
    } catch (error) {
      console.error("销毁 Vditor 实例失败:", error);
    } finally {
      vditorInstance.value = undefined;
    }
  }
});

const tryInitVditor = async () => {
  // 已初始化,直接返回
  if (vditorInstance.value) return;

  const el = vditorContainer.value as HTMLElement | null;

  // ⚠️ DOM 存在 ≠ 可初始化
  if (!el || el.offsetParent === null) {
    requestAnimationFrame(tryInitVditor);
    return;
  }

  try {
    await initVditorEditor();
  } catch (err) {
    console.error("Vditor 初始化失败:", err);
    isLoading.value = false; // 确保加载状态被关闭
  }
};

// Initialize Vditor editor
const initVditorEditor = async () => {
  try {
    if (vditorInstance.value) {
      return;
    }
    if (isDestroying.value) {
      return;
    }

    // 等待 DOM 元素准备好
    await nextTick();

    // if (!vditorContainer.value) {
    //   if (initRetryCount.value < maxInitRetries) {
    //     initRetryCount.value++;
    //     // 延迟重试
    //     setTimeout(() => {
    //       if (!isDestroying.value) {
    //         initVditorEditor();
    //       }
    //     }, 100);
    //   } else {
    //     isLoading.value = false;
    //   }
    //   return;
    // }

    // // 检查容器元素是否在 DOM 中
    // if (!document.contains(vditorContainer.value)) {
    //   console.warn("Vditor 容器元素不在 DOM 中,延迟初始化");
    //   if (initRetryCount.value < maxInitRetries) {
    //     initRetryCount.value++;
    //     setTimeout(() => {
    //       if (!isDestroying.value) {
    //         initVditorEditor();
    //       }
    //     }, 100);
    //   } else {
    //     console.error(
    //       "Vditor 初始化失败:容器元素不在 DOM 中,已达到最大重试次数",
    //     );
    //     isLoading.value = false;
    //   }
    //   return;
    // }
    const el = vditorContainer.value as HTMLElement | null;

    if (!el || el.offsetParent === null) {
      throw new Error("Vditor 容器未处于可见布局态");
    }

    isLoading.value = true;

    // 设置 Vditor 全局配置,禁用国际化文件加载
    if (typeof window !== "undefined") {
      (window as any).vditorI18n = {
        zh_CN: {},
      };
      // 设置 lute 路径,改用 jsdelivr 镜像,提高国内访问速度
      (window as any).vditorLutePath =
        "https://cdn.jsdelivr.net/npm/vditor@3.11.2/dist/js/lute/lute.min.js";
    }

    // 设置超时保护:如果 10 秒后还没初始化完成,强行关闭加载状态
    const initTimeout = setTimeout(() => {
      if (isLoading.value && !vditorInstance.value) {
        console.warn("Vditor 初始化超时,尝试强制解除加载状态");
        isLoading.value = false;
      }
    }, 10000);

    // Load file content
    let content = props.preloadContent;
    if (!content && props.fileId) {
      content = await loadFileContent();
    } else if (content) {
      // 如果提供了 preloadContent,也需要移除参考文献部分
      content = removeReferencesSection(content);
    }

    // 🔧 修复数学公式渲染问题:预处理内容
    if (content) {
      content = preprocessMathContent(content);
    }

    originalContent.value = content;
    currentContent.value = content;
    lastSavedContent.value = content;
    hasChanges.value = false;
    hasUnsavedChanges.value = false;
    hasUserEdited.value = false;

    // Vditor configuration
    vditorInstance.value = new Vditor(vditorContainer.value as HTMLElement, {
      value: content || "# 欢迎使用 Vditor 编辑器\n\n开始编辑您的文档...",
      height: "100%",
      mode: "wysiwyg", // 所见即所得模式  "ir" 即时渲染模式 "preview" 预览模式
      theme: "classic",
      placeholder: "开始编辑您的文档...",
      customWysiwygToolbar: () => {},
      // 输入回调:内容变化时触发
      input: (value: string) => {
        handleContentChange(value);
      },
      // 使用 jsdelivr CDN 资源
      cdn: "https://cdn.jsdelivr.net/npm/vditor@3.11.2",
      
      // 注意:Lute 引擎配置需要在 after 回调中设置,这里无法直接配置

      // 工具栏配置
      toolbar: [
        "emoji",
        "headings",
        "bold",
        "italic",
        "strike",
        "|",
        "line",
        "quote",
        "list",
        "ordered-list",
        "check",
        "outdent",
        "indent",
        "|",
        "code",
        "inline-code",
        "|",
        "upload",
        "link",
        "table",
        "|",
        "undo",
        "redo",
        "|",
        "edit-mode",
        "outline",
        "preview",
        "fullscreen",
        "|",
        {
          name: "custom-export",
          tipPosition: "s",
          tip: "导出文件",
          className: "vditor-tooltipped vditor-tooltipped--s",
          icon: '<svg viewBox="0 0 32 32" width="16" height="16"><path d="M26 24v4H6v-4H4v4a2 2 0 0 0 2 2h20a2 2 0 0 0 2-2v-4z"></path><path d="M26 14l-1.41-1.41L17 20.17V2h-2v18.17l-7.59-7.58L6 14l10 10 10-10z"></path></svg>',
          click: () => {
            openExportDialog();
          },
        },
      ],

      // 上传配置
      upload: {
        url: "/api/files/upload",
        accept: "image/*,video/*,audio/*",
        multiple: true,
        fieldName: "file",
        max: 10 * 1024 * 1024, // 10MB
        async handler(files: File[]) {
          // 自定义上传处理
          const uploadedFiles: string[] = [];

          for (const file of files) {
            try {
              const sessionRes = await filesApi.createUploadSession();
              const uploadId = (sessionRes as any).data.uploadId;
              const response = await filesApi.uploadFile({
                file,
                uploadId,
                parentId: props.folderId,
              });

              if (response && response.data) {
                const fileUrl =
                  response.data.url ||
                  response.data.downloadUrl ||
                  `/api/files/${response.data.id}/download`;
                uploadedFiles.push(fileUrl);
              }
            } catch (error) {
              console.error("文件上传失败:", error);
              ElMessage.error(`文件 ${file.name} 上传失败`);
            }
          }

          if (uploadedFiles.length > 0) {
            return JSON.stringify({
              code: 0,
              msg: "",
              data: {
                errFiles: [],
                succMap: uploadedFiles.reduce(
                  (acc, url, index) => {
                    if (files[index]) {
                      acc[files[index].name] = url;
                    }
                    return acc;
                  },
                  {} as Record<string, string>,
                ),
              },
            });
          }

          return JSON.stringify({
            code: 1,
            msg: "上传失败",
            data: { errFiles: files.map((f: File) => f.name), succMap: {} },
          });
        },
      },

      // 预览配置
      preview: {
        delay: 2000, // 增加预览延迟,从 500ms 提高到 2000ms,减轻实时预览负担
        mode: "both",
        hljs: {
          enable: true,
          lineNumber: true,
          style: "github",
        },
        math: {
          engine: "KaTeX",
        },
        markdown: {
          toc: true,
          autoSpace: true,
          // 内容净化配置:禁用净化以保留自定义 HTML 标签
          // 原因:需要保留引用标记的自定义标签 <span class="citation-tag" data-work-id="...">...</span>
          // Vditor 的 sanitize 配置只支持 boolean 类型,不支持自定义配置对象
          // 由于内容来源于用户自己创建,相对安全,因此禁用净化
          sanitize: false,
        },
        // 在渲染前处理内容,将引用标记转换为 HTML
        transform: (html: string) => {
          return renderCitations(html);
        },
      },

      // 大纲配置
      outline: {
        enable: false, // 禁用内置大纲,使用自定义侧边栏
        position: "left",
      },

      // 计数器
      counter: {
        enable: true,
        type: "markdown",
      },

      // 缓存配置
      cache: {
        enable: false, // 禁用缓存,使用自己的保存逻辑
      },

      // 回调函数
      after: () => {
        clearTimeout(initTimeout); // 成功初始化,清除超时保护
        isLoading.value = false;
        initRetryCount.value = 0; // 重置重试计数器

        // 配置 Lute 选项以保留自定义 HTML 标签
        if (vditorInstance.value && (vditorInstance.value as any).lute) {
          const lute = (vditorInstance.value as any).lute;
          // 禁用 Lute 的 HTML 净化
          if (lute.SetSanitize) {
            lute.SetSanitize(false);
          }
        }

        // 启动内容监听
        startContentWatcher();

        // 生成初始大纲
        nextTick(() => {
          setTimeout(() => {
            generateOutlineItems();
            // 在编辑器初始化后,检查并移除参考文献部分(DOM 级别)
            removeReferencesFromEditor();
          }, 500);
        });

        // 🔧 在编辑器初始化时加载参考文献数据
        // 这样可以确保引用标记能够匹配到参考文献并正确渲染样式
        loadReferences().then(() => {
          // 渲染已有的引用标记(多次尝试确保完全加载)
          setTimeout(() => {
            renderCitationsInEditor();
          }, 300);

          setTimeout(() => {
            renderCitationsInEditor();
          }, 800);

          setTimeout(() => {
            renderCitationsInEditor();
          }, 1500);
        });

        // 使用 MutationObserver 监听编辑区域的变化,保护引用标签
        setTimeout(() => {
          const contentArea = vditorContainer.value?.querySelector(
            '.vditor-wysiwyg__block, .vditor-ir__preview, [contenteditable="true"]',
          );

          if (contentArea) {
            // 保存引用标签的映射,用于恢复
            const citationBackup = new Map<Node, string>();

            // 创建 MutationObserver 来监听 DOM 变化
            const observer = new MutationObserver((mutations) => {
              let needsProtection = false;

              mutations.forEach((mutation) => {
                // 在节点被移除前,先备份其 markdown 标记
                mutation.removedNodes.forEach((node) => {
                  if (node.nodeType === Node.ELEMENT_NODE) {
                    const element = node as HTMLElement;
                    if (element.classList?.contains("citation-tag")) {
                      const markdownMarkup = element.getAttribute(
                        "data-citation-markup",
                      );
                      if (markdownMarkup) {
                        // 保存到备份映射
                        citationBackup.set(node, markdownMarkup);
                        needsProtection = true;
                      }
                    }
                  }
                });
              });

              // 延迟处理,让 Vditor 先完成其操作
              if (needsProtection) {
                // 使用 setTimeout 确保在 Vditor 处理完成后执行
                setTimeout(() => {
                  // 扫描整个编辑区域,查找丢失的引用标签
                  const allCitations =
                    contentArea.querySelectorAll(".citation-tag");
                  const existingMarkups = new Set<string>();

                  // 收集当前存在的所有引用标记
                  allCitations.forEach((citation) => {
                    const markup = citation.getAttribute(
                      "data-citation-markup",
                    );
                    if (markup) {
                      existingMarkups.add(markup);
                    }
                  });

                  // 检查哪些引用标记丢失了
                  const lostMarkups: string[] = [];
                  citationBackup.forEach((markup) => {
                    if (!existingMarkups.has(markup)) {
                      lostMarkups.push(markup);
                    }
                  });

                  if (lostMarkups.length > 0) {
                    // 通过 Vditor API 获取当前内容
                    if (vditorInstance.value) {
                      const currentContent = vditorInstance.value.getValue();
                      let hasModified = false;

                      // 对于每个丢失的标记,检查内容中是否缺失
                      lostMarkups.forEach((markup) => {
                        if (!currentContent.includes(markup)) {
                          // 尝试在合适的位置插入(这里简单追加,实际可能需要更智能的位置检测)
                          // 暂时不自动插入,而是触发重新渲染
                          hasModified = true;
                        }
                      });

                      if (hasModified) {
                        // 触发防抖重新渲染
                        debouncedRerenderCitations();
                      }
                    }
                  }

                  // 清空备份
                  citationBackup.clear();
                }, 100);
              }

              // 始终触发防抖重新渲染,以便在编辑停止后恢复标签
              if (needsProtection) {
                debouncedRerenderCitations();
              }
            });

            // 开始观察
            observer.observe(contentArea, {
              childList: true,
              subtree: true,
              characterData: false, // 不监听文本变化,只监听节点变化
            });

            // 保存 observer 引用以便后续清理
            (vditorContainer.value as any)._citationObserver = observer;
          }
        }, 1000);

        // 添加粘贴事件监听,使用捕获模式确保在 Vditor 之前拦截
        // 直接绑定到容器元素,使用捕获模式(第三个参数为 true)
        if (vditorContainer.value) {
          vditorContainer.value.addEventListener("paste", handlePaste, true);
        }

        // 同时也绑定到可编辑区域作为备份
        setTimeout(() => {
          const editableElement = vditorContainer.value?.querySelector(
            "[contenteditable='true']",
          );
          if (editableElement) {
            editableElement.addEventListener("paste", handlePaste, true);
          }
        }, 500);

        // 添加拖拽事件监听器,使用捕获模式确保在 Vditor 之前拦截
        if (vditorContainer.value) {
          vditorContainer.value.addEventListener(
            "dragstart",
            handleEditorDragStart,
            true,
          );
          vditorContainer.value.addEventListener(
            "dragover",
            handleEditorDragOver,
            true, // 使用捕获模式
          );
          vditorContainer.value.addEventListener(
            "drop",
            handleEditorDrop,
            true,
          ); // 使用捕获模式
        }

        // 同时也绑定到可编辑区域
        setTimeout(() => {
          const editableElement = vditorContainer.value?.querySelector(
            "[contenteditable='true']",
          );
          if (editableElement) {
            // 禁用编辑区域的原生拖拽,防止文本选择被误判为拖拽操作
            (editableElement as HTMLElement).setAttribute("draggable", "false");
            (editableElement as HTMLElement).style.webkitUserDrag = "none";

            editableElement.addEventListener(
              "dragstart",
              handleEditorDragStart,
              true,
            );
            editableElement.addEventListener(
              "dragover",
              handleEditorDragOver,
              true, // 使用捕获模式
            );
            editableElement.addEventListener("drop", handleEditorDrop, true); // 使用捕获模式
          }
        }, 500);
      },

      input: (value: string) => {
        handleContentChange(value);

        // 触发防抖重新渲染:用户停止编辑 3 秒后重新渲染引用标签
        debouncedRerenderCitations();
      },

      blur: () => {
        handleEditorBlur();
      },
    });
  } catch (error) {
    console.error("初始化 Vditor 编辑器失败:", error);
    ElMessage.error(`编辑器初始化失败: ${(error as Error).message}`);
    isLoading.value = false;
  }
};

// 从编辑器的 DOM 中移除参考文献部分
const removeReferencesFromEditor = () => {
  if (!vditorContainer.value || !vditorInstance.value) return;

  try {
    // 查找编辑器内容区域(WYSIWYG 模式)
    let contentArea = vditorContainer.value.querySelector(
      ".vditor-wysiwyg",
    ) as HTMLElement;

    // 如果找不到,尝试其他选择器
    if (!contentArea) {
      contentArea = vditorContainer.value.querySelector(
        ".vditor-ir__preview",
      ) as HTMLElement;
    }

    if (!contentArea) {
      contentArea = vditorContainer.value.querySelector(
        '[contenteditable="true"]',
      ) as HTMLElement;
    }

    if (!contentArea) {
      console.warn("未找到编辑器内容区域");
      return;
    }

    // 查找所有标题元素
    const headings = contentArea.querySelectorAll("h1, h2, h3, h4, h5, h6");

    for (const heading of Array.from(headings)) {
      const headingText = heading.textContent?.trim() || "";

      // 检查是否是参考文献标题(支持多种格式)
      const isReferenceHeading =
        headingText === "参考文献" ||
        headingText === "References" ||
        headingText.toLowerCase() === "references" ||
        headingText.toLowerCase().includes("参考文献") ||
        headingText.toLowerCase().includes("references") ||
        heading.id?.includes("参考文献") ||
        heading.id?.includes("References");

      if (isReferenceHeading) {
        // 找到该标题的父容器(可能是 .vditor-wysiwyg__block)
        let blockElement: HTMLElement | null = heading.parentElement;

        // 向上查找,找到包含该标题的块级元素
        while (blockElement && blockElement !== contentArea) {
          if (
            blockElement.classList?.contains("vditor-wysiwyg__block") ||
            blockElement.classList?.contains("vditor-ir__node")
          ) {
            break;
          }
          blockElement = blockElement.parentElement;
        }

        // 如果找到了块级元素,从该块开始移除
        if (blockElement) {
          // 找到该块后面的所有兄弟块
          let currentNode: Element | null = blockElement.nextElementSibling;
          const blocksToRemove: Element[] = [blockElement];

          // 收集需要移除的块(直到下一个同级或更高级的标题块)
          while (currentNode) {
            const nextNode = currentNode.nextElementSibling;

            // 检查是否是标题块
            const headingInBlock = currentNode.querySelector(
              "h1, h2, h3, h4, h5, h6",
            );
            if (headingInBlock) {
              const currentHeadingLevel = parseInt(heading.tagName.charAt(1));
              const nextHeadingLevel = parseInt(
                headingInBlock.tagName.charAt(1),
              );
              // 如果下一个标题级别小于等于当前参考文献标题级别,停止
              if (nextHeadingLevel <= currentHeadingLevel) {
                break;
              }
            }

            blocksToRemove.push(currentNode);
            currentNode = nextNode;
          }

          // 移除所有收集到的块
          blocksToRemove.forEach((block) => {
            block.remove();
          });
        } else {
          // 如果找不到块级元素,使用原来的方法(节点级移除)
          let currentNode: Node | null = heading.nextSibling;
          const nodesToRemove: Node[] = [heading];

          while (currentNode) {
            const nextNode = currentNode.nextSibling;

            if (
              currentNode.nodeType === Node.ELEMENT_NODE &&
              ["H1", "H2", "H3", "H4", "H5", "H6"].includes(
                (currentNode as Element).tagName,
              )
            ) {
              const currentHeadingLevel = parseInt(heading.tagName.charAt(1));
              const nextHeadingLevel = parseInt(
                (currentNode as Element).tagName.charAt(1),
              );
              if (nextHeadingLevel <= currentHeadingLevel) {
                break;
              }
            }

            nodesToRemove.push(currentNode);
            currentNode = nextNode;
          }

          nodesToRemove.forEach((node) => {
            node.parentNode?.removeChild(node);
          });
        }

        // 更新编辑器内容
        setTimeout(() => {
          if (vditorInstance.value) {
            const currentValue = vditorInstance.value.getValue();
            // 再次检查 Markdown 内容,确保移除
            const cleanedValue = removeReferencesSection(currentValue);
            if (cleanedValue !== currentValue) {
              vditorInstance.value.setValue(cleanedValue);
            }
            handleContentChange(cleanedValue);
          }
        }, 100);

        break; // 只移除第一个找到的参考文献部分
      }
    }
  } catch (error) {
    console.error("移除参考文献部分失败:", error);
  }
};

// 移除文档中的参考文献部分
const removeReferencesSection = (content: string): string => {
  if (!content) return content;

  // 匹配参考文献部分的正则表达式
  // 匹配 "## 参考文献"、"# 参考文献"、"## References"、"# References" 等标题
  // 以及后面的所有内容
  // 支持多种格式:
  // 1. Markdown 格式:## 参考文献、# 参考文献、### 参考文献
  // 2. 可能没有换行符的情况:直接以标题开头
  // 3. 支持中英文混合
  const referencePatterns = [
    /\n##\s*参考文献[\s\S]*$/i,
    /\n#\s*参考文献[\s\S]*$/i,
    /\n###\s*参考文献[\s\S]*$/i,
    /\n####\s*参考文献[\s\S]*$/i,
    /\n#####\s*参考文献[\s\S]*$/i,
    /\n######\s*参考文献[\s\S]*$/i,
    /\n##\s*References[\s\S]*$/i,
    /\n#\s*References[\s\S]*$/i,
    /\n###\s*References[\s\S]*$/i,
    /\n####\s*References[\s\S]*$/i,
    /\n#####\s*References[\s\S]*$/i,
    /\n######\s*References[\s\S]*$/i,
    // 匹配可能没有换行符的情况(文档开头就是参考文献)
    /^##\s*参考文献[\s\S]*$/i,
    /^#\s*参考文献[\s\S]*$/i,
    /^###\s*参考文献[\s\S]*$/i,
    /^##\s*References[\s\S]*$/i,
    /^#\s*References[\s\S]*$/i,
    /^###\s*References[\s\S]*$/i,
    // 匹配 "参考文献" 或 "References" 作为独立行(前后可能有空格)
    /\n\s*参考文献\s*[\n\r][\s\S]*$/i,
    /\n\s*References\s*[\n\r][\s\S]*$/i,
  ];

  let processedContent = content;

  for (const pattern of referencePatterns) {
    if (pattern.test(processedContent)) {
      processedContent = processedContent.replace(pattern, "");
      break;
    }
  }

  // 移除末尾多余的空行
  return processedContent.trim();
};

// Load file content
const loadFileContent = async (): Promise<string> => {
  try {
    const fileId = props.fileId;

    // 获取文件元信息以确定存储类型(非 chatAnswer 时)
    if (!props.isChatAnswer) {
      try {
        const metaRes = await filesApi.getFileMeta(fileId);
        if (metaRes?.data?.storageType) {
          fileStorageType.value = metaRes.data.storageType;
        }
      } catch (e) {
        console.warn("获取文件元信息失败,默认使用 LOCAL:", e);
      }
    }

    // 1. 尝试从持久化缓存读取
    try {
      const cached = await fileCache.getFile(fileId);
      if (cached) {
        // 如果缓存中是字符串,直接返回
        if (typeof cached.content === "string") {
          console.log("Markdown 命中持久化缓存:", fileId);
          // TOS 文件启动定时同步
          if (isTosFile.value) {
            startTosSyncTimer();
          }
          return cached.content;
        }
        // 如果缓存中是 Blob(来自 Codex),转换为字符串
        if (cached.content instanceof Blob) {
          const content = await cached.content.text();
          console.log("Markdown 从 Blob 缓存转换:", fileId);
          // TOS 文件启动定时同步
          if (isTosFile.value) {
            startTosSyncTimer();
          }
          return content;
        }
      }
    } catch (e) {
      console.warn("读取 Markdown 持久化缓存失败:", e);
    }

    // 统一使用文件下载 API
    {
      // 普通文件使用文件下载 API(返回 Blob)
      const response = await filesApi.downloadFile(props.fileId);

      // 处理 Blob 响应
      let blob: Blob | null = null;

      // 如果响应被包装了,提取 Blob
      if (response instanceof Blob) {
        blob = response;
      } else if (response && typeof response === "object") {
        const anyResponse = response as any;
        if (anyResponse.data instanceof Blob) {
          blob = anyResponse.data;
        } else if (
          anyResponse.data?.code === 200 &&
          anyResponse.data?.data instanceof Blob
        ) {
          blob = anyResponse.data.data;
        }
      }

      // 确保是 Blob 对象
      if (blob instanceof Blob) {
        let content = await blob.text();

        // 移除参考文献部分
        const originalContent = content;
        content = removeReferencesSection(content);

        // 如果内容被修改了,更新文件(可选,根据需求决定是否自动保存)
        if (content !== originalContent) {
          // console.log("📝 参考文献部分已被移除");
        }

        // 3. 写入持久化缓存
        await fileCache.setFile({
          fileId,
          content,
          type: "markdown",
          fileName: props.fileName,
        });

        // TOS 文件启动定时同步
        if (isTosFile.value) {
          startTosSyncTimer();
        }

        return content;
      } else {
        console.error("❌ 响应不是 Blob 对象:", response);
        throw new Error(`响应不是有效的Blob对象,实际类型: ${typeof response}`);
      }
    }

    return "";
  } catch (error: any) {
    console.error("❌ 加载文件内容失败:", error);
    ElMessage.error(`加载文件内容失败: ${error.message || "未知错误"}`);
    return "";
  }
};

// 将编辑器中的 span 标签转换回 Markdown 标记
const convertSpanToMarkdown = (content: string): string => {
  if (!vditorContainer.value) return content;

  // 查找所有引用标签
  const contentArea = vditorContainer.value.querySelector(
    '.vditor-wysiwyg__block, .vditor-ir__preview, [contenteditable="true"]',
  );

  if (!contentArea) return content;

  const citationSpans = contentArea.querySelectorAll(
    ".citation-tag[data-citation-markup]",
  );

  // 如果没有引用标签,直接返回原内容
  if (citationSpans.length === 0) return content;

  let convertedContent = content;

  citationSpans.forEach((span) => {
    const markup = span.getAttribute("data-citation-markup");
    const spanText = span.textContent || "";

    if (markup && spanText && markup !== spanText) {
      // 只有在内容不一致时才进行替换,减少不必要的字符串操作
      convertedContent = convertedContent.replace(spanText, markup);
    }
  });

  return convertedContent;
};

// 上一次处理的内容,用于去重
let lastProcessedContent = "";
let isProcessingContentChange = false;

// Handle content change
const handleContentChange = (text: string) => {
  // 如果组件正在销毁,不处理内容变化
  if (isDestroying.value) {
    return;
  }

  // 如果正在导出,忽略内容变化事件,避免循环触发
  if (isExporting.value) {
    return;
  }

  // 防止重入:如果正在处理内容变化,直接返回
  if (isProcessingContentChange) {
    return;
  }

  // 去重:如果内容和上次一样,直接返回
  if (text === lastProcessedContent) {
    return;
  }

  isProcessingContentChange = true;
  lastProcessedContent = text;

  try {
    // 将 span 标签转换回 markdown 标记后再保存
    const convertedText = convertSpanToMarkdown(text);

    currentContent.value = convertedText;
    hasUserEdited.value = true;
    hasChanges.value = convertedText !== originalContent.value;
    hasUnsavedChanges.value = convertedText !== lastSavedContent.value;

    // 延迟更新大纲
    debouncedUpdateOutline();

    // 触发内容变化事件(不调用getHTML避免触发循环)
    emit("content-change", {
      text: convertedText,
      html: "", // 不获取HTML,避免触发编辑器事件
      hasChanges: hasChanges.value,
    });

    // 用户停止编辑后自动保存(防抖)
    debouncedAutoSave();
  } finally {
    isProcessingContentChange = false;
  }
};

// Handle editor blur - 失焦时立即保存(作为备份机制)
const handleEditorBlur = () => {
  // 清除防抖定时器,立即保存
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }

  if (hasUserEdited.value && hasUnsavedChanges.value && !isSaving.value) {
    autoSaveDocument();
  }
};

// 上次检查的内容,用于startContentWatcher去重
let lastWatcherContent = "";

// Start content watcher
const startContentWatcher = () => {
  // 清除之前的监听器
  if (contentWatcherInterval.value) {
    clearInterval(contentWatcherInterval.value);
  }

  contentWatcherInterval.value = window.setInterval(() => {
    // 如果组件正在销毁,清除定时器并返回
    if (isDestroying.value) {
      if (contentWatcherInterval.value) {
        clearInterval(contentWatcherInterval.value);
        contentWatcherInterval.value = undefined;
      }
      return;
    }

    if (!vditorInstance.value || isExporting.value) {
      return;
    }

    try {
      const currentValue = vditorInstance.value.getValue();

      // 去重:与上次检查的内容和currentContent都比较
      if (
        currentValue === lastWatcherContent ||
        currentValue === currentContent.value
      ) {
        return;
      }

      lastWatcherContent = currentValue;

      if (currentValue !== currentContent.value) {
        handleContentChange(currentValue);
      }
    } catch (error) {
      console.error("获取编辑器内容失败:", error);
    }
  }, 10000); // 进一步降低备份监听频率,从 2s 提高到 10s,主要依靠 input 回调
};

// Auto-save document
const autoSaveDocument = async (forceRemoteSave = false) => {
  // 如果组件正在销毁,不执行自动保存
  if (isDestroying.value) {
    return;
  }

  // 检查 fileId 是否有效
  if (!props.fileId || props.fileId === undefined || props.fileId === null) {
    console.warn("文件ID无效,跳过自动保存");
    return;
  }

  // forceRemoteSave 模式只需检查 hasPendingTosSync,不依赖 hasUnsavedChanges
  if (forceRemoteSave) {
    if (!hasPendingTosSync.value || isSaving.value) return;
  } else {
    if (!hasUnsavedChanges.value || isSaving.value) return;
  }

  // 参考Vite项目:如果智能体文件已保存到知识库,跳过自动保存
  if (props.isChatAnswer && isSavedToKnowledge.value) {
    return;
  }

  try {
    isSaving.value = true;

    let response;

    if (props.isChatAnswer) {
      // 智能体回答文件使用草稿更新 API
      response = await apiUpdateDraft(props.fileId, {
        content: currentContent.value,
        title: props.fileName.replace(/\.md$/, ""),
      });
    } else if (isTosFile.value && !forceRemoteSave) {
      // TOS 文件:自动保存只写 IndexedDB 缓存,不上传远端
      await fileCache.setFile({
        fileId: props.fileId,
        content: currentContent.value,
        type: "markdown",
        fileName: props.fileName,
      });

      lastSavedContent.value = currentContent.value;
      hasUnsavedChanges.value = false;
      originalContent.value = currentContent.value;
      hasChanges.value = false;
      hasPendingTosSync.value = true;

      emit("file-saved", {
        fileId: props.fileId,
        fileName: props.fileName,
        content: currentContent.value,
        isAutoSave: true,
      });

      triggerNewbieTask("doc_generate_edit");
      console.log("💾 TOS 文件已保存到本地缓存,等待定时同步");
      return;
    } else {
      // 普通文件或 TOS 强制远端保存
      response = await filesApi.saveFileContent(props.fileId, {
        content: currentContent.value,
        fileName: props.fileName,
      }, fileStorageType.value);
    }

    // 检查保存是否成功
    const anyResponse = response as any;
    const isSuccess = props.isChatAnswer
      ? response &&
        (anyResponse.status === 200 ||
          anyResponse.code === 200 ||
          anyResponse.data)
      : response && (anyResponse.code === 200 || anyResponse.status === 200);

    if (isSuccess) {
      lastSavedContent.value = currentContent.value;
      hasUnsavedChanges.value = false;
      originalContent.value = currentContent.value;
      hasChanges.value = false;
      hasPendingTosSync.value = false; // 已同步到远端

      // TOS 文件同步成功后更新 IndexedDB 缓存
      if (isTosFile.value) {
        await fileCache.setFile({
          fileId: props.fileId,
          content: currentContent.value,
          type: "markdown",
          fileName: props.fileName,
        });
      }

      // 触发保存成功事件
      emit("file-saved", {
        fileId: props.fileId,
        fileName: props.fileName,
        content: currentContent.value,
        isAutoSave: true,
      });

      // 触发新手任务:编辑/生成文档
      triggerNewbieTask("doc_generate_edit");
    } else {
      const errorMsg = props.isChatAnswer
        ? (response as any)?.message ||
          (response as any)?.data?.message ||
          "草稿更新失败"
        : (response as any)?.message || "文件保存失败";
      throw new Error(errorMsg);
    }
  } catch (error: any) {
    console.error("自动保存失败:", error);

    // 检查是否是文件不存在的错误
    const statusCode =
      error?.response?.status || error?.status || error?.statusCode;
    const errorMessage =
      error?.response?.data?.message ||
      error?.message ||
      error?.response?.data?.error ||
      "";

    // 更精确地判断文件是否被删除:
    // 1. 404 状态码(文件不存在)
    // 2. 500 状态码 + 错误消息包含"不存在"、"无权访问"、"已删除"等关键词
    // 3. 错误消息明确表示文件不存在或无权访问
    const isFileNotFound =
      statusCode === 404 ||
      (statusCode === 500 &&
        (errorMessage.includes("不存在") ||
          errorMessage.includes("无权访问") ||
          errorMessage.includes("已删除") ||
          errorMessage.includes("not found") ||
          errorMessage.includes("no permission") ||
          errorMessage.includes("deleted"))) ||
      errorMessage.includes("草稿文件不存在") ||
      errorMessage.includes("无权访问");

    // 如果是文件不存在的错误,说明文件已被删除,停止后续的自动保存
    if (isFileNotFound) {
      console.warn("文件已被删除,停止自动保存:", props.fileId);

      // 设置销毁标志,停止所有操作
      isDestroying.value = true;

      // 清除所有定时器
      if (autoSaveTimer.value) {
        clearTimeout(autoSaveTimer.value);
        autoSaveTimer.value = undefined;
      }
      if (contentWatcherInterval.value) {
        clearInterval(contentWatcherInterval.value);
        contentWatcherInterval.value = undefined;
      }
      if (outlineUpdateTimer.value) {
        clearTimeout(outlineUpdateTimer.value);
        outlineUpdateTimer.value = undefined;
      }
      if (citationRerenderTimer.value) {
        clearTimeout(citationRerenderTimer.value);
        citationRerenderTimer.value = undefined;
      }

      // 不显示错误提示,因为文件已被删除是正常情况
      return;
    }

    // 其他错误才显示提示
    const errorPrefix = props.isChatAnswer
      ? "草稿自动保存失败"
      : "文件自动保存失败";
    ElMessage.error(`${errorPrefix}: ${(error as Error).message}`);
  } finally {
    isSaving.value = false;
  }
};

// Generate outline items
const generateOutlineItems = () => {
  if (!vditorInstance.value || !vditorContainer.value) {
    outlineItems.value = [];
    emit("outline-change", []);
    return;
  }

  try {
    // 根据不同模式查找内容容器
    // wysiwyg 模式: .vditor-wysiwyg
    // IR 模式: .vditor-ir
    // 预览模式: .vditor-preview
    let contentContainer =
      vditorContainer.value.querySelector(".vditor-wysiwyg") ||
      vditorContainer.value.querySelector(".vditor-ir") ||
      vditorContainer.value.querySelector(".vditor-content") ||
      vditorContainer.value.querySelector(".vditor-preview");

    if (!contentContainer) {
      console.warn("未找到 Vditor 内容容器,尝试从整个容器中查找");
      contentContainer = vditorContainer.value;
    }

    const headingElements = contentContainer.querySelectorAll(
      "h1, h2, h3, h4, h5, h6",
    );

    if (headingElements.length === 0) {
      outlineItems.value = [];
      emit("outline-change", []);
      return;
    }

    // 生成大纲项数组
    const newItems = Array.from(headingElements).map((element, index) => {
      const level = parseInt(element.tagName.charAt(1));
      const text = element.textContent?.trim() || "";
      let id = element.id;

      // 如果元素没有 ID,且其内容不为空,为其生成一个
      if (!id && text) {
        id = `outline-heading-${index}`;
        element.id = id;
      }

      return {
        level,
        text,
        id,
        element: element as HTMLElement,
      };
    });

    // 检查大纲是否有实际变化,减少不必要的事件触发
    const isSame =
      newItems.length === outlineItems.value.length &&
      newItems.every(
        (item, i) =>
          item.text === outlineItems.value[i].text &&
          item.level === outlineItems.value[i].level &&
          item.id === outlineItems.value[i].id,
      );

    if (isSame) return;

    outlineItems.value = newItems;
    // 发出大纲变化事件
    emit("outline-change", outlineItems.value);
  } catch (error) {
    console.error("生成大纲失败:", error);
    outlineItems.value = [];
    emit("outline-change", []);
  }
};

// Debounced update outline
const debouncedUpdateOutline = () => {
  if (outlineUpdateTimer.value) {
    clearTimeout(outlineUpdateTimer.value);
  }
  outlineUpdateTimer.value = window.setTimeout(() => {
    generateOutlineItems();
  }, 2000);
};

// TOS 定时同步:每 60 秒检查是否有待同步的修改
const syncToTos = async () => {
  if (!hasPendingTosSync.value || isSaving.value) return;
  console.log("🔄 TOS 定时同步触发");
  await autoSaveDocument(true);
};

const startTosSyncTimer = () => {
  stopTosSyncTimer();
  tosSyncTimer.value = window.setInterval(() => {
    syncToTos();
  }, TOS_SYNC_INTERVAL);
};

const stopTosSyncTimer = () => {
  if (tosSyncTimer.value) {
    clearInterval(tosSyncTimer.value);
    tosSyncTimer.value = null;
  }
};

// Debounced auto save - 用户停止编辑后自动保存
const debouncedAutoSave = () => {
  // 如果组件正在销毁,不设置新的定时器
  if (isDestroying.value) {
    return;
  }

  // 清除之前的定时器
  if (autoSaveTimer.value) {
    clearTimeout(autoSaveTimer.value);
  }

  // 设置新的定时器:用户停止编辑 15 秒后自动保存 (从 3s 增加到 15s 以解决编辑器卡顿)
  autoSaveTimer.value = window.setTimeout(() => {
    // 再次检查组件是否正在销毁
    if (isDestroying.value) {
      return;
    }
    if (hasUserEdited.value && hasUnsavedChanges.value && !isSaving.value) {
      autoSaveDocument();
    }
  }, 15000); // 15秒防抖时间
};

// Public methods (exposed via defineExpose)
const getContent = () => {
  return {
    markdown: vditorInstance.value
      ? vditorInstance.value.getValue()
      : currentContent.value,
    html: vditorInstance.value ? vditorInstance.value.getHTML() : "",
  };
};

const setContent = (content: string) => {
  if (vditorInstance.value) {
    vditorInstance.value.setValue(content);
    currentContent.value = content;
    hasChanges.value = content !== originalContent.value;

    // 渲染内容中的引用标记
    setTimeout(() => {
      renderCitationsInEditor();
    }, 300);
  }
};

const insertContent = (content: string) => {
  if (vditorInstance.value) {
    vditorInstance.value.insertValue(content);
  }
};

const scrollToHeading = (headingId: string) => {
  try {
    const element = document.getElementById(headingId);
    if (element) {
      element.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }
  } catch (error) {
    console.error("滚动失败:", error);
  }
};

// 标记文件已保存到知识库(参考Vite项目实现)
const markAsSavedToKnowledge = () => {
  isSavedToKnowledge.value = true;
  hasUnsavedChanges.value = false; // 清除未保存状态
};

// Expose methods
defineExpose({
  getContent,
  setContent,
  insertContent,
  scrollToHeading,
  markAsSavedToKnowledge,
  autoSaveDocument,
});
</script>

<style scoped lang="scss">
.vditor-markdown-editor {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background: var(--color-bg, #fff);
}

.vditor-wrapper {
  flex: 1;
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.editor-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: var(--color-bg, #fff);
  z-index: 10;

  .loading-icon {
    font-size: 32px;
    color: var(--color-primary, #1890ff);
    margin-bottom: 16px;
  }

  .loading-text {
    font-size: 14px;
    color: var(--color-text-secondary, #999);
  }
}

.vditor-container {
  width: 100%;
  height: 100%;

  :deep(.vditor) {
    border: none;
    overflow: visible !important;
  }

  // 禁止编辑区域的原生文本拖拽,防止从右到左选择时被浏览器误判为拖拽操作
  :deep(.vditor-wysiwyg [contenteditable="true"]),
  :deep(.vditor-ir [contenteditable="true"]) {
    -webkit-user-drag: none;
    user-drag: none;
  }

  // Vditor 内部所有滚动条样式统一为 6px
  :deep(.vditor-wysiwyg),
  :deep(.vditor-ir),
  :deep(.vditor-preview),
  :deep(.vditor-content),
  :deep(.vditor-reset),
  :deep(.vditor-panel),
  :deep(.vditor) * {
    scrollbar-width: thin !important;
    scrollbar-color: var(--color-border, #e0e0e0) transparent !important;

    &::-webkit-scrollbar {
      width: 6px !important;
      height: 6px !important;
    }

    &::-webkit-scrollbar-track {
      background: transparent !important;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #e0e0e0) !important;
      border-radius: 3px !important;

      &:hover {
        background: var(--color-text-secondary, #999) !important;
      }
    }
  }

  // 特别针对代码块、预览区域等的滚动条
  :deep(pre),
  :deep(code),
  :deep(.vditor-reset pre),
  :deep(.vditor-reset code),
  :deep(.hljs),
  :deep(.language-),
  :deep([class*="language-"]),
  :deep(.vditor-ir pre),
  :deep(.vditor-wysiwyg pre),
  :deep(.vditor-preview pre) {
    scrollbar-width: thin !important;
    scrollbar-color: var(--color-border, #e0e0e0) transparent !important;

    &::-webkit-scrollbar {
      width: 6px !important;
      height: 6px !important;
    }

    &::-webkit-scrollbar-track {
      background: transparent !important;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #e0e0e0) !important;
      border-radius: 3px !important;

      &:hover {
        background: var(--color-text-secondary, #999) !important;
      }
    }
  }

  // Vditor 内置大纲面板的滚动条和边框
  :deep(.vditor-outline) {
    border: none !important;
    border-left: none !important;
    border-right: none !important;
  }

  :deep(.vditor-outline),
  :deep(.vditor-outline__content),
  :deep(.vditor-outline ul) {
    scrollbar-width: thin !important;
    scrollbar-color: var(--color-border, #e0e0e0) transparent !important;

    &::-webkit-scrollbar {
      width: 6px !important;
      height: 6px !important;
    }

    &::-webkit-scrollbar-track {
      background: transparent !important;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #e0e0e0) !important;
      border-radius: 3px !important;

      &:hover {
        background: var(--color-text-secondary, #999) !important;
      }
    }
  }

  :deep(.vditor-toolbar) {
    background: var(--color-card, #f5f5f5);
    border-bottom: 1px solid var(--color-border, #e0e0e0);
    // 允许提示框溢出显示
    overflow: visible !important;

    // 隐藏 Vditor 默认导出按钮
    .vditor-toolbar__item[data-type="export"] {
      display: none !important;
    }

    // 自定义导出按钮样式
    .vditor-toolbar__item[data-type="custom-export"] {
      svg {
        width: 16px;
        height: 16px;
        fill: currentColor;
      }

      &:hover {
        background-color: var(--color-hover, rgba(0, 0, 0, 0.04));
      }
    }
  }

  :deep(.vditor-content) {
    background: var(--color-bg, #fff);
  }

  // 工具栏按钮提示框样式 - 显示在下方
  :deep(.vditor-tooltipped) {
    position: relative;
    // 允许提示框溢出显示
    overflow: visible !important;

    // 移除默认的提示样式
    &::before,
    &::after {
      display: none !important;
    }

    // 只在hover时显示提示框,不在focus或active时显示
    &:hover:not(:active)::after {
      display: table !important;
      position: absolute;
      z-index: 999999;
      padding: 8px 14px;
      font-size: 13px;
      font-weight: normal;
      line-height: normal;
      color: #fff !important;
      text-align: center;
      text-decoration: none;
      word-wrap: normal;
      white-space: nowrap;
      background: rgba(0, 0, 0, 0.9) !important;
      border-radius: 4px;
      content: attr(aria-label);
      // 显示在下方,紧贴按钮
      top: calc(100% + 2px);
      left: 50%;
      transform: translateX(-50%);
      // 确保宽高自适应内容
      width: auto;
      height: auto;
      min-height: fit-content;
      max-width: none;
      box-sizing: content-box;
      box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25);
      // 确保内容完整显示
      overflow: visible;
      // 文本渲染优化
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      vertical-align: middle;
    }

    // 只在hover时显示箭头,不在active时显示
    &:hover:not(:active)::before {
      display: block !important;
      position: absolute;
      z-index: 999999;
      width: 0;
      height: 0;
      pointer-events: none;
      content: "";
      border: 5px solid transparent;
      // 箭头指向上方(提示框在下方),紧贴按钮
      border-bottom-color: rgba(0, 0, 0, 0.9);
      top: calc(100% - 3px);
      left: 50%;
      transform: translateX(-50%);
    }
  }
}

// 深色主题适配
:root[data-theme="dark"] {
  .vditor-container :deep(.vditor) {
    background: var(--color-bg, #1a1a1a);
  }

  .vditor-container :deep(.vditor-toolbar) {
    background: var(--color-card, #2c2c2c);
    border-color: var(--color-border, #404040);

    // 隐藏 Vditor 默认导出按钮
    .vditor-toolbar__item[data-type="export"] {
      display: none !important;
    }

    // 深色主题下的自定义导出按钮样式
    .vditor-toolbar__item[data-type="custom-export"] {
      &:hover {
        background-color: var(--color-hover, rgba(255, 255, 255, 0.05));
      }
    }
  }

  .vditor-container :deep(.vditor-content) {
    background: var(--color-bg, #1a1a1a);
    color: var(--color-text, #fff);
  }

  // 深色主题下的加载状态样式
  .editor-loading {
    background: var(--color-bg, #1a1a1a);

    .loading-icon {
      color: var(--color-primary, #1890ff);
    }

    .loading-text {
      color: var(--color-text-secondary, #aaa);
    }
  }

  // 深色主题下的滚动条样式
  .vditor-container :deep(.vditor-wysiwyg),
  .vditor-container :deep(.vditor-ir),
  .vditor-container :deep(.vditor-preview),
  .vditor-container :deep(.vditor-content),
  .vditor-container :deep(.vditor-reset),
  .vditor-container :deep(.vditor-panel),
  .vditor-container :deep(.vditor) * {
    scrollbar-color: var(--color-border, #404040) transparent !important;

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #404040) !important;

      &:hover {
        background: var(--color-text-secondary, #666) !important;
      }
    }
  }

  // 深色主题下代码块等的滚动条样式
  .vditor-container :deep(pre),
  .vditor-container :deep(code),
  .vditor-container :deep(.vditor-reset pre),
  .vditor-container :deep(.vditor-reset code),
  .vditor-container :deep(.hljs),
  .vditor-container :deep(.language-),
  .vditor-container :deep([class*="language-"]),
  .vditor-container :deep(.vditor-ir pre),
  .vditor-container :deep(.vditor-wysiwyg pre),
  .vditor-container :deep(.vditor-preview pre) {
    scrollbar-color: var(--color-border, #404040) transparent !important;

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #404040) !important;

      &:hover {
        background: var(--color-text-secondary, #666) !important;
      }
    }
  }

  // 深色主题下大纲面板的边框和滚动条样式
  .vditor-container :deep(.vditor-outline) {
    border: none !important;
    border-left: none !important;
    border-right: none !important;
  }

  .vditor-container :deep(.vditor-outline),
  .vditor-container :deep(.vditor-outline__content),
  .vditor-container :deep(.vditor-outline ul) {
    scrollbar-color: var(--color-border, #404040) transparent !important;

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #404040) !important;

      &:hover {
        background: var(--color-text-secondary, #666) !important;
      }
    }
  }

  // 深色主题下的提示框样式
  .vditor-container :deep(.vditor-tooltipped) {
    &:hover:not(:active)::after {
      background: rgba(60, 60, 60, 0.95) !important;
      color: #f0f0f0 !important;
    }

    &:hover:not(:active)::before {
      border-bottom-color: rgba(60, 60, 60, 0.95) !important;
    }
  }
}

// 引用标记下拉菜单样式
.citation-menu-wrapper {
  position: fixed;
  z-index: 9999;
}

.citation-menu {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 6px 0;
  min-width: 280px;
  max-width: 400px;
  max-height: 400px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.citation-menu-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 8px 16px;
  border-bottom: 1px solid #e4e7ed;

  .header-title {
    font-size: 12px;
    color: #909399;
    font-weight: 500;
    white-space: nowrap;
  }

  .header-search {
    position: relative;
    display: flex;
    align-items: center;
    flex: 1;
    max-width: 200px;
    background-color: #f5f7fa;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 4px 8px;
    transition: all 0.2s;

    &:focus-within {
      border-color: #1890ff;
      background-color: #ffffff;
    }

    .search-icon {
      color: #909399;
      font-size: 12px;
      margin-right: 6px;
      flex-shrink: 0;
    }

    .search-input {
      flex: 1;
      border: none;
      outline: none;
      background: transparent;
      color: #303133;
      font-size: 12px;
      min-width: 0;

      &::placeholder {
        color: #c0c4cc;
      }
    }
  }
}

.citation-menu-list {
  overflow-y: auto;
  max-height: 340px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: #dcdfe6;
    border-radius: 3px;

    &:hover {
      background: #c0c4cc;
    }
  }
}

.citation-menu-item {
  padding: 10px 16px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  gap: 4px;

  &:hover {
    background: #f5f7fa;
  }

  &:active {
    background: #e6f7ff;
  }

  .menu-item-note {
    font-size: 14px;
    color: #303133;
    font-weight: 500;
    line-height: 1.4;
  }

  .menu-item-meta {
    font-size: 12px;
    color: #909399;
    line-height: 1.2;
  }
}

.citation-menu-empty {
  padding: 20px;
  text-align: center;
  color: #909399;
  font-size: 13px;
}

// 深色主题适配
:root[data-theme="dark"] {
  .citation-menu {
    background: #1e1e1e;
    border-color: #3a3a3a;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.4);
  }

  .citation-menu-header {
    border-bottom-color: #3a3a3a;

    .header-title {
      color: #a0a0a0;
    }

    .header-search {
      background-color: #2a2a2a;
      border-color: #3a3a3a;

      &:focus-within {
        border-color: #1890ff;
        background-color: #1e1e1e;
      }

      .search-icon {
        color: #666;
      }

      .search-input {
        color: #e0e0e0;

        &::placeholder {
          color: #666;
        }
      }
    }
  }

  .citation-menu-list {
    &::-webkit-scrollbar-thumb {
      background: #4a4a4a;

      &:hover {
        background: #5a5a5a;
      }
    }
  }

  .citation-menu-item {
    &:hover {
      background: #2a2a2a;
    }

    &:active {
      background: rgba(24, 144, 255, 0.15);
    }

    .menu-item-note {
      color: #e0e0e0;
    }

    .menu-item-meta {
      color: #808080;
    }
  }

  .citation-menu-empty {
    color: #808080;
  }
}
</style>

<style lang="scss">
// 全局样式:移除 Vditor 的边框(不使用 scoped,确保能够覆盖 Vditor 内部样式)
.vditor-markdown-editor {
  .vditor {
    border: 0 !important;
    border-width: 0 !important;
  }

  .vditor-wysiwyg,
  .vditor-ir,
  .vditor-preview {
    border-left: 0 !important;
    border-right: 0 !important;
  }

  // 隐藏 Vditor 默认导出按钮(全局)
  .vditor-toolbar__item[data-type="export"] {
    display: none !important;
  }
}

// 全局引用标签样式
.citation-tag {
  display: inline-block !important;
  padding: 2px 8px !important;
  background-color: #e6f7ff !important;
  border-radius: 4px !important;
  color: #1890ff !important;
  font-size: 13px !important;
  font-weight: 500 !important;
  cursor: pointer !important;
  transition: all 0.2s !important;
  white-space: nowrap !important;

  // 隐藏原始的 textContent(markdown 格式)
  font-size: 0 !important;

  // 使用 ::before 伪元素显示友好的文本
  &::before {
    content: attr(data-display-text);
    font-size: 13px;
    color: #1890ff;
    font-weight: 500;
  }

  &:hover {
    background-color: rgba(24, 144, 255, 0.2) !important;
  }
}

// 拖拽预览样式
.reference-drag-preview {
  padding: 6px 12px;
  background-color: #e6f7ff;
  color: #1890ff;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  white-space: nowrap;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  border: 1px solid #91d5ff;
  pointer-events: none;
}

// Vditor 编辑器内的引用标签样式
.vditor-wysiwyg .citation-tag,
.vditor-ir .citation-tag,
.vditor-preview .citation-tag,
.vditor-content .citation-tag,
.vditor .citation-tag,
.vditor-reset .citation-tag {
  display: inline-block !important;
  padding: 2px 8px !important;
  background-color: #e6f7ff !important;
  border-radius: 4px !important;
  color: #1890ff !important;
  font-size: 13px !important;
  font-weight: 500 !important;
  cursor: pointer !important;
  transition: all 0.2s !important;
  white-space: nowrap !important;

  // 隐藏原始的 textContent(markdown 格式)
  font-size: 0 !important;

  // 使用 ::before 伪元素显示友好的文本
  &::before {
    content: attr(data-display-text);
    font-size: 13px;
    color: #1890ff;
    font-weight: 500;
  }

  &:hover {
    background-color: rgba(24, 144, 255, 0.2) !important;
  }
}

// 引用标签样式 - 应用到 Vditor 所有编辑和预览区域
.vditor-markdown-editor {
  // 在编辑器容器级别定义样式
  :deep(.vditor-wysiwyg .citation-tag),
  :deep(.vditor-ir .citation-tag),
  :deep(.vditor-preview .citation-tag),
  :deep(.vditor-content .citation-tag),
  :deep(.citation-tag) {
    display: inline-block;
    padding: 2px 8px;
    background-color: #e6f7ff !important;
    border-radius: 4px;
    color: #1890ff !important;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s;

    // 隐藏原始的 textContent(markdown 格式)
    font-size: 0 !important;

    // 使用 ::before 伪元素显示友好的文本
    &::before {
      content: attr(data-display-text);
      font-size: 13px;
      color: #1890ff;
      font-weight: 500;
    }

    &:hover {
      background-color: rgba(24, 144, 255, 0.2) !important;
    }
  }
}

// 可拖拽分割条样式
.resize-handle {
  height: 4px;
  background: transparent;
  cursor: ns-resize;
  position: relative;
  z-index: 10;
  transition: background-color 0.15s ease;
  flex-shrink: 0;

  &::before {
    content: "";
    position: absolute;
    top: -8px;
    bottom: -8px;
    left: 0;
    right: 0;
    background: transparent;
  }
}

.resize-handle:hover {
  background: var(--resize-bar-color, #1890ff);
}

.resize-handle:active {
  background: var(--resize-bar-color, #1890ff);
}

// 参考文献管理区域样式
.reference-section {
  background-color: var(--color-card, #f5f5f5);
  border-top: 1px solid var(--color-border, #e0e0e0);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  min-height: 300px;

  .reference-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px;

    .toolbar-left {
      display: flex;
      gap: 8px;

      .toolbar-btn {
        width: 32px;
        height: 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: none;
        border-radius: 4px;
        background: none;
        color: var(--color-text, #333);
        cursor: pointer;
        transition: all 0.2s;
        padding: 6px;

        &:hover {
          background-color: rgba(0, 0, 0, 0.05);
        }

        &:active {
          transform: scale(0.95);
        }

        i {
          font-size: 14px;
        }
      }
    }

    .search-input-wrapper {
      position: relative;
      display: flex;
      align-items: center;
      width: 30%; // 固定宽度为30%
      background-color: var(--color-bg, #fff);
      border: 1px solid var(--color-border, #e0e0e0);
      border-radius: 6px;
      padding: 5px 12px;
      transition: border-color 0.2s;
      margin-left: 12px; // 与左侧按钮保持间距

      &:focus-within {
        border-color: var(--color-primary, #1890ff);
      }

      .search-icon {
        color: var(--color-text-secondary, #999);
        margin-right: 8px;
        font-size: 14px;
      }

      .search-input {
        flex: 1;
        border: none;
        outline: none;
        background: transparent;
        color: var(--color-text, #333);
        font-size: 14px;

        &::placeholder {
          color: var(--color-text-secondary, #999);
        }
      }
    }
  }

  .reference-table-container {
    flex: 1;
    overflow: auto;
    border-top: 1px solid var(--color-border, #e0e0e0);
    border-radius: 6px;
    background-color: var(--color-bg, #fff);

    // 滚动条样式
    scrollbar-width: thin;
    scrollbar-color: var(--color-border, #e0e0e0) transparent;

    &::-webkit-scrollbar {
      width: 6px;
      height: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #e0e0e0);
      border-radius: 3px;

      &:hover {
        background: var(--color-text-secondary, #999);
      }
    }

    // 加载状态样式
    .reference-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      text-align: center;

      .loading-icon {
        font-size: 24px;
        color: var(--color-primary, #1890ff);
        margin-bottom: 12px;
      }

      .loading-text {
        font-size: 14px;
        color: var(--color-text-secondary, #999);
      }
    }

    // 空状态样式
    .reference-empty {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 60px 20px;
      text-align: center;

      .empty-icon {
        font-size: 48px;
        color: var(--color-border, #e0e0e0);
        margin-bottom: 16px;
      }

      .empty-text {
        font-size: 14px;
        color: var(--color-text-secondary, #999);
        margin-bottom: 8px;
      }

      .empty-hint {
        font-size: 12px;
        color: var(--color-text-tertiary, #bbb);
        font-style: italic;
      }
    }

    .reference-table {
      width: 100%;
      min-width: 800px; // 设置最小宽度,确保表格不会过于压缩
      border-collapse: collapse;
      font-size: 13px;
      table-layout: fixed; // 固定表格布局

      thead {
        background-color: var(--color-card, #f5f5f5);
        position: sticky;
        top: 0;
        z-index: 1;

        th {
          padding: 12px 8px;
          text-align: left;
          font-weight: 600;
          color: var(--color-text, #333);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;

          &:first-child {
            width: 60px; // 序列号
          }

          &:nth-child(2) {
            width: auto; // 名称 - 自动宽度,占据剩余空间
            min-width: 200px;
          }

          &:nth-child(3) {
            width: 140px; // 别名
          }

          &:nth-child(4) {
            width: 150px; // 作者
          }

          &:nth-child(5) {
            width: 80px; // 年限
          }

          &:last-child {
            width: 80px; // 详情
          }
        }
      }

      tbody {
        tr {
          transition: background-color 0.2s;
          height: 42px; // 固定行高
          cursor: move; // 显示可拖拽光标

          &:hover {
            background-color: var(--color-hover, rgba(0, 0, 0, 0.04));
          }

          &.highlighted {
            background-color: rgba(24, 144, 255, 0.1);
          }

          // 拖拽时的样式
          &:active {
            opacity: 0.7;
            cursor: grabbing;
          }

          td {
            padding: 10px 8px;
            color: var(--color-text, #333);
            vertical-align: middle; // 垂直居中对齐
            overflow: hidden;
            height: 42px; // 固定单元格高度
            box-sizing: border-box;

            &:first-child {
              text-align: left;
              font-weight: 500;
            }

            &:nth-child(2) {
              // 名称列 - 单行显示
              .title-text {
                display: block;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                line-height: 1.4;
              }
            }

            &:nth-child(3) {
              // 别名列
              padding: 0;

              .alias-display {
                display: flex;
                align-items: center;
                gap: 8px;
                padding: 10px 8px;
                height: 42px; // 固定高度
                box-sizing: border-box;

                .alias-text {
                  flex: 1;
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  line-height: 1.4;
                }

                .edit-alias-btn {
                  display: none;
                  padding: 4px 6px;
                  background: none;
                  border: none;
                  color: var(--color-text-secondary, #999);
                  cursor: pointer;
                  transition: all 0.2s;
                  border-radius: 4px;
                  flex-shrink: 0;
                  width: 24px;
                  height: 24px;
                  align-items: center;
                  justify-content: center;

                  &:hover {
                    background: var(--color-hover, rgba(0, 0, 0, 0.04));
                    color: var(--color-primary, #1890ff);
                  }

                  i {
                    font-size: 12px;
                  }
                }
              }

              &:hover .alias-display .edit-alias-btn {
                display: flex;
              }

              .alias-edit {
                width: 100%;
                padding: 6px 8px;
                height: 42px; // 固定高度
                box-sizing: border-box;
                display: flex;
                align-items: center;

                .alias-input {
                  width: 100%;
                  padding: 6px 8px;
                  border: 1px solid var(--color-primary, #1890ff);
                  border-radius: 4px;
                  background: var(--color-bg, #fff);
                  color: var(--color-text, #333);
                  font-size: 13px;
                  outline: none;
                  transition: all 0.2s;
                  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
                  height: 30px; // 固定输入框高度
                  box-sizing: border-box;

                  &:focus {
                    border-color: var(--color-primary, #1890ff);
                    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
                  }

                  &::placeholder {
                    color: var(--color-text-secondary, #999);
                  }
                }
              }
            }

            &:nth-child(4) {
              // 作者列
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              line-height: 1.4;
            }

            &.details-cell {
              text-align: center;

              .detail-icons {
                display: flex;
                gap: 4px;
                justify-content: flex-start;
                align-items: center;
                height: 100%;

                i {
                  font-size: 14px;
                  color: var(--color-text-secondary, #999);
                  cursor: pointer;
                  transition: color 0.2s;

                  &:hover {
                    color: var(--color-primary, #1890ff);
                  }

                  &.icon-b {
                    color: #1890ff;
                  }

                  &.icon-a {
                    color: #52c41a;
                  }

                  &.icon-delete {
                    color: #ff4d4f;

                    &:hover {
                      color: #ff7875;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

// 参考文献详情 popover 样式
.reference-detail-popover {
  .reference-detail-content {
    max-height: 500px;
    overflow-y: auto;
    padding: 8px 0;
    font-size: 13px;

    // 滚动条样式
    scrollbar-width: thin;
    scrollbar-color: var(--color-border, #e0e0e0) transparent;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background: var(--color-border, #e0e0e0);
      border-radius: 3px;

      &:hover {
        background: var(--color-text-secondary, #999);
      }
    }

    // 加载状态
    .detail-loading {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 40px 20px;
      gap: 12px;
      color: var(--color-primary, #1890ff);

      i {
        font-size: 24px;
      }

      span {
        font-size: 14px;
        color: var(--color-text-secondary, #999);
      }
    }

    .detail-item {
      display: flex;
      padding: 2px 12px;
      min-height: 32px;
      align-items: flex-start;

      &:last-child {
        border-bottom: none;
      }

      .detail-label {
        flex-shrink: 0;
        width: 120px;
        font-weight: 600;
        color: var(--color-text, #333);
        line-height: 1.6;
      }

      .detail-value {
        flex: 1;
        color: var(--color-text-secondary, #666);
        line-height: 1.6;
        word-break: break-word;

        &.more-authors {
          font-style: italic;
          color: var(--color-text-tertiary, #999);
        }

        .detail-link {
          color: var(--color-primary, #1890ff);
          text-decoration: none;

          &:hover {
            text-decoration: underline;
          }
        }
      }
    }
  }
}

// 导出对话框样式
.export-dialog-content {
  padding: 20px 0;

  .export-option-section {
    margin-bottom: 28px;

    &:last-child {
      margin-bottom: 0;
    }

    .option-label {
      display: block;
      font-size: 14px;
      font-weight: 600;
      color: var(--color-text, #333);
      margin-bottom: 12px;
    }

    .option-group {
      display: flex;
      gap: 24px;
    }

    .option-hint {
      margin-top: 8px;
      font-size: 12px;
      color: var(--color-text-secondary, #999);
      font-style: italic;
    }
  }
}

// 导入参考文献对话框样式
.import-dialog-content {
  padding: 12px 0;

  .import-method-section {
    margin-bottom: 24px;

    .section-label {
      display: block;
      font-size: 14px;
      font-weight: 600;
      color: var(--color-text, #333);
      margin-bottom: 12px;
    }

    .import-method-group {
      display: flex;
      gap: 24px;
    }
  }

  // 搜索区域左右布局
  .import-search-section {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;

    .section-label-inline {
      flex-shrink: 0;
      width: 80px;
      font-size: 14px;
      font-weight: 600;
      color: var(--color-text, #333);
    }

    .search-input-wrapper-inline {
      width: 400px; // 固定宽度,不再使用 flex: 1
    }
  }

  // 搜索结果区域
  .search-results-section {
    margin-top: 24px;
    border-top: 1px solid var(--color-border, #e0e0e0);
    padding-top: 16px;

    .results-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .results-count {
        font-size: 14px;
        font-weight: 600;
        color: var(--color-text, #333);
      }
    }

    .results-list {
      max-height: 400px;
      overflow-y: auto;
      padding-right: 8px;

      // 滚动条样式
      scrollbar-width: thin;
      scrollbar-color: var(--color-border, #e0e0e0) transparent;

      &::-webkit-scrollbar {
        width: 6px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background: var(--color-border, #e0e0e0);
        border-radius: 3px;

        &:hover {
          background: var(--color-text-secondary, #999);
        }
      }

      .result-item {
        padding: 12px;
        background: var(--color-card, #f5f5f5);
        border-radius: 8px;
        margin-bottom: 12px;
        transition: all 0.2s;

        &:last-child {
          margin-bottom: 0;
        }

        &:hover {
          background: var(--color-hover, rgba(0, 0, 0, 0.04));
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }

        .result-content {
          display: flex;
          flex-direction: column;
          gap: 12px;
        }

        .result-info {
          flex: 1;
          min-width: 0;

          .result-title {
            font-size: 14px;
            font-weight: 600;
            color: var(--color-text, #333);
            margin-bottom: 8px;
            line-height: 1.5;
            word-break: break-word;
          }

          .result-meta {
            display: flex;
            flex-direction: column;
            gap: 6px;
            font-size: 13px;
            color: var(--color-text-secondary, #666);

            .meta-row {
              display: flex;
              align-items: center;
              flex-wrap: wrap;
              gap: 8px;
              line-height: 1.6;
            }

            .result-authors {
              color: var(--color-text-secondary, #666);
              font-weight: 500;
            }

            .result-year {
              color: var(--color-text-secondary, #666);
              margin-left: 4px;
            }

            .result-type {
              color: var(--color-primary, #1890ff);
              font-weight: 600;
              font-size: 11px;
              text-transform: uppercase;
            }

            .result-venue {
              color: var(--color-text, #333);
              font-weight: 500;
              font-style: italic;
            }

            .result-journal-abbr {
              color: var(--color-text-secondary, #999);
              font-size: 12px;
            }

            .result-volume,
            .result-issue,
            .result-pages {
              color: var(--color-text-secondary, #666);
              font-size: 12px;
            }

            .result-issn,
            .result-doi {
              color: var(--color-text-secondary, #999);
              font-size: 11px;
              font-family: monospace;
            }
          }
        }

        .result-actions {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 8px;
          padding-top: 8px;
          border-top: 1px solid var(--color-border, #e0e0e0);

          .action-link {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            color: var(--color-primary, #1890ff);
            text-decoration: none;
            font-size: 12px;
            transition: all 0.2s;
            padding: 6px 10px;
            border-radius: 4px;
            background: rgba(24, 144, 255, 0.08);

            i {
              font-size: 11px;
            }

            &:hover {
              color: var(--color-primary-hover, #40a9ff);
              background: rgba(24, 144, 255, 0.15);
            }

            &.action-pdf {
              color: #f5222d;
              background: rgba(245, 34, 45, 0.08);

              &:hover {
                color: #ff4d4f;
                background: rgba(245, 34, 45, 0.15);
              }
            }
          }

          .el-button {
            flex-shrink: 0;
          }
        }
      }
    }
  }

  // 空状态样式
  .empty-results {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 20px;
    text-align: center;

    .empty-icon {
      font-size: 48px;
      color: var(--color-border, #e0e0e0);
      margin-bottom: 16px;
    }

    .empty-text {
      font-size: 14px;
      color: var(--color-text-secondary, #999);
      margin: 0;
    }
  }
}

// 深色主题
:root[data-theme="dark"] {
  // 深色主题下的全局引用标签样式
  .citation-tag {
    background-color: rgba(24, 144, 255, 0.15) !important;
    color: #40a9ff !important;

    // 隐藏原始的 textContent(markdown 格式)
    font-size: 0 !important;

    // 使用 ::before 伪元素显示友好的文本
    &::before {
      content: attr(data-display-text);
      font-size: 13px;
      color: #40a9ff;
      font-weight: 500;
    }

    &:hover {
      background-color: rgba(24, 144, 255, 0.25) !important;
    }
  }

  // 深色主题下的拖拽预览样式
  .reference-drag-preview {
    background-color: rgba(24, 144, 255, 0.2);
    color: #40a9ff;
    border-color: rgba(64, 169, 255, 0.5);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
  }

  // 深色主题下 Vditor 编辑器内的引用标签样式
  .vditor-wysiwyg .citation-tag,
  .vditor-ir .citation-tag,
  .vditor-preview .citation-tag,
  .vditor-content .citation-tag,
  .vditor .citation-tag,
  .vditor-reset .citation-tag {
    background-color: rgba(24, 144, 255, 0.15) !important;
    color: #40a9ff !important;

    // 隐藏原始的 textContent(markdown 格式)
    font-size: 0 !important;

    // 使用 ::before 伪元素显示友好的文本
    &::before {
      content: attr(data-display-text);
      font-size: 13px;
      color: #40a9ff;
      font-weight: 500;
    }

    &:hover {
      background-color: rgba(24, 144, 255, 0.25) !important;
    }
  }

  .vditor-markdown-editor {
    .vditor {
      border: 0 !important;
      border-width: 0 !important;
    }

    .vditor-wysiwyg,
    .vditor-ir,
    .vditor-preview {
      border-left: 0 !important;
      border-right: 0 !important;
    }
  }

  // 导出对话框深色主题样式
  .export-dialog-content {
    .export-option-section {
      .option-label {
        color: var(--color-text, #fff);
      }

      .option-hint {
        color: var(--color-text-secondary, #666);
      }
    }
  }

  // 导入对话框深色主题样式
  .import-dialog-content {
    .section-label,
    .section-label-inline {
      color: var(--color-text, #fff);
    }

    .search-results-section {
      border-top-color: var(--color-border, #404040);

      .results-header .results-count {
        color: var(--color-text, #fff);
      }

      .results-list {
        scrollbar-color: var(--color-border, #404040) transparent;

        &::-webkit-scrollbar-thumb {
          background: var(--color-border, #404040);

          &:hover {
            background: var(--color-text-secondary, #666);
          }
        }

        .result-item {
          background: var(--color-card, #2c2c2c);

          &:hover {
            background: var(--color-hover, rgba(255, 255, 255, 0.05));
          }

          .result-info {
            .result-title {
              color: var(--color-text, #fff);
            }

            .result-meta {
              color: var(--color-text-secondary, #aaa);

              .result-authors {
                color: var(--color-text-secondary, #aaa);
              }

              .result-year {
                color: var(--color-text-secondary, #aaa);
              }

              .result-type {
                color: var(--color-primary, #1890ff);
              }

              .result-venue {
                color: var(--color-text, #fff);
              }

              .result-journal-abbr {
                color: var(--color-text-secondary, #666);
              }

              .result-volume,
              .result-issue,
              .result-pages {
                color: var(--color-text-secondary, #aaa);
              }

              .result-issn,
              .result-doi {
                color: var(--color-text-secondary, #666);
              }
            }
          }

          .result-actions {
            border-top-color: var(--color-border, #404040);

            .action-link {
              color: var(--color-primary, #1890ff);
              background: rgba(24, 144, 255, 0.12);

              &:hover {
                color: var(--color-primary-hover, #40a9ff);
                background: rgba(24, 144, 255, 0.2);
              }

              &.action-pdf {
                color: #ff4d4f;
                background: rgba(245, 34, 45, 0.12);

                &:hover {
                  color: #ff7875;
                  background: rgba(245, 34, 45, 0.2);
                }
              }
            }
          }
        }
      }
    }

    .empty-results {
      .empty-icon {
        color: var(--color-border, #404040);
      }

      .empty-text {
        color: var(--color-text-secondary, #666);
      }
    }
  }

  // 深色主题下的 popover 样式
  .reference-detail-popover {
    .reference-detail-content {
      scrollbar-color: var(--color-border, #404040) transparent;

      &::-webkit-scrollbar-thumb {
        background: var(--color-border, #404040);

        &:hover {
          background: var(--color-text-secondary, #666);
        }
      }

      .detail-item {
        border-bottom-color: var(--color-border, #2c2c2c);

        .detail-label {
          color: var(--color-text, #fff);
        }

        .detail-value {
          color: var(--color-text-secondary, #aaa);

          &.more-authors {
            color: var(--color-text-tertiary, #777);
          }
        }
      }
    }
  }

  // 深色主题下的引用标签样式
  .vditor-markdown-editor {
    :deep(.vditor-wysiwyg .citation-tag),
    :deep(.vditor-ir .citation-tag),
    :deep(.vditor-preview .citation-tag),
    :deep(.vditor-content .citation-tag),
    :deep(.citation-tag) {
      background-color: rgba(24, 144, 255, 0.15) !important;
      color: #40a9ff !important;

      // 隐藏原始的 textContent(markdown 格式)
      font-size: 0 !important;

      // 使用 ::before 伪元素显示友好的文本
      &::before {
        content: attr(data-display-text);
        font-size: 13px;
        color: #40a9ff;
        font-weight: 500;
      }

      &:hover {
        background-color: rgba(24, 144, 255, 0.25) !important;
      }
    }
  }

  // 深色主题下的参考文献管理区域样式覆盖
  .reference-section {
    background-color: var(--color-card, #2c2c2c);
    border-top-color: var(--color-border, #404040);

    .reference-toolbar {
      .toolbar-left .toolbar-btn {
        background: none;
        border: none;
        color: var(--color-text, #fff);

        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      }

      .search-input-wrapper {
        background-color: var(--color-bg, #1a1a1a);
        border-color: var(--color-border, #404040);

        .search-icon {
          color: var(--color-text-secondary, #666);
        }

        .search-input {
          color: var(--color-text, #fff);

          &::placeholder {
            color: var(--color-text-secondary, #666);
          }
        }
      }
    }

    .reference-table-container {
      border-color: var(--color-border, #404040);
      background-color: var(--color-bg, #1a1a1a);

      // 深色主题滚动条
      scrollbar-color: var(--color-border, #404040) transparent;

      &::-webkit-scrollbar-thumb {
        background: var(--color-border, #404040);

        &:hover {
          background: var(--color-text-secondary, #666);
        }
      }

      // 深色主题加载状态
      .reference-loading {
        .loading-icon {
          color: var(--color-primary, #1890ff);
        }

        .loading-text {
          color: var(--color-text-secondary, #aaa);
        }
      }

      // 深色主题空状态
      .reference-empty {
        .empty-icon {
          color: var(--color-border, #404040);
        }

        .empty-text {
          color: var(--color-text-secondary, #666);
        }

        .empty-hint {
          color: var(--color-text-tertiary, #555);
        }
      }

      .reference-table {
        thead {
          background-color: var(--color-card, #2c2c2c);

          th {
            color: var(--color-text, #fff);
            border-bottom-color: var(--color-border, #404040);
          }
        }

        tbody tr {
          border-bottom-color: var(--color-border, #404040);
          height: 42px; // 固定行高
          cursor: move; // 显示可拖拽光标

          &:hover {
            background-color: var(--color-hover, rgba(255, 255, 255, 0.05));
          }

          // 拖拽时的样式
          &:active {
            opacity: 0.7;
            cursor: grabbing;
          }

          td {
            color: var(--color-text, #fff);
            height: 42px; // 固定单元格高度
            vertical-align: middle; // 垂直居中对齐

            &:nth-child(3) {
              .alias-display {
                height: 42px; // 固定高度

                .edit-alias-btn {
                  color: var(--color-text-secondary, #666);
                  width: 24px;
                  height: 24px;

                  &:hover {
                    background: var(--color-hover, rgba(255, 255, 255, 0.05));
                    color: var(--color-primary, #1890ff);
                  }
                }
              }

              .alias-edit {
                height: 42px; // 固定高度

                .alias-input {
                  background: var(--color-bg, #1a1a1a);
                  color: var(--color-text, #fff);
                  border-color: var(--color-primary, #1890ff);
                  height: 30px; // 固定输入框高度

                  &::placeholder {
                    color: var(--color-text-secondary, #666);
                  }
                }
              }
            }

            // 深色主题下的详情图标样式
            &.details-cell {
              .detail-icons {
                i {
                  &.icon-delete {
                    color: #ff4d4f;

                    &:hover {
                      color: #ff7875;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>