DeerFlowChat.vue 146 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
<!--
 * @Author: 赵丽婷
 * @Date: 2025-11-10 10:30:43
 * @LastEditors: 赵丽婷
 * @LastEditTime: 2026-01-12 10:53:22
 * @FilePath: \LinkMed\linkmed-vue3\src\components\Chat\DeerFlowChat.vue
 * @Description: 
 * Copyright (c) 2025 by 北京连心医疗科技有限公司, All Rights Reserved. 
-->
<template>
  <div class="deerflow-chat">
    <!-- 返回按钮 -->
    <div v-if="props.showBackButton" class="back-button-container">
      <div
        class="back-button"
        @click="handleBack"
        :title="t('welcomeSidebar.backToScheduledTaskList')"
      >
        <i class="fas fa-arrow-left"></i>
      </div>
    </div>
    <!-- 主聊天区域 -->
    <div class="chat-main" v-if="hasMessages">
      <!-- Header 区域:用户消息 + 模型状态栏 -->
      <div class="chat-header" v-if="latestUserMessage">
        <div class="header-content">
          <div class="user-message-header">
            <div class="message-text-wrapper">
              <div
                ref="messageTextRef"
                class="message-text"
                :class="{
                  collapsed: !isMessageExpanded && shouldShowExpandButton,
                }"
                v-html="formatMessage(latestUserMessage.content)"
              ></div>
              <div class="message-header-tools">
                <img
                  src="/fuzhi.svg"
                  alt="复制"
                  class="icon-svg"
                  :title="t('chat.copy')"
                  @click="handleCopy(latestUserMessage.content)"
                />
                <i
                  v-if="shouldShowExpandButton"
                  class="toggle-icon fas"
                  :class="isMessageExpanded ? 'fa-chevron-up' : 'fa-chevron-down'"
                  @click="toggleMessageExpand"
                ></i>
              </div>
            </div>
            <div class="model-status">
              <!-- 使用 computed 属性显示当前实际状态 -->
              <span class="status-badge" :class="currentProcessingStatus.class">
                <i :class="currentProcessingStatus.icon"></i>
                {{ currentProcessingStatus.text }}
              </span>
              <!-- 中止按钮 -->
              <el-button
                v-if="deerflowStore.streaming && !deerflowStore.processingStatus.isResearchInProgress && !deerflowStore.processingStatus.isPlanGenerating && !deerflowStore.processingStatus.isReportGenerating"
                class="stop-button"
                size="small"
                type="danger"
                plain
                @click="handleStopStreaming"
              >
                <i class="fas fa-stop"></i>
                {{ t("chat.stop") || "停止" }}
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 高级筛选选项 -->
      <div
        class="advanced-filter-container"
        v-if="selectedFilterOptions.length > 0"
      >
        <div class="advanced-filter-btn" @click="handleAdvancedFilterClick">
          <img src="/shaixuan.svg" class="filter-icon" alt="高级筛选" />
        </div>
        <!-- 筛选的内容 -->
        <div class="filter-tags-wrapper">
          <div
            ref="filterTagsRef"
            class="filter-tags"
            :class="{
              collapsed: !isFilterTagsExpanded && shouldShowFilterExpandButton,
            }"
          >
            <span
              v-for="option in selectedFilterOptions"
              :key="option.id"
              class="filter-tag"
              :title="
                option.labelText
                  ? option.labelText
                  : option.translationKey
                    ? t(option.translationKey)
                    : option.id
              "
              @click="handleAdvancedFilterClick"
            >
              {{
                option.labelText
                  ? option.labelText
                  : option.translationKey
                    ? t(option.translationKey)
                    : option.id
              }}
            </span>
          </div>
          <i
            v-if="shouldShowFilterExpandButton"
            class="toggle-icon fas"
            :class="isFilterTagsExpanded ? 'fa-chevron-up' : 'fa-chevron-down'"
            @click="toggleFilterTagsExpand"
          ></i>
        </div>
      </div>

      <!-- Tab 切换栏 - 固定在顶部 - 仅在有消息时显示 -->
      <div class="global-tabs">
        <button
          class="tab-button"
          :class="{
            active: globalActiveTab === 'plan',
            disabled: !canSwitchToPlan,
          }"
          @click="handleTabSwitch('plan')"
          :disabled="!canSwitchToPlan"
        >
          <i class="fas fa-list-alt"></i>
          {{ t("chat.planContent") || "详细计划内容" }}
        </button>
        <button
          class="tab-button"
          :class="{
            active: globalActiveTab === 'reasoning',
            disabled: !canSwitchToReasoning,
          }"
          @click="handleTabSwitch('reasoning')"
          :disabled="!canSwitchToReasoning"
        >
          <i class="fas fa-lightbulb"></i>
          {{ t("chat.reasoning") || "推理过程" }}
        </button>
        <button
          class="tab-button"
          :class="{
            active: globalActiveTab === 'results',
            disabled: !canSwitchToResults,
          }"
          @click="handleTabSwitch('results')"
          :disabled="!canSwitchToResults"
        >
          <i class="fas fa-file-alt"></i>
          {{ t("chat.results") || "最终结果" }}
        </button>
      </div>

      <!-- 聊天消息区域 -->
      <div class="chat-messages" ref="messagesContainer" @scroll="handleScroll">
        <div
          v-for="message in safeMessages"
          :key="message.id"
          :data-message-id="message.id"
          class="message"
          :class="{
            assistant: message.role === 'assistant',
          }"
        >
          <div class="message-content">
            <!-- AI 消息 -->
            <div v-if="message.role === 'assistant'" class="assistant-message">
              <div v-if="message.agentContents" class="multi-agent-container">
                <!-- 计划内容 Tab - 显示 planner -->
                <div v-if="globalActiveTab === 'plan'" class="plan-tab-content">
                  <div
                    v-if="
                      shouldShowPlan(message, 'planner') &&
                      message.agentContents.planner
                    "
                    class="plan-card"
                  >
                    <div class="plan-content">
                      <div class="plan-card-container">
                        <div class="plan-body">
                          <!-- 计划思路 -->
                          <div
                            v-if="getPlanData(message, 'planner').thought"
                            class="plan-thought"
                          >
                            <div
                              :id="`content-${message.id}-planner`"
                              class="thought-content"
                              :class="{
                                typing:
                                  message.agentContents.planner.status ===
                                  'typing',
                              }"
                              v-html="
                                formatMarkdown(
                                  getPlanData(message, 'planner').thought,
                                )
                              "
                            ></div>
                          </div>

                          <!-- 执行步骤 -->
                          <div
                            v-if="
                              getPlanData(message, 'planner').steps &&
                              getPlanData(message, 'planner').steps.length
                            "
                            class="plan-steps"
                          >
                            <div class="steps-container">
                              <div
                                v-for="(
                                  step, stepIndex
                                ) in editingPlanMessageId === message.id
                                  ? editedPlanData?.steps
                                  : getPlanData(message, 'planner').steps"
                                :key="`step-${stepIndex}`"
                                class="step-item"
                                :class="{
                                  'step-editing':
                                    editingPlanMessageId === message.id,
                                }"
                                :data-step-number="Number(stepIndex) + 1"
                              >
                                <div class="step-content">
                                  <div class="step-header">
                                    <!-- 编辑模式:可编辑输入框 -->
                                    <input
                                      v-if="editingPlanMessageId === message.id"
                                      v-model="
                                        editedPlanData.steps[stepIndex].title
                                      "
                                      class="step-title-input"
                                      :placeholder="
                                        t('chat.stepTitlePlaceholder') ||
                                        '请输入步骤标题'
                                      "
                                    />
                                    <!-- 非编辑模式:显示渲染后的内容 -->
                                    <div
                                      v-else
                                      :id="`step-title-${message.id}-${stepIndex}`"
                                      class="step-title"
                                      v-html="
                                        formatMarkdown(
                                          step.title ||
                                            t('chat.step') +
                                              ' ' +
                                              (Number(stepIndex) + 1),
                                        )
                                      "
                                    ></div>
                                    <div
                                      v-if="step.tools && step.tools.length"
                                      class="tools-badge"
                                    >
                                      <i class="el-icon-setting"></i>
                                      <span>{{ step.tools.length }}</span>
                                    </div>
                                  </div>
                                  <!-- 编辑模式:可编辑文本域 -->
                                  <textarea
                                    v-if="
                                      editingPlanMessageId === message.id &&
                                      editedPlanData.steps[stepIndex]
                                        .description
                                    "
                                    v-model="
                                      editedPlanData.steps[stepIndex]
                                        .description
                                    "
                                    class="step-description-textarea"
                                    :placeholder="
                                      t('chat.stepDescriptionPlaceholder') ||
                                      '请输入步骤描述'
                                    "
                                    rows="4"
                                  />
                                  <!-- 非编辑模式:显示渲染后的内容 -->
                                  <div
                                    v-else-if="step.description"
                                    :id="`step-desc-${message.id}-${stepIndex}`"
                                    class="step-description"
                                    v-html="formatMarkdown(step.description)"
                                  ></div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 计划操作按钮 -->
                  <div
                    v-if="
                      shouldShowPlannerActions(message) &&
                      !props.isHistoryMode
                    "
                    class="plan-actions-wrapper"
                  >
                    <!-- 编辑模式:只显示"继续检索"按钮 -->
                    <template v-if="editingPlanMessageId === message.id">
                      <button
                        class="plan-action-btn btn-continue btn-blue-outline"
                        @click="handlePlanAction(message, 'continue_research')"
                        :disabled="planActionLoading"
                      >
                        <i class="fas fa-arrow-right"></i>
                        {{ t("chat.continueResearch") || "继续检索" }}
                      </button>
                    </template>
                    <!-- 非编辑模式:显示"修订计划"和"接受计划"按钮 -->
                    <!-- 只有在未开启自动接受计划时,才显示这些按钮 -->
                    <template
                      v-else-if="
                        !settingsStore.autoAcceptPlan &&
                        !hasResearchContent(message) &&
                        isThreadStillInterrupted(message)
                      "
                    >
                      <button
                        class="plan-action-btn btn-edit btn-blue-outline"
                        @click="handlePlanAction(message, 'edit_plan')"
                        :disabled="planActionLoading"
                      >
                        <i class="fas fa-edit"></i>
                        {{ t("chat.editPlan") || "修订计划" }}
                      </button>
                      <button
                        class="plan-action-btn btn-accept btn-blue-outline"
                        @click="handlePlanAction(message, 'accepted')"
                        :disabled="planActionLoading"
                      >
                        <i class="fas fa-check-circle"></i>
                        {{ t("chat.acceptPlan") || "接受计划" }}
                      </button>
                    </template>
                  </div>

                  <div
                    v-else-if="
                      (!message.agentContents.planner ||
                        !shouldShowPlan(message, 'planner')) &&
                      schedulesStore.repeatType !== 'immediately'
                    "
                    class="no-content-message"
                  >
                    <template
                      v-if="
                        message.agentContents.reporter ||
                        hasResearchContent(message)
                      "
                    >
                      {{ t("chat.noPlanContent") || "暂无计划内容" }}
                    </template>
                    <template v-else>
                      <div class="loading-spinner">
                        <i class="fas fa-spinner fa-spin"></i>
                      </div>
                      <div class="loading-text">
                        {{ t("chat.loadingMessages") }}
                      </div>
                    </template>
                  </div>
                </div>

                <!-- 推理过程 Tab - 显示 researcher -->
                <div
                  v-if="globalActiveTab === 'reasoning'"
                  class="reasoning-tab-content"
                  :class="{
                    'has-content': hasReasoningContent(message),
                  }"
                >
                  <!-- 垂直时间线容器 -->
                  <div class="timeline-container">
                    <!-- 遍历所有 researcher 的内容 -->
                    <div
                      v-for="(agentItem, index) in getOrderedAgentContents(
                        message,
                      )"
                      :key="agentItem.name"
                      class="timeline-node agent-node"
                      :class="`${agentItem.name}-node`"
                    >
                      <div class="timeline-content">
                        <div class="timeline-header">
                          <div class="timeline-header-left">
                            <div class="timeline-icon agent-icon">
                              <span class="step-number">{{
                                String(index + 1).padStart(2, "0")
                              }}</span>
                            </div>
                            <div class="timeline-title">
                              {{ getAgentDisplayName(agentItem.name) }}
                            </div>
                          </div>
                          <button
                            class="expand-toggle-btn"
                            @click="
                              toggleExpand(
                                message.id,
                                `${agentItem.name}-${index}`,
                              )
                            "
                            :title="
                              isExpanded(
                                message.id,
                                `${agentItem.name}-${index}`,
                              )
                                ? '收起'
                                : '展开'
                            "
                          >
                            <i
                              class="fas"
                              :class="
                                isExpanded(
                                  message.id,
                                  `${agentItem.name}-${index}`,
                                )
                                  ? 'fa-chevron-up'
                                  : 'fa-chevron-down'
                              "
                            ></i>
                          </button>
                        </div>

                        <!-- Agent 内容 -->
                        <div
                          class="agent-content-wrapper"
                          v-show="
                            isExpanded(message.id, `${agentItem.name}-${index}`)
                          "
                        >
                          <div
                            v-if="
                              agentItem.content.content ||
                              agentItem.content.reasoningContent
                            "
                            class="agent-content-wrapper"
                          >
                            <!-- 回答内容 -->
                            <div
                              v-if="agentItem.content.content"
                              class="content-section"
                            >
                              <div
                                class="content"
                                :class="{
                                  typing: agentItem.content.status === 'typing',
                                }"
                                v-html="
                                  formatMarkdown(agentItem.content.content)
                                "
                              ></div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    v-if="
                      getOrderedAgentContents(message).length === 0 &&
                      schedulesStore.repeatType !== 'immediately'
                    "
                    class="no-content-message"
                  >
                    {{ t("chat.noReasoningContent") }}
                  </div>
                </div>

                <!-- Results Tab 内容 - 只显示 reporter -->
                <div
                  v-if="globalActiveTab === 'results'"
                  class="results-tab-content"
                >
                  <div
                    v-if="message.agentContents.reporter"
                    class="agent-section reporter-message"
                  >
                    <div
                      v-if="
                        message.agentContents.reporter.content ||
                        message.agentContents.reporter.reasoningContent
                      "
                      class="agent-content-wrapper"
                    >
                      <!-- 回答内容 -->
                      <div
                        v-if="message.agentContents.reporter.content"
                        class="content-section"
                      >
                        <div
                          class="content"
                          :class="{
                            typing:
                              message.agentContents.reporter.status ===
                              'typing',
                          }"
                          v-html="
                            formatMarkdown(
                              removeKeyCitations(
                                message.agentContents.reporter.content,
                              ),
                            )
                          "
                        ></div>
                      </div>
                    </div>
                  </div>
                  <div
                    v-if="
                      !message.agentContents.reporter &&
                      schedulesStore.repeatType !== 'immediately'
                    "
                    class="no-results-message"
                  >
                    {{ t("chat.noResults") }}
                  </div>
                </div>
              </div>

              <!-- 状态提示:计划生成中 -->
              <div
                v-if="
                  globalActiveTab === 'plan' &&
                  deerflowStore.processingStatus.isPlanGenerating &&
                  deerflowStore.streaming &&
                  deerflowStore.getThreadInterrupted(
                    deerflowStore.currentThreadId || '',
                  ) !== false
                "
                class="status-indicator"
              >
                <div class="status-content">
                  <div class="thinking-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                  <span>{{ t("chat.planGenerating") }}</span>
                </div>
              </div>
              <!-- 状态提示:检索内容中 -->
              <div
                v-if="
                  globalActiveTab === 'reasoning' &&
                  deerflowStore.processingStatus.isResearchInProgress
                "
                class="status-indicator"
              >
                <div class="status-content">
                  <div class="thinking-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                  <span>{{ t("chat.researchInProgress") }}</span>
                </div>
              </div>
              <!-- 状态提示:报告生成中 -->
              <div
                v-if="
                  globalActiveTab === 'results' &&
                  deerflowStore.processingStatus.isReportGenerating &&
                  message.status !== 'completed'
                "
                class="status-indicator"
              >
                <div class="status-content">
                  <div class="thinking-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                  <span>{{ t("chat.reportGenerating") }}</span>
                </div>
              </div>

              <!-- 工具图标容器 - 仅在"最终结果"标签栏中显示,且 reporter 完成后 -->
              <div
                v-if="
                  globalActiveTab === 'results' &&
                  !deerflowStore.processingStatus.isReportGenerating
                "
                class="message-tools"
              >
                <!-- 反馈按钮:👍 / 👎 -->
                <div class="feedback-tools">
                  <el-popover
                    placement="top"
                    :width="260"
                    trigger="contextmenu"
                    :visible="getFeedbackVisible(message.id, 'positive')"
                    popper-class="feedback-popover"
                    :disabled="message.feedbackSubmitted"
                  >
                    <template #reference>
                      <i 
                        class="feedback-icon" 
                        :class="[
                          message.feedback === 'positive' ? 'fas fa-thumbs-up is-active' : 'far fa-thumbs-up',
                          { 'is-disabled': message.feedbackSubmitted }
                        ]"
                        @click.stop="(e) => toggleFeedbackPopover(e, message.id, 'positive')"
                      ></i>
                    </template>
                    <div class="feedback-tags-container">
                      <div class="feedback-title">
                        {{ t("chat.whyLike") || "哪些方面做得好?" }}
                      </div>
                      <div class="tags-list">
                        <el-tag
                          v-for="tag in positiveTags"
                          :key="tag"
                          size="small"
                          :effect="
                            isTagSelected(message, tag) ? 'dark' : 'plain'
                          "
                          class="feedback-tag"
                          @click="handleTagClick(message, 'positive', tag)"
                        >
                          {{ getTagLabel('positive', tag) }}
                        </el-tag>
                      </div>
                      <div class="feedback-footer">
                        <el-button 
                          type="primary" 
                          size="small" 
                          :disabled="!message.feedbackTags?.length"
                          @click="submitFeedback(message, 'positive')"
                        >
                          {{ t("common.submit") || "提交" }}
                        </el-button>
                      </div>
                    </div>
                  </el-popover>

                  <el-popover
                    placement="top"
                    :width="260"
                    trigger="contextmenu"
                    :visible="getFeedbackVisible(message.id, 'negative')"
                    popper-class="feedback-popover"
                    :disabled="message.feedbackSubmitted"
                  >
                    <template #reference>
                      <i 
                        class="feedback-icon" 
                        :class="[
                          message.feedback === 'negative' ? 'fas fa-thumbs-down is-active' : 'far fa-thumbs-down',
                          { 'is-disabled': message.feedbackSubmitted }
                        ]"
                        @click.stop="(e) => toggleFeedbackPopover(e, message.id, 'negative')"
                      ></i>
                    </template>
                    <div class="feedback-tags-container">
                      <div class="feedback-title">
                        {{ t("chat.whyDislike") || "哪些方面需要改进?" }}
                      </div>
                      <div class="tags-list">
                        <el-tag
                          v-for="tag in negativeTags"
                          :key="tag"
                          size="small"
                          type="danger"
                          :effect="
                            isTagSelected(message, tag) ? 'dark' : 'plain'
                          "
                          class="feedback-tag"
                          @click="handleTagClick(message, 'negative', tag)"
                        >
                          {{ getTagLabel('negative', tag) }}
                        </el-tag>
                      </div>
                      <div class="feedback-footer">
                        <el-button 
                          type="primary" 
                          size="small" 
                          :disabled="!message.feedbackTags?.length"
                          @click="submitFeedback(message, 'negative')"
                        >
                          {{ t("common.submit") || "提交" }}
                        </el-button>
                      </div>
                    </div>
                  </el-popover>
                </div>

                <div class="divider-vertical"></div>

                <img
                  src="/bianji.svg"
                  alt="生成文档并编辑"
                  class="icon-svg"
                  :class="{ disabled: !isMessageCompleted(message) }"
                  :title="t('chat.generateDocument')"
                  @click="handleSaveAndEdit(message)"
                />
                <img
                  src="/fuzhi.svg"
                  alt="复制"
                  class="icon-svg"
                  :class="{ disabled: !isMessageCompleted(message) }"
                  :title="t('chat.copy')"
                  @click="handleCopyMessage(message)"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 - 当没有消息时显示 -->
    <div v-if="!hasMessages" class="chat-loading-state">
      <div class="loading-spinner">
        <i class="fas fa-spinner fa-spin"></i>
      </div>
      <div class="loading-text">
        {{ t("chat.loadingMessages") }}
      </div>
    </div>

    <!-- 深度检索启动卡片(靠左侧边栏展示) -->
    <div v-if="showDeepSearchStartingModal" class="deep-search-starting-card">
      <div class="deep-search-card-inner">
        <div class="deep-search-card-header">
          <div class="header-left">
            <span class="header-title">
              {{ t("chat.deepSearchStarted") || "深度检索已启动" }}
            </span>
          </div>
          <i class="fas fa-times header-close" @click="handleWaitOnPage"></i>
        </div>

        <div class="deep-search-card-body">
          <div class="info-item">
            <i class="far fa-clock info-icon"></i>
            <span class="info-text">
              {{
                t("chat.deepSearchTimeHint") ||
                "预计耗时约30分钟(不同数据源检索时长存在差异)"
              }}
            </span>
          </div>
          <div class="info-item">
            <i class="fas fa-mobile-alt info-icon"></i>
            <span class="info-text">
              {{
                t("chat.deepSearchNotifyHint") ||
                "完成后将通过短信+邮件通知你"
              }}
            </span>
          </div>
          <div class="info-item">
            <i class="fas fa-paperclip info-icon"></i>
            <span class="info-text">
              {{
                t("chat.deepSearchReportHint") ||
                "报告链接将发送至你的邮箱"
              }}
            </span>
          </div>
        </div>

        <div class="deep-search-card-footer">
          <el-button
            type="primary"
            class="confirm-btn"
            @click="handleWaitOnPage"
          >
            {{ t("chat.iknow") || "我知道了" }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  computed,
  nextTick,
  onMounted,
  onUnmounted,
  onUpdated,
  watch,
} from "vue";
import { useI18n } from "vue-i18n";
import { ElMessage, ElLoading } from "element-plus";
import { useRouter } from "vue-router";
import { useSettingsStore } from "@/stores/settings";
import { useDeerFlowStore } from "@/stores/deerflow";
import { useSchedulesStore } from "@/stores/schedules";
import { useAppStore } from "@/stores/app";
import { markdownToHtml, ensureKatexReady } from "@/utils/renderMarkdown";
import { saveDeepSearch } from "@/api/deerflow";
import {
  apiCreateDraftFromDeepSearch,
  apiSaveDraftToKnowledge,
} from "@/api/drafts";
import { getFiles, createFolder, getFileContent } from "@/api/files";
import { getServicePrice, consumeBeans } from "@/api/pay";
import { getReferenceDetail, type ReferenceDetail } from "@/api/references";
import { service as http } from "@/utils/request"; // 增加导入用于反馈接口
// 引入 KaTeX 样式以支持数学公式渲染(仅样式,JS 通过 ensureKatexReady 按需加载)
import "katex/dist/katex.min.css";

const { t } = useI18n();
const router = useRouter();

// Props
interface Props {
  initialMessage?: string;
  isHistoryMode?: boolean; // 是否为历史对话模式
  historyTaskId?: number | null; // 历史任务ID
  showBackButton?: boolean; // 是否显示返回按钮
  literatureFilters?: Array<{ key: string; selected: string[] }>; // 文献筛选器(从父组件传递)
  literatureDateRange?: string[]; // 文献日期范围(从父组件传递)
  literatureQuickTime?: string; // 文献快捷时间(从父组件传递)
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  back: [];
  "open-advanced-filter": [];
}>();

const deerflowStore = useDeerFlowStore();
const settingsStore = useSettingsStore();
const schedulesStore = useSchedulesStore();

// 当前处于激活状态的反馈气泡 ID 和类型
const activeFeedbackId = ref<string | null>(null);
const activeFeedbackType = ref<'positive' | 'negative' | null>(null);

// 获取反馈气泡显示状态
const getFeedbackVisible = (messageId: string, type: 'positive' | 'negative') => {
  return activeFeedbackId.value === messageId && activeFeedbackType.value === type;
};

// 设置反馈气泡显示状态
const setFeedbackVisible = (messageId: string, type: 'positive' | 'negative', visible: boolean) => {
  if (visible) {
    activeFeedbackId.value = messageId;
    activeFeedbackType.value = type;
  } else if (getFeedbackVisible(messageId, type)) {
    activeFeedbackId.value = null;
    activeFeedbackType.value = null;
  }
};

// 切换反馈气泡显示
const toggleFeedbackPopover = (e: Event, messageId: string, type: 'positive' | 'negative') => {
  e.stopPropagation();
  if (getFeedbackVisible(messageId, type)) {
    activeFeedbackId.value = null;
    activeFeedbackType.value = null;
  } else {
    activeFeedbackId.value = messageId;
    activeFeedbackType.value = type;
  }
};

// 生命周期
// 预设反馈标签映射(用于 API 提交)
const feedbackTagsMap = {
  positive: {
    dynamic: "前沿动态敏感",
    personalization: "个性化适配高",
    insight: "观点提炼精准",
    contrast: "跨研究对比深度好",
  },
  negative: {
    precision: "文献筛选精准度低",
    accuracy: "医学知识错误率高",
    homogenization: "内容同质化严重",
    significance: "临床意义缺失",
  },
};

// 预设反馈标签
const positiveTags = Object.keys(feedbackTagsMap.positive);
const negativeTags = Object.keys(feedbackTagsMap.negative);

// 获取标签显示文本
const getTagLabel = (type: 'positive' | 'negative', tag: string) => {
  return t(`chat.feedbackTags.${type}.${tag}`);
};

// 判断标签是否选中
const isTagSelected = (message: any, tag: string) => {
  return message.feedbackTags && message.feedbackTags.includes(tag);
};

// 标签点击处理(仅切换选中状态,不触发提交)
const handleTagClick = (message: any, type: string, tag: string) => {
  if (message.feedbackSubmitted) return;

  if (message.feedbackTags === undefined) {
    message.feedbackTags = [];
  }

  // 如果点击的是不同类型的反馈(👍和👎之间切换),清空之前的标签
  if (message.feedback !== type) {
    message.feedback = type;
    message.feedbackTags = [tag];
  } else {
    // 同类型反馈,切换标签选中状态
    const tagIndex = message.feedbackTags.indexOf(tag);
    if (tagIndex > -1) {
      message.feedbackTags.splice(tagIndex, 1);
    } else {
      message.feedbackTags.push(tag);
    }
  }
};

// 提交反馈内容
const submitFeedback = async (message: any, type: 'positive' | 'negative') => {
  if (!message.feedback || !message.feedbackTags?.length) {
    ElMessage.warning(t("common.warning") || "请选择反馈标签");
    return;
  }

  // 这里的 message.id 通常是前端生成的字符串 (msg_xxx)
  // 后端接口 deep-search-feedbacks 需要的是 deepSearchId (数据库自增 ID)
  // 优先从消息对象中获取保存后的 ID,兜底使用 Store 中的当前任务 ID
  const deepSearchId = message.deepSearchId || deerflowStore.currentRunningTaskId;

  if (!deepSearchId) {
    console.error("提交反馈失败: 未找到对应的 deepSearchId", { 
      messageId: message.id,
      messageDeepSearchId: message.deepSearchId,
      storeTaskId: deerflowStore.currentRunningTaskId
    });
    ElMessage.error("反馈提交失败:未找到关联的任务记录,请刷新页面重试");
    return;
  }

  try {
    // 获取标签对应的中文文本(按需求拼接)
    const tagTexts = message.feedbackTags.map((tag: string) => (feedbackTagsMap[type] as any)[tag]);

    await http.post("/agent/deep-search-feedbacks", {
      deepSearchId: Number(deepSearchId), // 确保是数字类型
      type: message.feedback === "positive" ? "like" : "dislike",
      content: tagTexts.join(","), // 拼接所选标签的中文文本
    });

    // 更新状态:标记为已提交,进入禁用状态
    message.feedbackSubmitted = true;
    
    // 关闭 Popover
    activeFeedbackId.value = null;
    activeFeedbackType.value = null;
    
    ElMessage.success(t("chat.feedbackSuccess") || "感谢您的反馈!");
  } catch (error) {
    console.error("发送反馈失败:", error);
    ElMessage.error(t("common.error") || "反馈发送失败,请重试");
  }
};

onMounted(() => {
  ensureKatexReady().catch(() => {
    // 加载失败时降级为普通 Markdown 渲染
  });
});
// 数据源ID到翻译键的映射
const dataSourceTranslationMap: Record<string, string> = {
  pubmed: "welcomeSidebar.dataSourcePubMed",
  clinicalTrials: "welcomeSidebar.dataSourceClinicalTrials",
  fdaDrug: "welcomeSidebar.dataSourceFDADrug",
  wos: "welcomeSidebar.dataSourceWos",
  arxiv: "welcomeSidebar.arxiv",
  drugReview: "welcomeSidebar.dataSourceDrugReview",
  internal: "welcomeSidebar.dataSourceInternal",
};

// 获取筛选数据:优先使用从父组件传递的 props,否则使用 settingsStore
const literatureFilters = computed(() => {
  // 如果父组件传递了筛选器,使用传递的数据
  if (props.literatureFilters !== undefined) {
    return props.literatureFilters;
  }
  // 否则使用 settingsStore 中的数据
  return settingsStore.getLiteratureFilters();
});

const literatureDateRange = computed(() => {
  // 如果父组件传递了日期范围,使用传递的数据
  if (props.literatureDateRange !== undefined) {
    return props.literatureDateRange;
  }
  // 否则使用 settingsStore 中的数据
  return settingsStore.getLiteratureDateRange();
});

// 构建 literature_filters 参数
// useStoreData: true 表示使用 store 中的数据(用于提交),false 表示使用 props 中的数据(用于显示)
const buildLiteratureFilters = (useStoreData: boolean = false) => {
  // 如果 useStoreData 为 true,使用 store 中的数据;否则使用 props 中的数据(用于显示)
  const filters = useStoreData
    ? settingsStore.getLiteratureFilters() || []
    : literatureFilters.value || [];
  const dateRange = useStoreData
    ? settingsStore.getLiteratureDateRange()
    : literatureDateRange.value;

  // 判断是否启用了知识库
  const isKnowledgeBaseEnabled =
    useStoreData && !!settingsStore.selectedKnowledgeBaseDirectory;

  // 将 literatureFilters 转换为只包含 key 和 selected 的格式,只保留 key 为 "dataSource" 的项
  const literatureFiltersFormatted = filters
    .filter((filter) => filter.key === "dataSource")
    .map((filter) => {
      // 如果启用了知识库,数据源应为空;否则如果没有选择,默认使用 pubmed
      let selected = isKnowledgeBaseEnabled
        ? []
        : filter.selected && filter.selected.length > 0
          ? filter.selected
          : ["pubmed"];

      // 强制过滤掉 medRxiv
      selected = selected.filter((id: string) => id !== "medRxiv");

      // 如果过滤后为空且未启用知识库,确保至少有 pubmed
      if (selected.length === 0 && !isKnowledgeBaseEnabled) {
        selected = ["pubmed"];
      }

      return {
        key: filter.key || "dataSource",
        selected: selected,
      };
    });

  // 构建 literature_filters 对象
  const result: any = {
    literatureFilters: literatureFiltersFormatted,
  };

  // 如果有日期范围,添加到结果中
  if (dateRange && Array.isArray(dateRange) && dateRange.length === 2) {
    result.literatureDateRange = dateRange;
  }

  // 3. 移除知识库相关的内部逻辑,因为它们现在是顶层参数
  return result;
};

// 将 UI 模式映射为后端 mode 参数
const resolveDeerFlowMode = (): "fast" | "standard" | "deep" | undefined => {
  const mode = settingsStore.getDeepSearchMode();
  if (!mode) return undefined;
  if (mode === "quick") return "fast";
  return mode;
};

// 格式化日期范围
const formatDateRange = (
  dateRange: string[] | [string, string] | null | undefined,
): string => {
  if (!dateRange || dateRange.length !== 2) return "";
  return `${dateRange[0]} / ${dateRange[1]}`;
};

// 获取所有选中的筛选选项(包括日期范围和筛选配置,不包含快捷时间)
const selectedFilterOptions = computed(() => {
  const options: Array<{
    id: string;
    translationKey?: string;
    labelText?: string;
    type: "dateRange" | "filter" | "knowledgeBase";
  }> = [];

  // 0. 添加知识库目录
  if (settingsStore.selectedKnowledgeBaseDirectory) {
    options.push({
      id: "knowledgeBase",
      labelText: settingsStore.selectedKnowledgeBaseDirectoryName || "已选知识库",
      type: "knowledgeBase",
    });
  }

  // 1. 添加日期范围
  if (literatureDateRange.value && literatureDateRange.value.length === 2) {
    options.push({
      id: "dateRange",
      labelText: formatDateRange(literatureDateRange.value),
      type: "dateRange",
    });
  }

  // 2. 添加筛选配置(只处理数据源,不处理文档类型)
  const filters = literatureFilters.value;
  filters.forEach((filterGroup: any) => {
    if (filterGroup.selected && filterGroup.selected.length > 0) {
      // 只处理数据源类型的筛选器
      if (filterGroup.key === "dataSource") {
        filterGroup.selected.forEach((selectedId: string) => {
          const translationKey = dataSourceTranslationMap[selectedId];
          if (translationKey) {
            options.push({
              id: `${filterGroup.key}-${selectedId}`,
              translationKey,
              type: "filter",
            });
          }
        });
      }
    }
  });

  return options;
});

// 筛选标签展开/收起状态
const isFilterTagsExpanded = ref(false);
const filterTagsRef = ref<HTMLElement | null>(null);

// 判断是否需要显示展开/收起按钮(检查是否超过1行)
const shouldShowFilterExpandButton = computed(() => {
  if (!filterTagsRef.value) return false;
  // 检查元素的实际高度是否超过1行
  const lineHeight =
    parseFloat(getComputedStyle(filterTagsRef.value).lineHeight) || 32;
  return filterTagsRef.value.scrollHeight > lineHeight * 1.5; // 允许一些误差
});

// 切换筛选标签展开/收起
const toggleFilterTagsExpand = () => {
  isFilterTagsExpanded.value = !isFilterTagsExpanded.value;
};

// 处理高级筛选点击
const handleAdvancedFilterClick = () => {
  emit("open-advanced-filter");
};

const safeMessages = computed(() =>
  deerflowStore.messages.filter((message: any) => !!message),
);
// 计算属性:判断是否有消息数据
const hasMessages = computed(() => {
  return safeMessages.value && safeMessages.value.length > 0;
});
const latestUserMessage = computed(() => {
  for (let i = safeMessages.value.length - 1; i >= 0; i--) {
    const message = safeMessages.value[i];
    if (message?.role === "user") {
      return message;
    }
  }
  return null;
});
const messagesContainer = ref<HTMLElement | null>(null);
const isSubmitting = ref(false); // 提交状态锁,防止重复点击
const planActionLoading = ref(false); // 计划操作加载状态
let citationClickHandler: ((event: MouseEvent) => void) | null = null; // 保存事件处理函数引用
let citationHandlerBound = false; // 标记事件监听器是否已绑定

// 引用标记弹窗相关
let citationModalElement: HTMLElement | null = null;
let citationClickOutsideHandler: ((event: MouseEvent) => void) | null = null;
let citationScrollHandler: (() => void) | null = null;

const scheduleId = ref<number | undefined>(undefined);
const showDeepSearchStartingModal = ref(false); // 深度检索启动弹窗控制

// 消息文本展开/收起状态
const isMessageExpanded = ref(false);
const messageTextRef = ref<HTMLElement | null>(null);

// 判断是否需要显示展开/收起按钮
const shouldShowExpandButton = computed(() => {
  if (!messageTextRef.value) return false;
  // 检查元素的实际高度是否超过一行(line-height * 1)
  const lineHeight =
    parseFloat(getComputedStyle(messageTextRef.value).lineHeight) || 24;
  return messageTextRef.value.scrollHeight > lineHeight * 1.5; // 允许一些误差
});

// 切换消息展开/收起
const toggleMessageExpand = () => {
  isMessageExpanded.value = !isMessageExpanded.value;
};

// 监听消息变化,重置展开状态
watch(
  latestUserMessage,
  () => {
    isMessageExpanded.value = false;
    // 等待 DOM 更新后检查是否需要显示展开按钮
    nextTick(() => {
      // shouldShowExpandButton 会自动重新计算
    });
  },
  { deep: true },
);

// 监听筛选选项变化,重置展开状态
watch(
  selectedFilterOptions,
  () => {
    isFilterTagsExpanded.value = false;
    // 等待 DOM 更新后检查是否需要显示展开按钮
    nextTick(() => {
      // shouldShowFilterExpandButton 会自动重新计算
    });
  },
  { deep: true },
);

// 全局 tab 状态管理
const globalActiveTab = ref<"plan" | "reasoning" | "results">("plan");

// 监听处理状态,自动切换 Tab
watch(
  [
    () => deerflowStore.processingStatus.isResearchInProgress,
    () => deerflowStore.processingStatus.isResearchCompleted,
    () => deerflowStore.processingStatus.isReportGenerating,
    () => deerflowStore.messages,
  ],
  ([isResearching, isResearchCompleted, isReportGenerating, messages]) => {
    // 如果正在等待用户确认计划,不要自动切换 Tab
    const lastAssistantMessage = [...messages]
      .reverse()
      .find((m) => m.role === "assistant");
    if (lastAssistantMessage?.status === "planner_waiting_confirmation") {
      return;
    }

    // 逻辑:优先显示最高进度的 Tab
    if (isResearchCompleted || isReportGenerating) {
      if (
        globalActiveTab.value === "plan" ||
        globalActiveTab.value === "reasoning"
      ) {
        console.log(
          "【调试】检测到研究已完成/正在生成报告,自动切换到最终结果 Tab",
        );
        globalActiveTab.value = "results";
      }
    } else if (isResearching) {
      if (globalActiveTab.value === "plan") {
        console.log("【调试】检测到进入检索阶段,自动切换到推理过程 Tab");
        globalActiveTab.value = "reasoning";
      }
    }
  },
  { immediate: true, deep: true },
);

// 计算属性:是否可以切换到"计划内容"tab
const canSwitchToPlan = computed(() => {
  return true; // 计划内容始终可访问
});

// 计算属性:是否可以切换到"推理过程"tab
const canSwitchToReasoning = computed(() => {
  // 只有当检索已经开始或完成,才允许查看推理过程
  return (
    deerflowStore.processingStatus.isResearchInProgress ||
    deerflowStore.processingStatus.isResearchCompleted ||
    deerflowStore.processingStatus.isReportGenerating
  );
});

// 计算属性:是否可以切换到"最终结果"tab
const canSwitchToResults = computed(() => {
  // 历史模式下,检查是否有报告内容
  if (props.isHistoryMode) {
    const lastAssistantMessage = [...deerflowStore.messages]
      .reverse()
      .find((msg: any) => msg.role === "assistant");
    const hasReporterContent =
      lastAssistantMessage?.agentContents?.reporter?.content &&
      lastAssistantMessage.agentContents.reporter.content.trim() !== "";
    return hasReporterContent;
  }

  // 非历史模式:只有当报告生成中或已完成时,才允许切换
  return (
    deerflowStore.processingStatus.isReportGenerating ||
    deerflowStore.processingStatus.isResearchCompleted
  );
});

// 计算属性:当前的实际处理状态
const currentProcessingStatus = computed(() => {
  //  计划生成中
  const tid = deerflowStore.currentThreadId || "";
  const interrupted = tid ? deerflowStore.getThreadInterrupted(tid) : undefined;
  if (
    deerflowStore.processingStatus.isPlanGenerating &&
    deerflowStore.streaming &&
    interrupted !== false
  ) {
    return {
      type: "planGenerating",
      text: t("chat.planGenerating"),
      icon: "fas fa-spinner fa-spin",
      class: "generating",
    };
  }

  // 检索内容中
  if (deerflowStore.processingStatus.isResearchInProgress) {
    return {
      type: "researchInProgress",
      text: t("chat.researchInProgress"),
      icon: "fas fa-spinner fa-spin",
      class: "searching",
    };
  }

  // 报告生成中
  if (deerflowStore.processingStatus.isReportGenerating) {
    return {
      type: "reportGenerating",
      text: t("chat.reportGenerating"),
      icon: "fas fa-spinner fa-spin",
      class: "generating",
    };
  }
  // 报告完成
  if (
    !deerflowStore.processingStatus.isReportGenerating &&
    deerflowStore.processingStatus.isResearchCompleted
  ) {
    return {
      type: "completed",
      text: t("chat.completed") || "Completed",
      icon: "fas fa-check",
      class: "success",
    };
  }

  //  默认:等待确认
  return {
    type: "pending",
    text: t("chat.pendingConfirmation") || "Pending Confirmation",
    icon: "fas fa-spinner fa-spin",
    class: "pending",
  };
});

// 展开/收起状态管理
const expandState = ref<Record<string, boolean>>({});

// 记录已处理的 planner 消息,避免重复显示按钮
const processedPlannerMessages = ref<Set<string>>(new Set());

// 编辑计划相关状态
const editingPlanMessageId = ref<string | null>(null);
const editedPlanData = ref<any>(null);

// 检查是否展开
const isExpanded = (messageId: string, agentKey: string) => {
  const key = `${messageId}-${agentKey}`;
  return expandState.value[key] ?? true; // 默认展开
};

// 切换展开/收起
const toggleExpand = (messageId: string, agentKey: string) => {
  const key = `${messageId}-${agentKey}`;
  expandState.value[key] = !isExpanded(messageId, agentKey);
};

// 处理标签切换
// 处理返回按钮点击
const handleBack = () => {
  emit("back");
};


const handleTabSwitch = (tab: "plan" | "reasoning" | "results") => {
  // 如果尝试切换到"推理过程",检查是否允许
  if (tab === "reasoning") {
    if (!canSwitchToReasoning.value) {
      ElMessage.warning("请等待任务启动后,再查看推理过程");
      return;
    }
  }

  // 如果尝试切换到"最终结果",检查是否允许
  if (tab === "results") {
    if (!canSwitchToResults.value) {
      // 如果不允许切换,显示提示信息
      if (deerflowStore.processingStatus.isResearchInProgress) {
        ElMessage.warning(
          t("chat.researchInProgressCannotSwitch") ||
            "内容正在检索中,请稍候再查看最终结果",
        );
      } else {
        ElMessage.warning(t("chat.reportNotReady") || "报告尚未生成,请稍候");
      }
      return;
    }
  }

  globalActiveTab.value = tab;
};

// 滚动控制状态
const isUserScrolling = ref(false);
const shouldAutoScroll = ref(true);
const scrollTimeout = ref<ReturnType<typeof setTimeout> | null>(null);

// 格式化消息
const formatMessage = (content: string) => {
  return content.replace(/\n/g, "<br>");
};

// 渲染引用标记为可视化标签
const renderCitations = (htmlContent: string, references?: any[]): string => {
  if (!htmlContent) return htmlContent;

  // 匹配 {{cite:workId:note}} 格式
  const citationRegex = /\{\{cite:([^:]+):([^}]*)\}\}/g;

  // 使用传入的 references
  const refs = references || [];

  return htmlContent.replace(citationRegex, (_match, workId, note) => {
    // 清理 workId 和 note
    const cleanWorkId = String(workId).trim();
    const cleanNote = String(note).trim();

    // 尝试从引用列表中找到对应的引用
    let matchedReference = null;
    if (refs.length > 0) {
      // 通过 work_id 匹配
      matchedReference = refs.find(
        (ref: any) =>
          ref.work_id !== null &&
          ref.work_id !== undefined &&
          String(ref.work_id) === cleanWorkId,
      );

      // 如果通过 workId 匹配不到,尝试通过 note 匹配
      if (!matchedReference && cleanNote) {
        matchedReference = refs.find(
          (ref: any) =>
            ref.note && ref.note.toLowerCase() === cleanNote.toLowerCase(),
        );
      }
    }

    // 构建显示文本(使用 note 作为显示文本,如果没有 note 则使用 workId)
    // 使用方括号格式:[cite:note] 或 [cite:workId]
    const finalDisplayText = `[cite:${cleanNote || cleanWorkId}]`;

    // 创建带样式的 span 标签,添加 data 属性用于事件委托
    const refId =
      matchedReference &&
      matchedReference.work_id !== null &&
      matchedReference.work_id !== undefined
        ? matchedReference.work_id
        : cleanWorkId;

    return `<span class="citation-tag" data-work-id="${cleanWorkId}" data-citation-note="${cleanNote}" data-ref-id="${refId}">${finalDisplayText}</span>`;
  });
};

// 移除 reporter 内容中的参考文献部分,避免在最终结果中显示
const removeKeyCitations = (content: string) => {
  if (!content) return content;

  // 查找"参考文献"或"Key Citations"的位置
  // 支持多种格式:### 参考文献、## 参考文献、参考文献等
  const refKeywords = ["参考文献", "Key Citations"];

  let result = content;

  for (const keyword of refKeywords) {
    // 查找关键词的最后出现位置(可能是最后一个标题)
    const keywordIndex = content.lastIndexOf(keyword);

    if (keywordIndex !== -1) {
      // 向前查找,找到该行的开始位置(可能包含 # 号)
      let lineStart = keywordIndex;
      while (lineStart > 0 && content[lineStart - 1] !== "\n") {
        lineStart--;
      }

      // 从该行开始位置删除到文档末尾
      result = content.substring(0, lineStart).trim();
      break;
    }
  }

  return result.trim();
};

// 处理引用标记点击事件 - 显示弹窗
const handleCitationClick = (
  refId: string | number,
  citationTag?: HTMLElement,
) => {
  // ⭐ 检查报告生成状态:如果报告正在生成中(isReportGenerating 为 true),不允许点击
  if (deerflowStore.processingStatus.isReportGenerating) {
    ElMessage.warning(
      t("chat.reportGeneratingCannotClick") ||
        "报告正在生成中,请稍候再点击引用标记",
    );
    return;
  }

  // 保持 refId 的原始类型(字符串或数字),不强制转换
  // 因为参考文献的 ID 可能是字符串或数字
  const refIdValue = refId;

  // 获取点击元素的引用标记元素
  let targetCitationTag: HTMLElement | null = null;
  if (citationTag) {
    targetCitationTag = citationTag;
  } else {
    // 如果没有传入 citationTag,尝试从 DOM 中查找
    targetCitationTag = document.querySelector(
      `.citation-tag[data-ref-id="${refIdValue}"], .citation-tag[data-work-id="${refIdValue}"]`,
    ) as HTMLElement;
  }

  // 从点击元素上获取 data-work-id 属性值
  if (targetCitationTag) {
    const workIdAttr = targetCitationTag.getAttribute("data-work-id");
    if (workIdAttr) {
      const workId = Number(workIdAttr);
      if (!isNaN(workId)) {
        // 调用深度检索接口获取参考文献详情
        getReferenceDetail(workId)
          .then((response) => {
            console.log(
              "【深度检索】参考文献详情接口返回数据:",
              response.data,
            );
            // 使用接口返回的数据显示弹窗
            if (targetCitationTag) {
              showCitationModal(targetCitationTag, response.data);
            }
          })
          .catch((error) => {
            console.error("【深度检索】获取参考文献详情失败:", error);
            ElMessage.error("获取参考文献详情失败,请稍后重试");
          });
      }
    }
  }
};

// HTML 转义函数
const escapeHtml = (text: string): string => {
  const div = document.createElement("div");
  div.textContent = text;
  return div.innerHTML;
};

// 显示引用弹窗
const showCitationModal = (
  target: HTMLElement,
  referenceDetail: ReferenceDetail,
) => {
  // 立即同步移除已存在的弹窗(不延迟)
  if (citationClickOutsideHandler) {
    document.removeEventListener("click", citationClickOutsideHandler);
    citationClickOutsideHandler = null;
  }
  // 移除旧的滚动事件监听
  if (citationScrollHandler) {
    window.removeEventListener("scroll", citationScrollHandler, true);
    if (messagesContainer.value) {
      messagesContainer.value.removeEventListener(
        "scroll",
        citationScrollHandler,
      );
    }
    citationScrollHandler = null;
  }
  if (citationModalElement) {
    citationModalElement.classList.remove("show");
    citationModalElement.remove();
    citationModalElement = null;
  }

  // 创建弹窗元素
  citationModalElement = document.createElement("div");
  citationModalElement.className = "citation-modal";

  let modalHTML = `
    <div class="citation-modal-header">
      <div class="citation-modal-title">引用文献</div>
      <button class="citation-modal-close" aria-label="关闭">
        <i class="fas fa-times"></i>
      </button>
    </div>
    <div class="citation-modal-body">
      <div class="citation-modal-content-text">
  `;

  // 从接口返回的数据中构建显示内容
  // 作者部分(只显示前3个作者)
  if (referenceDetail.authorsText) {
    // 解析作者列表(支持分号和逗号分隔)
    const authors = referenceDetail.authorsText
      .split(/[;,]/)
      .map((author) => author.trim())
      .filter((author) => author.length > 0);

    // 只取前3个作者
    const displayAuthors = authors.slice(0, 3);
    let authorsDisplayText = displayAuthors.join(", ");

    // 如果超过3个作者,添加 "et al."
    if (authors.length > 3) {
      authorsDisplayText += ", et al.";
    }

    modalHTML += `<span class="citation-author">${escapeHtml(authorsDisplayText)}</span> `;
  }

  // 标题部分(加粗)
  if (referenceDetail.title) {
    modalHTML += `<span class="title-bold">"${escapeHtml(referenceDetail.title)}"</span> `;
  }

  // 期刊部分
  const journalName = referenceDetail.venueName;
  if (journalName) {
    modalHTML += `<span class="journal-style">${escapeHtml(journalName)}.</span> `;
  }

  // 其他部分(卷号、期号、年份、页码、DOI等)
  const otherParts: string[] = [];

  if (referenceDetail.volume) {
    otherParts.push(`vol. ${referenceDetail.volume}`);
  }

  if (referenceDetail.issue) {
    otherParts.push(`no. ${referenceDetail.issue}`);
  }
  if (referenceDetail.publicationYear) {
    otherParts.push(String(referenceDetail.publicationYear));
  }

  if (referenceDetail.pages) {
    otherParts.push(`pp. ${referenceDetail.pages}`);
  }

  if (referenceDetail.doi) {
    otherParts.push(`DOI: ${referenceDetail.doi}`);
  }

  if (otherParts.length > 0) {
    modalHTML += `<span class="citation-other">${escapeHtml(otherParts.join(", "))}</span>`;
  }

  modalHTML += `
      </div>
    </div>
  `;

  // 查看原文按钮(优先使用 landingUrl,如果没有则使用 pdfUrl)
  const url = referenceDetail.landingUrl || referenceDetail.pdfUrl;
  if (url) {
    modalHTML += `
      <div class="citation-modal-footer">
        <a href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer" class="citation-modal-link">
          查看原文
          <i class="fas fa-external-link-alt"></i>
        </a>
      </div>
    `;
  }

  citationModalElement.innerHTML = modalHTML;

  // 绑定关闭按钮事件
  const closeBtn = citationModalElement.querySelector(".citation-modal-close");
  if (closeBtn) {
    closeBtn.addEventListener("click", hideCitationModal);
  }

  // 先添加到页面(但不可见),以便获取尺寸
  citationModalElement.style.visibility = "hidden";
  document.body.appendChild(citationModalElement);

  // 计算位置:显示在引用标记上方
  const rect = target.getBoundingClientRect();
  const modalRect = citationModalElement.getBoundingClientRect();

  // 计算水平位置:引用标记的中心对齐弹窗的中心
  let left = rect.left + rect.width / 2 - modalRect.width / 2;
  // 垂直位置:显示在引用标记上方,留出 10px 间距
  let top = rect.top - modalRect.height - 10;

  // 确保弹窗不超出视窗左边界
  if (left < 10) {
    left = 10;
  }
  // 确保弹窗不超出视窗右边界
  if (left + modalRect.width > window.innerWidth - 10) {
    left = window.innerWidth - modalRect.width - 10;
  }
  // 如果上方空间不足,显示在下方
  if (top < 10) {
    top = rect.bottom + 10;
  }
  // 确保弹窗不超出视窗下边界
  if (top + modalRect.height > window.innerHeight - 10) {
    top = window.innerHeight - modalRect.height - 10;
  }

  citationModalElement.style.left = `${left}px`;
  citationModalElement.style.top = `${top}px`;
  citationModalElement.style.visibility = "visible";

  // 添加点击外部关闭功能
  citationClickOutsideHandler = (event: MouseEvent) => {
    if (
      citationModalElement &&
      !citationModalElement.contains(event.target as Node) &&
      !target.contains(event.target as Node)
    ) {
      hideCitationModal();
    }
  };

  // 添加滚动事件监听:滚动时关闭弹窗
  // 先移除可能存在的旧监听器
  if (citationScrollHandler) {
    window.removeEventListener("scroll", citationScrollHandler, true);
    if (messagesContainer.value) {
      messagesContainer.value.removeEventListener(
        "scroll",
        citationScrollHandler,
      );
    }
  }

  citationScrollHandler = () => {
    hideCitationModal();
  };

  // 监听窗口滚动和消息容器滚动
  window.addEventListener("scroll", citationScrollHandler, true);
  if (messagesContainer.value) {
    messagesContainer.value.addEventListener("scroll", citationScrollHandler);
  }

  // 延迟添加事件监听,避免立即触发
  setTimeout(() => {
    document.addEventListener("click", citationClickOutsideHandler!);
  }, 0);

  // 添加动画效果
  setTimeout(() => {
    if (citationModalElement) {
      citationModalElement.classList.add("show");
    }
  }, 10);
};

// 隐藏引用弹窗
const hideCitationModal = () => {
  // 移除点击外部关闭的事件监听
  if (citationClickOutsideHandler) {
    document.removeEventListener("click", citationClickOutsideHandler);
    citationClickOutsideHandler = null;
  }

  // 移除滚动事件监听
  if (citationScrollHandler) {
    window.removeEventListener("scroll", citationScrollHandler, true);
    if (messagesContainer.value) {
      messagesContainer.value.removeEventListener(
        "scroll",
        citationScrollHandler,
      );
    }
    citationScrollHandler = null;
  }

  if (citationModalElement) {
    citationModalElement.classList.remove("show");
    setTimeout(() => {
      if (citationModalElement) {
        citationModalElement.remove();
        citationModalElement = null;
      }
    }, 200);
  }
};

// 格式化 Markdown
const formatMarkdown = (content: string) => {
  if (!content) return "";
  try {
    // 先将 markdown 转换为 HTML
    let htmlContent = markdownToHtml(content);

    // 修复被误识别为链接的数据源名称
    // 将包含数据源名称的链接恢复为普通文本
    const dataSourceNames = ["ClinicalTrials.gov", "clinicaltrials.gov"];

    dataSourceNames.forEach((name) => {
      // 匹配包含数据源名称的链接,支持以下情况:
      // 1. <a href="http://ClinicalTrials.gov">ClinicalTrials.gov</a>
      // 2. <a href="http://xn-ClinicalTrials-pw5y.gov">在ClinicalTrials.gov</a> (Punycode编码 + 链接文本包含其他文字)
      // 转义特殊字符,确保正则表达式正确
      const escapedName = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
      // 匹配链接标签,只要链接文本包含数据源名称就匹配(不依赖 href 内容,因为可能是 Punycode 编码)
      // 使用捕获组来分别捕获链接文本的前后部分和数据源名称
      const linkPattern = new RegExp(
        `<a[^>]*href=["'][^"']*["'][^>]*>(.*?)(${escapedName})(.*?)<\\/a>`,
        "gi",
      );
      // 替换时保留链接文本中的其他文字,只移除链接标签
      htmlContent = htmlContent.replace(
        linkPattern,
        (_match, beforeText, dataSourceName, afterText) => {
          // 保留链接文本的完整内容(包括前后的文字),只移除链接标签
          return (beforeText + dataSourceName + afterText).trim();
        },
      );
    });

    // 然后渲染引用标记
    htmlContent = renderCitations(htmlContent);
    return htmlContent;
  } catch (error) {
    return content.replace(/\n/g, "<br>");
  }
};

// 获取 Agent 显示名称
const getAgentDisplayName = (agentName: string) => {
  const displayNames: Record<string, string> = {
    coordinator: "coordinator",
    planner: "planner",
    researcher: "researcher",
    writer: "writer",
    editor: "editor",
  };
  return displayNames[agentName] || agentName;
};

// 检查消息是否已完成
const isMessageCompleted = (message: any) => {
  return message.status === "completed";
};

// 处理提交
const handleSubmit = async (content: string) => {
  if (!content || !content.trim() || isSubmitting.value) return;

  isSubmitting.value = true;
  // 截断 question,最多 200 个字符(用于发送消息)
  const questionForMessage =
    content.length > 200 ? content.substring(0, 200) : content;
  try {
    // 清空之前的消息,确保界面中只显示当前深度检索任务的内容
    deerflowStore.clearMessages();
    globalActiveTab.value = "plan";
    // 生成新的 thread_id
    const threadId = `thread_${Date.now()}`;
    deerflowStore.currentThreadId = threadId;
    const mode = resolveDeerFlowMode();
    // 1.先调用创建任务的接口,然会将接口返回的任务ID 给到 saveDeepSearch接口中的 scheduleId 参数
    // 同步透传 mode,确保创建任务接口 paramsJson 中包含检索模式
    const scheduleResult = await schedulesStore.createScheduleTask(mode);
    if (scheduleResult.success && scheduleResult.data) {
      const scheduleData = scheduleResult.data as { id: number };
      scheduleId.value = scheduleData.id;
      schedulesStore.scheduleId = scheduleData.id;
    } else {
      // 如果创建任务失败,则不继续后续的请求
      scheduleId.value = undefined;
      schedulesStore.scheduleId = undefined;
      ElMessage.error(
        scheduleResult.message || "创建定时任务失败,已取消后续操作",
      );
      return;
    }
    // 2.先保存深度检索提问,并保存返回的 ID,同时传递 thread_id
    try {
      const saveResult = await saveDeepSearch(
        questionForMessage.trim(),
        undefined,
        undefined,
        undefined,
        threadId,
        scheduleId.value,
      );
      // 保存返回的 ID 到 store
      if (saveResult && saveResult.id) {
        // 设置当前正在执行的任务 ID,获取最新的深度检索列表
        deerflowStore.setCurrentRunningTaskId(saveResult.id);
      } else {
        // 如果保存失败(没有返回 id),则不允许继续执行
        return;
      }
    } catch (error) {
      // 如果保存失败,则不允许继续执行后续的 sendMessage
      return;
    }
    // 3.调用 sendMessage 时传递生成的 threadId
    const shouldUseModePreset = !!mode;
    await deerflowStore.sendMessage({
      content: content.trim(),
      threadId,
      options: {
        auto_accepted_plan: true,
        ...(shouldUseModePreset
          ? {
              mode,
              max_plan_iterations: null,
              max_step_num: null,
              max_search_results: null,
              literature_filters: {
                ...buildLiteratureFilters(true),
                literatureFilters: [],
              },
            }
          : {
              max_plan_iterations: settingsStore.maxPlanIterations, // 最大计划迭代次数
              max_step_num: settingsStore.maxStepNum, // 最大步骤数
              max_search_results: settingsStore.maxSearchResults, // 最大搜索结果数
              literature_filters: buildLiteratureFilters(true), // 文献筛选配置(提交时使用 store 中的数据)
            }),
        use_surveyx: !!settingsStore.selectedKnowledgeBaseDirectory, // 顶层参数:是否启用知识库
        file_ids: settingsStore.selectedKnowledgeBaseDirectory
          ? settingsStore.knowledgeBaseFileIds.map((id) => "prod" + id)
          : [], // 顶层参数:知识库文件ID
        notify_type: "all", // 完成之后给用户发邮件和短信
      },
    });

    // 4. 显示深度检索启动弹窗
    showDeepSearchStartingModal.value = true;

    // 价格获取成功后,调用消费领医豆接口
    const { data } = await getServicePrice({ serviceTypeId: 2 });
    if (data !== undefined && data !== null) {
      try {
        await consumeBeans({
          serviceType: "深度检索",
          beanQuantity: data,
          agentTaskId: threadId,
        });
      } catch (consumeError) {
        console.error("消费领医豆失败:", consumeError);
      }
    }
    nextTick(() => scrollToBottom());
  } catch (error: any) {
    ElMessage.error(t("chat.sendMessageError") + ": " + error.message);
  } finally {
    isSubmitting.value = false;
  }
};

// 深度检索弹窗:知道了,去做其他事
const handleDoSomethingElse = () => {
  showDeepSearchStartingModal.value = false;
  // 跳转回首页或其他页面,这里假设用户想回到欢迎页/历史列表
  // 发出事件让父组件处理
  emit("back-to-welcome");
};

// 深度检索弹窗:留在页面等待
const handleWaitOnPage = () => {
  showDeepSearchStartingModal.value = false;
  // 留在当前页面,不做额外操作
};

// 获取 planner 的计划数据
const getPlanData = (message: any, agentName: string) => {
  if (agentName !== "planner") {
    return { title: "", thought: "", steps: [] };
  }

  // ⭐ 优先使用 message.planData(从历史记录或 plan 事件中获取)
  if (message.planData && typeof message.planData === "object") {
    return {
      title: t("chat.researchPlan"),
      thought: message.planData.thought || "",
      steps: message.planData.steps || [],
      ...message.planData,
    };
  }

  const content =
    message.agentContents?.[agentName]?.content ||
    (message.agent === agentName ? message.content : "") ||
    "";

  // 检查内容是否为空或只有空白字符
  if (!content.trim()) {
    return {
      title: t("chat.deepResearchPlan"),
      thought: "",
      steps: [],
    };
  }

  // 检查是否是 JSON 格式
  if (!content.trim().startsWith("{")) {
    // 如果不是 JSON 格式,可能是纯文本内容
    return {
      title: t("chat.planContent"),
      thought: content,
      steps: [],
    };
  }

  // 检查 JSON 是否完整(简单的括号匹配)
  if (!isCompleteJSON(content)) {
    // JSON 还未完成,返回带有默认值的对象
    return {
      title: t("chat.generatingResearchPlan"),
      thought: "",
      steps: [],
    };
  }

  try {
    const parsed = JSON.parse(content);
    // ⭐ 将解析成功的数据缓存到 message.planData,避免重复解析
    if (!message.planData) {
      message.planData = parsed;
    }
    // 确保解析后的对象有必需的字段
    return {
      title: t("chat.researchPlan"),
      thought: parsed.thought || "",
      steps: parsed.steps || [],
      ...parsed,
    };
  } catch (error) {
    // JSON 格式错误,静默处理
    console.debug("JSON 解析失败,可能是流式传输中:", error);
    return {
      title: t("chat.planParsing"),
      thought: content,
      steps: [],
    };
  }
};

// 检查 JSON 是否完整
const isCompleteJSON = (str: string) => {
  if (!str || typeof str !== "string") return false;

  const trimmed = str.trim();
  if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
    return false;
  }

  // 简单的括号匹配检查
  let braceCount = 0;
  let inString = false;
  let escaped = false;

  for (let i = 0; i < trimmed.length; i++) {
    const char = trimmed[i];

    if (escaped) {
      escaped = false;
      continue;
    }

    if (char === "\\") {
      escaped = true;
      continue;
    }

    if (char === '"') {
      inString = !inString;
      continue;
    }

    if (!inString) {
      if (char === "{") {
        braceCount++;
      } else if (char === "}") {
        braceCount--;
      }
    }
  }

  return braceCount === 0 && !inString;
};

// 是否应该显示计划
const shouldShowPlan = (message: any, agentName: string) => {
  if (agentName !== "planner") return false;

  const content =
    message.agentContents?.[agentName]?.content ||
    (message.agent === agentName ? message.content : "") ||
    "";

  const hasContent = content && content.trim() !== "";
  if (!hasContent) {
    return false;
  }

  // 额外检查:确保计划数据有实际内容
  const planData = getPlanData(message, agentName);

  // 如果有思考内容或者有步骤,则显示
  const hasThought = planData.thought && planData.thought.trim() !== "";
  const hasSteps = planData.steps && planData.steps.length > 0;

  return hasThought || hasSteps;
};

// 如果已经有 researcher 的输出内容,就认为"推理过程的 research 已经开始/已有结果"
const hasResearchContent = (message: any) => {
  const researcher = message?.agentContents?.researcher;
  const content = researcher?.content || "";
  const reasoning = researcher?.reasoningContent || "";
  return (
    (typeof content === "string" && content.trim() !== "") ||
    (typeof reasoning === "string" && reasoning.trim() !== "")
  );
};

// 检查是否有推理内容(用于判断是否显示边框)
const hasReasoningContent = (message: any) => {
  const orderedContents = getOrderedAgentContents(message);
  if (orderedContents.length === 0) return false;

  // 检查是否有任何 agent 有内容或推理内容
  return orderedContents.some((agentItem) => {
    const content = agentItem.content?.content || "";
    const reasoningContent = agentItem.content?.reasoningContent || "";
    return (
      (typeof content === "string" && content.trim() !== "") ||
      (typeof reasoningContent === "string" && reasoningContent.trim() !== "")
    );
  });
};

// 后端 status.interrupted === false 表示用户已“继续检索/接受计划”,不应再显示确认按钮
const isThreadStillInterrupted = (message: any) => {
  const threadId = message?.threadId || deerflowStore.currentThreadId;
  if (!threadId) return true; // 未知 threadId 时按旧逻辑:显示按钮
  const interrupted = deerflowStore.getThreadInterrupted(threadId);
  // 未拿到状态时按兼容逻辑:仍显示按钮
  if (typeof interrupted !== "boolean") return true;
  return interrupted;
};

// 判断是否应该显示 planner 操作按钮
// 简化逻辑:只要有 planner 内容且有计划文本,并且状态是 planner_waiting_confirmation,就显示按钮
const shouldShowPlannerActions = (message: any) => {
  const plannerContent = message.agentContents?.planner;
  const isProcessed = processedPlannerMessages.value.has(message.id);

  // 1. 必须有 planner 内容
  if (!plannerContent || !plannerContent.content) {
    return false;
  }

  // 2. 不能已经处理过
  if (isProcessed) {
    return false;
  }

  // 3. 关键判断:检查消息状态或 plannerFinished 标记
  // 只要满足以下任一条件就显示按钮:
  // - message.status === "interrupt" (中断状态,需要用户确认)
  // - message.status === "planner_waiting_confirmation"
  // - message.plannerFinished === true
  // - planner 状态是 completed 且不在流式传输
  const shouldShow =
    message.status === "interrupt" ||
    message.status === "planner_waiting_confirmation" ||
    message.plannerFinished === true ||
    (plannerContent.status === "completed" && !plannerContent.isStreaming);

  // ⭐ 重要修改:在历史模式下,只有当消息状态是 interrupt 时才显示按钮
  // 这样可以支持重新执行未完成的任务,同时不影响查看已完成任务的体验
  if (
    (props.isHistoryMode &&
      message.status === "planner_waiting_confirmation") ||
    (props.isHistoryMode && message.plannerFinished === true)
  ) {
    return true;
  }

  return shouldShow;
};

// 处理计划操作(edit_plan 或 accepted)
const handlePlanAction = async (
  message: any,
  action: "edit_plan" | "accepted" | "continue_research",
) => {
  try {
    planActionLoading.value = true;
    if (action === "edit_plan") {
      // 进入编辑模式
      editingPlanMessageId.value = message.id;

      // 获取当前的计划数据并初始化编辑数据
      const currentPlanData = getPlanData(message, "planner");
      editedPlanData.value = JSON.parse(JSON.stringify(currentPlanData)); // 深拷贝

      planActionLoading.value = false;
      return;
    } else if (action === "continue_research") {
      // 继续检索 - 发送编辑后的计划
      if (!editedPlanData.value) {
        ElMessage.error("没有可提交的编辑内容");
        return;
      }

      // 标记该消息已处理
      processedPlannerMessages.value.add(message.id);

      // 查找当前助手消息之前最近的一条用户消息
      const currentMessageIndex = deerflowStore.messages.findIndex(
        (msg: any) => msg.id === message.id,
      );

      let originalUserMessage: any = null;
      for (let i = currentMessageIndex - 1; i >= 0; i--) {
        const msg = deerflowStore.messages[i];
        if (msg && msg.role === "user") {
          originalUserMessage = msg;
          break;
        }
      }

      if (!originalUserMessage) {
        ElMessage.error("无法找到原始用户消息");
        return;
      }

      // ⭐ 关键修复:用编辑后的内容更新 planner,并标记为"已锁定"
      // 这样用户编辑的内容会被保留,不会被后端返回的内容覆盖
      if (message.agentContents && message.agentContents.planner) {
        // 将编辑后的计划数据保存为 JSON 字符串
        const editedPlanJson = JSON.stringify(editedPlanData.value);
        message.agentContents.planner.content = editedPlanJson;
        message.agentContents.planner.status = "completed";
        message.agentContents.planner.isStreaming = false;

        // ⭐ 添加特殊标记,表示这是用户编辑后的内容,不应该被覆盖
        message.agentContents.planner.isUserEdited = true;
        message.planData = JSON.parse(JSON.stringify(editedPlanData.value));
      }

      // 重置消息状态,准备接收后续 agent(researcher、coder 等)的数据
      message.status = "typing";
      message.isStreaming = true;
      message.plannerFinished = true; // 标记 planner 已完成

      // ⭐ 使用 store 中保存的真实 thread_id
      const realThreadId = deerflowStore.currentThreadId || message.threadId;

      // 传递原始用户消息内容和当前会话的 threadId
      try {
        const content = originalUserMessage.content.trim();
        let taskID;
        // 如果是任务列表点击展开的则不传 id
        if (props.isHistoryMode) {
          taskID = undefined;
        } else {
          taskID = deerflowStore.currentRunningTaskId || undefined;
        }
        const result = await saveDeepSearch(
          content,
          undefined,
          taskID,
          undefined,
          realThreadId,
          schedulesStore.scheduleId,
        );

        // 更新深度检索记录 ID(如果返回了新的 ID)
        if (result && result.id) {
          // 设置当前正在执行的任务 ID
          deerflowStore.setCurrentRunningTaskId(result.id);
        }
      } catch (error) {
        console.error("保存深度检索记录失败:", error);
        // 即使保存失败也继续执行
      }

      // ⭐ 构造人类可读的修改说明文本(在清除编辑数据之前)
      // 格式:修改执行步骤steps为:[步骤1内容][步骤2内容]...
      const stepsDescription = editedPlanData.value.steps
        .map((step: any, index: number) => {
          return `步骤 ${index + 1}:\n标题:${step.title}\n描述:${step.description}`;
        })
        .join("\n\n");
      const modificationMessage = `修改执行步骤steps为:\n\n${stepsDescription}`;

      // 清除编辑状态
      editingPlanMessageId.value = null;
      editedPlanData.value = null;
      globalActiveTab.value = "reasoning";

      // 调用 store 的 startStreaming 继续流程
      // 后端会重新生成计划,但应该自动接受并继续执行,不再触发 interrupt
      await deerflowStore.startStreaming({
        messages: [
          {
            role: "user",
            content: modificationMessage, // 传递人类可读的修改说明,而不是JSON
          },
        ],
        threadId: realThreadId,
        interrupt_feedback: "edit_plan",
        auto_accepted_plan: true, // 自动接受修订后的计划,继续执行
        max_plan_iterations: settingsStore.maxPlanIterations, // 最大计划迭代次数
        max_step_num: settingsStore.maxStepNum, // 最大步骤数
        max_search_results: settingsStore.maxSearchResults, // 最大搜索结果数
        literature_filters: buildLiteratureFilters(true), // 文献筛选配置(提交时使用 store 中的数据)
        use_surveyx: !!settingsStore.selectedKnowledgeBaseDirectory,
        file_ids: settingsStore.selectedKnowledgeBaseDirectory
          ? settingsStore.knowledgeBaseFileIds.map((id) => "prod" + id)
          : [],
      });
    } else if (action === "accepted") {
      // 查找当前助手消息之前最近的一条用户消息
      const currentMessageIndex = deerflowStore.messages.findIndex(
        (msg: any) => msg.id === message.id,
      );

      // 从当前消息向前查找最近的用户消息
      let originalUserMessage: any = null;
      for (let i = currentMessageIndex - 1; i >= 0; i--) {
        const msg = deerflowStore.messages[i];
        if (msg && msg.role === "user") {
          originalUserMessage = msg;
          break;
        }
      }

      if (originalUserMessage) {
        // ⭐ 关键修复:保护 planner 内容,防止被后端返回的内容覆盖
        // 在调用 startStreaming 之前,标记 planner 内容为"已锁定"
        if (message.agentContents && message.agentContents.planner) {
          // 确保 planner 内容已保存
          const plannerContent = message.agentContents.planner.content;
          if (plannerContent) {
            // 标记为已完成且非流式传输
            message.agentContents.planner.status = "completed";
            message.agentContents.planner.isStreaming = false;

            // ⭐ 添加特殊标记,表示这是用户确认的计划,不应该被覆盖
            message.agentContents.planner.isUserEdited = true;
          }
        }

        // ⭐ 使用 store 中保存的真实 thread_id
        const realThreadId = deerflowStore.currentThreadId || message.threadId;
        // 传递原始用户消息内容和当前会话的 threadId
        try {
          const content = originalUserMessage.content.trim();
          let taskID;
          // 如果是任务列表点击展开的则不传 id
          if (props.isHistoryMode) {
            taskID = undefined;
          } else {
            taskID = deerflowStore.currentRunningTaskId || undefined;
          }
          const result = await saveDeepSearch(
            content,
            undefined,
            taskID,
            undefined,
            realThreadId,
            schedulesStore.scheduleId,
          );

          // 更新深度检索记录 ID(如果返回了新的 ID)
          if (result && result.id) {
            // 设置当前正在执行的任务 ID
            deerflowStore.setCurrentRunningTaskId(result.id);
          }
        } catch (error) {
          console.error("保存深度检索记录失败:", error);
          // 即使保存失败也继续执行
        }

        // 标记该消息已处理
        processedPlannerMessages.value.add(message.id);

        // 重置消息状态,准备接收后续 agent(researcher、coder 等)的数据
        message.status = "typing";
        message.isStreaming = true;
        message.plannerFinished = true; // 标记 planner 已完成
        globalActiveTab.value = "reasoning";

        // 调用 store 的 startStreaming 直接继续流程
        // ⭐ startStreaming 会自动将 threadId 转换为 thread_id
        await deerflowStore.startStreaming({
          messages: [
            {
              role: "user",
              content: originalUserMessage.content,
            },
          ],
          threadId: realThreadId, // 使用驼峰命名,store会自动转换
          interrupt_feedback: "accepted",
          auto_accepted_plan: true,
          max_plan_iterations: settingsStore.maxPlanIterations, // 最大计划迭代次数
          max_step_num: settingsStore.maxStepNum, // 最大步骤数
          max_search_results: settingsStore.maxSearchResults, // 最大搜索结果数
          literature_filters: buildLiteratureFilters(true), // 文献筛选配置(提交时使用 store 中的数据)
          use_surveyx: !!settingsStore.selectedKnowledgeBaseDirectory,
          file_ids: settingsStore.selectedKnowledgeBaseDirectory
            ? settingsStore.knowledgeBaseFileIds.map((id) => "prod" + id)
            : [],
        });
      } else {
        console.error("❌ 无法找到原始用户消息", {
          currentMessageIndex,
          messagesBefore: deerflowStore.messages.slice(0, currentMessageIndex),
        });
        ElMessage.error("无法找到原始用户消息");
      }
    }
  } catch (error: any) {
    console.error("处理计划操作失败:", error);
    ElMessage.error(t("chat.planActionError") + ": " + error.message);
    // 如果失败,从已处理列表中移除
    processedPlannerMessages.value.delete(message.id);
  } finally {
    planActionLoading.value = false;
  }
};

// 处理复制消息
const handleCopy = async (content: string) => {
  try {
    if (!content) {
      ElMessage.warning(t("chat.noContentToCopy"));
      return;
    }
    await navigator.clipboard.writeText(content);
    ElMessage.success(t("chat.contentCopied"));
  } catch (error) {
    console.error("复制失败:", error);
    ElMessage.error(t("chat.copyFailed"));
  }
};

const handleCopyMessage = async (message: any) => {
  // 获取 reporter 的内容(包含参考文献)
  const reporterContent =
    message.agentContents?.reporter?.content ||
    message.agentContents?.reporter?.reasoningContent ||
    "";
  await handleCopy(reporterContent);
};

// 从 Markdown 内容中提取第一个一级标题
const extractTitleFromMarkdown = (content: string): string => {
  if (!content) return "";

  // 尝试提取 Markdown 一级标题 (# 标题)
  const h1Match = content.match(/^#\s+(.+)$/m);
  if (h1Match && h1Match[1]) {
    return h1Match[1].trim();
  }

  // 如果没有标题标记,尝试获取第一行非空文本(最多100个字符)
  const lines = content.split("\n").filter((line) => line.trim());
  if (lines.length > 0 && lines[0]) {
    const firstLine = lines[0].trim();
    return firstLine.length > 100
      ? firstLine.substring(0, 100) + "..."
      : firstLine;
  }

  return t("chat.deepSearchResult") || "深度检索结果";
};

// 处理保存并编辑
const handleSaveAndEdit = async (message: any) => {
  try {
    // 检查是否有 reporter 内容
    if (!message.agentContents?.reporter?.content) {
      ElMessage.warning(t("chat.noContentToSave") || "暂无内容可保存");
      return;
    }
    // 检查消息状态
    if (message.status === "thinking") {
      ElMessage.warning(t("chat.aiThinking") || "AI正在思考中,请等待完成");
      return;
    }
    if (message.status === "typing") {
      ElMessage.warning(
        t("chat.generatingAnswer") || "内容正在生成中,请等待完成",
      );
      return;
    }
    // 只有当状态为 completed 或者没有状态字段时才允许保存
    if (message.status && message.status !== "completed") {
      ElMessage.warning(t("chat.answerNotCompleted") || "内容尚未完成");
      return;
    }
    try {
      // 获取完整的 reporter 内容(包含参考文献)
      const reporterContent = message.agentContents.reporter.content;
      // 提取标题(一级标题)并截取前20个字符
      let title = extractTitleFromMarkdown(reporterContent);
      title = title.replace(/\n/g, " ").substring(0, 20).trim();
      if (!title) title = "未命名深度检索";

      // 2. 检查并创建“草稿”目录
      let draftFolderId: number | undefined;
      const rootFilesRes = await getFiles();
      if (
        rootFilesRes.status === 200 &&
        rootFilesRes.data
      ) {
        const items = Array.isArray(rootFilesRes.data) ? rootFilesRes.data : (rootFilesRes.data.items || []);
        const draftFolder = items.find(
          (item: any) =>
            (item.type === "folder" || item.isFolder) && item.name === "草稿",
        );
        if (draftFolder) {
          draftFolderId = draftFolder.id;
        }
      }

      if (!draftFolderId) {
        const createFolderRes = await createFolder({ name: "草稿" });
        if (createFolderRes.status === 200 && createFolderRes.data) {
          draftFolderId = createFolderRes.data.id;
        }
      }

      // 3. 调用 API 创建草稿
      const response = await apiCreateDraftFromDeepSearch({
        title,
        content: reporterContent,
      });

      if (response.status === 200 && response.data) {
        const draftInfo = response.data;
        const draftContent = draftInfo.content || "";

        // 4. 将草稿保存到“草稿”目录
        const saveRes = await apiSaveDraftToKnowledge(draftInfo.id, {
          parentId: draftFolderId,
          fileName: title + ".md",
        });

        if (saveRes.status === 200 && saveRes.data) {
          const fileInfo = saveRes.data;

          // 5. 添加到对话框引用 (DeerFlow 目前可能不直接支持在输入框显示文件引用)
          // TODO: 如果输入组件支持,可以在这里添加

          // 6. 跳转到工作台编辑器
          await openInWorkspace({
            id: fileInfo.id,
            title: fileInfo.name || fileInfo.fileName,
            isDraft: false,
            preloadContent: draftContent, // 传递预抓取的内容
          });

          // 7. 触发全局事件和状态信号,刷新文件列表
          window.dispatchEvent(
            new CustomEvent("refresh-file-hierarchy", {
              detail: { folderId: draftFolderId },
            }),
          );
          const appStore = useAppStore();
          appStore.triggerRefreshFileHierarchy(draftFolderId);

          ElMessage.success("已保存到草稿目录");
        } else {
          throw new Error("保存到目录失败");
        }
      } else {
        throw new Error((response as any)?.data?.message || "创建草稿失败");
      }
    } catch (apiError: any) {
      console.error("API调用失败:", apiError);
      if (!apiError.response && apiError.request) {
        ElMessage.error("网络请求失败,请检查网络连接");
      } else if (!apiError.response && !apiError.request) {
        ElMessage.error(apiError.message || "保存失败");
      }
    }
  } catch (error: any) {
    console.error("保存并编辑失败:", error);
    ElMessage.error(t("chat.operationFailed") || "操作失败");
  }
};

// 在工作台编辑器中打开文件
const openInWorkspace = async (fileInfo: any) => {
  // 显示加载状态
  const loading = ElLoading.service({
    lock: true,
    text: t("chat.preparingDocument") || "正在准备文档...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    // 先下载文件内容,确保文件可以正常访问
    let fileContent = fileInfo.preloadContent || "";
    try {
      if (!fileContent) {
        // 统一使用常规文件 API
        const contentResponse = await getFileContent(fileInfo.id);
        fileContent = contentResponse.data;
      }
    } catch (downloadError) {
      console.error("下载文件内容失败:", downloadError);
      // 如果下载失败,仍然尝试跳转,让工作台组件自己处理
      ElMessage.warning(t("chat.filePreloadFailed") || "文件预加载失败");
    }

    // 构建跳转参数,包含文件内容
    const params: any = {
      fileId: fileInfo.id,
      fileName: fileInfo.title || fileInfo.name,
      fileType: "md", // 默认为 markdown
      isChatAnswer: fileInfo.isDraft === false ? "false" : "true",
    };

    // 如果成功获取到内容,也传递过去(可选)
    if (fileContent) {
      params.preloadContent = encodeURIComponent(fileContent);
    }

    // 跳转到工作台页面,并传递文件参数
    await performRouterNavigation(params);
  } catch (error) {
    console.error("打开工作台编辑器失败:", error);
    ElMessage.error(t("chat.openEditorFailed") || "打开编辑器失败");
  } finally {
    loading.close();
  }
};

// 执行路由跳转的辅助方法
const performRouterNavigation = async (params: any) => {
  try {
    // 首先尝试使用路由名称跳转
    try {
      await router.push({
        name: "Workspace",
        query: params,
      });
      return;
    } catch (nameError) {
      console.warn("路由名称跳转失败:", nameError);
    }

    // 如果路由名称失败,尝试使用路径跳转
    try {
      await router.push({
        path: "/app/workspace",
        query: params,
      });
      return;
    } catch (pathError) {
      console.warn("路径跳转失败:", pathError);
    }

    // 尝试其他可能的路径
    const possiblePaths = ["/workspace", "/Workspace", "/app/Workspace"];

    for (const path of possiblePaths) {
      try {
        await router.push({
          path,
          query: params,
        });
        return;
      } catch (error) {
        console.warn(`路径 ${path} 跳转失败:`, error);
      }
    }

    // 所有跳转方式都失败
    throw new Error("所有路由跳转方式都失败");
  } catch (error) {
    console.error("路由跳转失败:", error);
    ElMessage.error(
      t("chat.routeNavigationFailed") || "页面跳转失败,请稍后重试",
    );
    throw error;
  }
};

// 获取有序的Agent内容(用于时间线显示)
const getOrderedAgentContents = (message: any) => {
  if (!message.agentContents) return [];

  const agentOrder = ["researcher", "coder"];
  const orderedContents: Array<{ name: string; content: any }> = [];

  agentOrder.forEach((agentName) => {
    if (message.agentContents[agentName]) {
      orderedContents.push({
        name: agentName,
        content: message.agentContents[agentName],
      });
    }
  });

  return orderedContents;
};

// 滚动到底部
const scrollToBottom = (smooth = true) => {
  nextTick(() => {
    const container = messagesContainer.value;
    if (container) {
      container.scrollTo({
        top: container.scrollHeight,
        behavior: smooth ? "smooth" : "auto",
      });
    }
  });
};

// 检查是否在底部
const isAtBottom = () => {
  const container = messagesContainer.value;
  if (!container) return false;

  const threshold = 50; // 50px 的容差
  return (
    container.scrollTop + container.clientHeight >=
    container.scrollHeight - threshold
  );
};

// 处理滚动事件
const handleScroll = () => {
  if (!messagesContainer.value) return;

  const atBottom = isAtBottom();

  if (atBottom) {
    // 用户滚到底部,恢复自动滚动
    shouldAutoScroll.value = true;
    isUserScrolling.value = false;

    // 清除之前的定时器
    if (scrollTimeout.value) {
      clearTimeout(scrollTimeout.value);
    }
  } else {
    // 用户不在底部,暂停自动滚动
    shouldAutoScroll.value = false;
    isUserScrolling.value = true;

    // 设置定时器,如果用户停止滚动一段时间后恢复自动滚动
    if (scrollTimeout.value) {
      clearTimeout(scrollTimeout.value);
    }

    scrollTimeout.value = setTimeout(() => {
      if (isAtBottom()) {
        shouldAutoScroll.value = true;
        isUserScrolling.value = false;
      }
    }, 2000); // 2秒后检查是否在底部
  }
};

// 监听消息变化,自动滚动
watch(
  () => deerflowStore.messages,
  () => {
    // 只有在应该自动滚动时才滚动到底部
    if (shouldAutoScroll.value) {
      nextTick(() => scrollToBottom());
    }
  },
  { deep: true },
);

// 监听 reporter 完成,自动解析参考文献,并清除虚拟任务
watch(
  () => deerflowStore.messages,
  (newMessages) => {
    // 从最后一条消息开始查找
    for (let i = newMessages.length - 1; i >= 0; i--) {
      const message = newMessages[i];

      if (
        message &&
        message.role === "assistant" &&
        message.agentContents?.reporter
      ) {
        const reporter = message.agentContents.reporter;

        // 检查 reporter 是否已完成
        const isReporterCompleted =
          reporter.status === "completed" ||
          (message.status === "completed" && reporter.content);

        if (isReporterCompleted && reporter.content) {
          // 找到后退出循环
          break;
        }
      }
    }
  },
  { deep: true },
);

// 监听报告生成完成,清除当前运行任务ID
watch(
  () => deerflowStore.processingStatus.isReportGenerating,
  (isGenerating, wasGenerating) => {
    // 当报告生成状态从 true 变为 false,说明报告生成完成
    if (wasGenerating && !isGenerating) {
      // 检查是否有 reporter 内容
      const messages = deerflowStore.messages;
      let hasReporter = false;

      for (let i = messages.length - 1; i >= 0; i--) {
        const message = messages[i];
        if (
          message &&
          message.role === "assistant" &&
          message.agentContents?.reporter?.content
        ) {
          hasReporter = true;
          break;
        }
      }

      // 如果有 reporter 内容且报告生成已完成,清除当前运行任务ID
      if (hasReporter) {
        deerflowStore.setCurrentRunningTaskId(null);
      }
    }
  },
);

// 重新绑定引用标记点击事件监听器
const rebindCitationClickHandler = async () => {
  // 先移除旧的事件监听器
  if (messagesContainer.value && citationClickHandler) {
    messagesContainer.value.removeEventListener(
      "click",
      citationClickHandler,
      true,
    );
  }
  if (citationClickHandler) {
    document.removeEventListener("click", citationClickHandler, true);
  }
  citationHandlerBound = false;

  // 等待 DOM 更新
  await nextTick();

  // 重新绑定事件监听器
  if (messagesContainer.value && citationClickHandler) {
    messagesContainer.value.addEventListener(
      "click",
      citationClickHandler,
      true,
    );
    citationHandlerBound = true;
  } else if (citationClickHandler) {
    // 如果 messagesContainer 不存在,使用 document 级别的事件委托
    document.addEventListener("click", citationClickHandler, true);
    citationHandlerBound = true;
  }
};

// 监听历史任务ID变化,当切换历史任务时重置Tab并重新绑定事件监听器
watch(
  () => props.historyTaskId,
  async (newTaskId, oldTaskId) => {
    // 如果任务ID不为null且发生了变化,说明切换到了新的历史任务
    if (newTaskId !== null && newTaskId !== oldTaskId) {
      // ⭐ 关闭已打开的参考文献弹窗
      hideCitationModal();
      // ⭐ 修改默认tab
      globalActiveTab.value = "plan";
      // ⭐ 重新绑定引用标记点击事件监听器
      await rebindCitationClickHandler();
    }
  },
  { immediate: true }, // 立即执行一次,处理初始加载历史任务的情况
);

// 监听 messagesContainer 的变化,当它准备好时重新绑定事件监听器
watch(
  () => messagesContainer.value,
  async (newContainer, oldContainer) => {
    // 当容器从 null 变为有值时,重新绑定事件监听器
    if (newContainer && !oldContainer && citationClickHandler) {
      // 先移除 document 上的监听器(如果存在)
      if (citationClickHandler) {
        document.removeEventListener("click", citationClickHandler, true);
      }
      // 绑定到新的容器
      await nextTick();
      if (messagesContainer.value && citationClickHandler) {
        messagesContainer.value.addEventListener(
          "click",
          citationClickHandler,
          true,
        );
        citationHandlerBound = true;
      }
    }
  },
);

onMounted(async () => {
  // 使用事件委托监听引用标记点击事件
  citationClickHandler = (event: MouseEvent) => {
    // 获取点击的目标元素
    let target = event.target as HTMLElement;

    // 如果目标是文本节点,获取其父元素
    if (target.nodeType === Node.TEXT_NODE) {
      target = target.parentElement as HTMLElement;
    }

    // 检查点击的元素是否是引用标记或其子元素
    const citationTag = target?.closest?.(".citation-tag") as HTMLElement;

    if (citationTag) {
      event.preventDefault();
      event.stopPropagation();

      const refId = citationTag.getAttribute("data-ref-id");
      if (refId) {
        handleCitationClick(refId, citationTag);
        return;
      }

      // 如果 data-ref-id 不存在,尝试使用 data-work-id 作为后备
      const workId = citationTag.getAttribute("data-work-id");
      if (workId) {
        handleCitationClick(workId, citationTag);
        return;
      }

      console.warn("引用标记缺少 data-ref-id 和 data-work-id 属性", {
        citationTag,
        attributes: Array.from(citationTag.attributes).map((attr) => ({
          name: attr.name,
          value: attr.value,
        })),
      });
    }
  };

  // 使用 nextTick 确保 DOM 已经渲染完成后再绑定事件监听器
  await nextTick();

  // 绑定事件监听器 - 优先使用 messagesContainer,如果不存在则使用 document
  const bindEventListener = () => {
    if (messagesContainer.value) {
      if (citationClickHandler) {
        messagesContainer.value.addEventListener(
          "click",
          citationClickHandler,
          true,
        ); // 使用捕获阶段
      }
    } else {
      // 如果 messagesContainer 不存在,使用 document 级别的事件委托
      if (citationClickHandler) {
        document.addEventListener("click", citationClickHandler, true);
      }
    }
  };

  bindEventListener();
  // 标记事件监听器已绑定
  if (messagesContainer.value) {
    citationHandlerBound = true;
  } else {
    citationHandlerBound = true; // document 级别的事件委托也算已绑定
  }

  // 如果 messagesContainer 还未准备好,延迟重试
  if (!messagesContainer.value) {
    setTimeout(() => {
      if (messagesContainer.value) {
        // 移除 document 上的监听器(如果已绑定)
        if (citationClickHandler) {
          document.removeEventListener("click", citationClickHandler, true);
          messagesContainer.value.addEventListener(
            "click",
            citationClickHandler,
            true,
          );
          citationHandlerBound = true;
        }
      }
    }, 200);
  }

  // 初始化 DeerFlow
  try {
    await deerflowStore.initDeerFlow();
    // 如果有初始消息,等待初始化完成后再发送
    if (props.initialMessage && !props.isHistoryMode) {
      setTimeout(() => {
        handleSubmit(props.initialMessage!);
      }, 500);
    }
  } catch (error: any) {
    ElMessage.error({
      message: `${t("chat.deerflowConnectionFailed")}: ${error.message || error}。${t("chat.deerflowServiceUrl")}`,
      duration: 5000,
    });
  }
});

// 组件更新后重新绑定事件监听器(处理快速切换组件的情况)
onUpdated(async () => {
  // 如果 messagesContainer 已准备好但事件监听器可能未绑定,重新绑定
  // 只在 messagesContainer 存在但可能未绑定时才重新绑定
  if (
    messagesContainer.value &&
    citationClickHandler &&
    !citationHandlerBound
  ) {
    // 由于我们使用的是 addEventListener,无法直接检查是否已绑定
    // 采用重新绑定的方式:先移除可能存在的监听器,然后重新绑定
    // 移除旧监听器(如果存在)
    messagesContainer.value.removeEventListener(
      "click",
      citationClickHandler,
      true,
    );
    // 移除 document 上的监听器(如果存在)
    document.removeEventListener("click", citationClickHandler, true);
    // 重新绑定到 messagesContainer
    await nextTick();
    if (messagesContainer.value && citationClickHandler) {
      messagesContainer.value.addEventListener(
        "click",
        citationClickHandler,
        true,
      );
      citationHandlerBound = true;
    }
  }
});

// 组件卸载时清理定时器和事件监听
onUnmounted(() => {
  if (scrollTimeout.value) {
    clearTimeout(scrollTimeout.value);
  }

  // 移除事件监听
  if (messagesContainer.value) {
    if (citationClickHandler) {
      messagesContainer.value.removeEventListener(
        "click",
        citationClickHandler,
        true,
      );
    }
  }
  // 同时移除 document 上的监听器(如果存在)
  if (citationClickHandler) {
    document.removeEventListener("click", citationClickHandler, true);
  }
  citationHandlerBound = false;

  // 清理弹窗
  hideCitationModal();

  // 关闭正在进行的流式请求
  deerflowStore.stopStreaming();
});
</script>

<!-- 全局样式:确保 v-html 渲染的 markdown 内容有正确样式 -->
<style lang="scss">
/* DeerFlow 聊天组件的全局 Markdown 样式 */
.deerflow-chat {
  /* ========== 段落样式 ========== */
  .content p,
  .reasoning-content p {
    margin: 8px 0 !important;
    line-height: 1.6 !important;
    white-space: normal !important;
    word-break: break-word !important;
    overflow-wrap: anywhere !important;
  }

  /* ========== 列表样式 ========== */
  .content ul,
  .content ol,
  .reasoning-content ul,
  .reasoning-content ol {
    margin: 8px 0 !important;
    padding-left: 20px !important;
    white-space: normal !important;
  }

  .content li,
  .reasoning-content li {
    margin: 4px 0 !important;
    line-height: 2 !important;
    white-space: normal !important;
    display: list-item !important;
    list-style: disc !important;
    word-break: break-word !important;
    overflow-wrap: anywhere !important;
  }

  /* 有序列表 */
  .content ol li,
  .reasoning-content ol li {
    list-style: decimal !important;
  }

  /* ========== 链接样式 ========== */
  .content a,
  .reasoning-content a {
    color: var(--color-primary, #409eff) !important;
    text-decoration: none !important;
    cursor: pointer !important;

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

  /* ========== 强调样式 ========== */
  .content strong,
  .reasoning-content strong {
    font-weight: 600 !important;
    color: var(--color-text, #eee) !important;
  }

  .content em,
  .reasoning-content em {
    font-style: italic !important;
  }

  /* ========== 引用块样式 ========== */
  .content blockquote,
  .reasoning-content blockquote {
    margin: 16px 0 !important;
    padding: 8px 16px !important;
    border-left: 4px solid var(--color-primary, #409eff) !important;
    background: rgba(40, 113, 246, 0.05) !important;
    font-style: italic !important;
    color: var(--color-text-secondary, #999) !important;
  }

  /* ========== 行内代码样式 ========== */
  code:not(pre code) {
    background: rgba(40, 113, 246, 0.1) !important;
    padding: 2px 6px !important;
    border-radius: 4px !important;
    font-family: "Consolas", "Monaco", "Courier New", monospace !important;
    font-size: 1em !important;
    color: var(--color-text, #eee) !important;
    border: 1px solid rgba(40, 113, 246, 0.2) !important;
  }

  /* 代码块内的 code 标签不添加额外样式 */
  pre code {
    background: none !important;
    padding: 0 !important;
    border: none !important;
  }

  /* ========== 代码块样式 ========== */
  pre {
    max-width: 100% !important;
    padding: 12px !important;
    border-radius: 6px !important;
    overflow-x: auto !important;
    margin: 12px 0 !important;
    border: 1px solid var(--color-border) !important;
    white-space: pre-wrap !important;
    word-break: break-all !important;
  }

  /* ========== 表格样式 ========== */
  table {
    border-collapse: collapse !important;
    width: 100% !important;
    margin: 12px 0 !important;
  }

  th,
  td {
    border: 1px solid var(--color-border, #333) !important;
    padding: 8px 12px !important;
    text-align: left !important;
  }

  th {
    background: rgba(40, 113, 246, 0.1) !important;
    font-weight: 600 !important;
  }

  /* ========== 分隔线样式 ========== */
  hr {
    border: none !important;
    border-top: 1px solid var(--color-border, #333) !important;
    margin: 16px 0 !important;
  }

  /* ========== 段落内的代码 ========== */
  p code,
  li code,
  td code,
  th code,
  h1 code,
  h2 code,
  h3 code,
  h4 code,
  h5 code,
  h6 code,
  blockquote code {
    padding: 2px 6px !important;
    border-radius: 4px !important;
    font-family: "Consolas", "Monaco", "Courier New", monospace !important;
    font-size: 1em !important;
    color: var(--color-text, #eee) !important;
  }

  /* ========== 引用标记样式 ========== */
  .citation-tag {
    display: inline-block !important;
    padding: 2px 4px !important;
    background-color: transparent !important;
    border-radius: 2px !important;
    color: #1890ff !important;
    font-size: 0.85em !important;
    font-weight: normal !important;
    cursor: pointer !important;
    transition:
      color 0.2s ease,
      background-color 0.2s ease !important;
    white-space: nowrap !important;
    margin: 0 2px !important;
    vertical-align: super !important;
    line-height: 1 !important;
    text-decoration: none !important;
    position: relative !important;
    top: -0.1em !important;
    pointer-events: auto !important;
    z-index: 10 !important;
    user-select: none !important;
    -webkit-user-select: none !important;

    &:hover {
      background-color: rgba(24, 144, 255, 0.1) !important;
      color: #096dd9 !important;
      text-decoration: underline !important;
    }

    &:active {
      background-color: rgba(24, 144, 255, 0.2) !important;
    }
  }
}
</style>

<!-- 引用弹窗样式 - 全局样式,确保样式生效 -->
<style lang="scss">
/* 引用弹窗样式 */
.citation-modal {
  position: fixed;
  z-index: 10000;
  max-width: 500px;
  min-width: 300px;
  width: auto;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  opacity: 0;
  transform: translateY(-5px);
  transition:
    opacity 0.2s ease-out,
    transform 0.2s ease-out;
  pointer-events: none;
  overflow: hidden;

  &.show {
    opacity: 1;
    transform: translateY(0);
    pointer-events: auto;
  }
}

.citation-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-radius: 12px 12px 0 0;
  color: var(--color-text, #e0e0e0);
}

.citation-modal-title {
  font-size: 13px;
  font-weight: 500;
  color: var(--color-primary, #2871f6);
  background: rgba(24, 144, 255, 0.1);
  line-height: 1.5;
  padding: 2px 6px;
  border-radius: 4px;
}

.citation-modal-close {
  background: none;
  border: none;
  color: var(--color-text, #e0e0e0);
  font-size: 16px;
  cursor: pointer;
  padding: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: opacity 0.2s;
  width: 24px;
  height: 24px;
  border-radius: 4px;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    opacity: 0.9;
  }

  &:active {
    opacity: 0.7;
  }

  i {
    font-size: 14px;
  }
}

.citation-modal-body {
  padding: 0 16px;
  max-height: 400px;
  overflow-y: auto;
}

.citation-modal-content-text {
  font-size: 13px;
  color: #333;
  line-height: 1.8;
  letter-spacing: 0.01em;
  text-align: justify;
  /* 中英文字体栈:英文用Times New Roman,中文用宋体/仿宋 */
  font-family: "Times New Roman", 宋体, SimSun, 仿宋, FangSong, serif;
  word-wrap: break-word;

  /* 作者样式 */
  .citation-author {
    color: #333;
  }

  /* 标题样式 */
  .title-bold {
    font-weight: 700 !important;
    color: #333 !important;
  }

  /* 期刊样式 */
  .journal-style {
    font-weight: 700 !important;
    color: #0066cc !important;
    font-style: italic !important;
  }

  /* 其他内容样式(年份、DOI等) */
  .citation-other {
    color: #666;
  }
}

.citation-modal-footer {
  padding: 12px 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
}

.citation-modal-link {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  color: var(--color-primary, #2871f6);
  font-size: 13px;
  text-decoration: none;
  transition: color 0.2s;
  padding: 4px 8px;
  border-radius: 4px;

  &:hover {
    color: #40a9ff;
    background: rgba(24, 144, 255, 0.08);
  }

  i {
    font-size: 11px;
  }
}

/* 深色主题适配 */
:root.theme-dark {
  .citation-modal {
    background: #1f1f1f;
    border: 1px solid #333;
  }

  .citation-modal-header {
    background: #1890ff;
  }

  .citation-modal-content-text {
    color: #e0e0e0;

    .citation-author {
      color: #e0e0e0;
    }

    .title-bold {
      color: #e0e0e0 !important;
    }

    .journal-style {
      color: #4a9eff !important;
    }

    .citation-other {
      color: #aaa;
    }
  }

  .citation-modal-footer {
    border-top-color: #333;
  }
}
</style>

<style lang="scss" scoped>
.deerflow-chat {
  * {
    box-sizing: border-box;
  }
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: flex-start; /* 改为 flex-start */
  height: 100vh;
  width: 100%;
  flex: 1; /* 确保占据剩余空间 */
  min-width: 0; /* 允许收缩 */
  position: relative;
  background: var(--color-bg, #141518);
  box-sizing: border-box;
  max-width: 100%;
  overflow: hidden; /* 改为 hidden 以确保内容不溢出 */
}

/* 返回按钮容器 */
.back-button-container {
  position: absolute;
  top: 16px;
  left: 20px;
  z-index: 1000;
}

.back-button {
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text, #fff);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 16px;
}

.back-button:active {
  opacity: 0.8;
  transform: scale(0.95);
}

.back-button i {
  font-size: 16px;
}

.chat-main {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
  height: 100vh;
  width: 100%;
  position: relative;
  overflow: hidden;
}

/* Header 区域样式 */
.chat-header {
  width: 90%;
  margin: 0 auto;
  padding: 16px 0px;
  flex-shrink: 0;
}

.header-content {
  width: 100%;
}

.message-header-tools {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;

  .icon-svg {
    width: 14px;
    height: 14px;
    cursor: pointer;
    opacity: 0.6;
    transition: opacity 0.2s;

    &:hover {
      opacity: 1;
    }
  }
}

.user-message-header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  column-gap: 10px;
}

.message-text-wrapper {
  flex: 1;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  min-width: 0; // 允许文本收缩
}

.user-message-header .message-text {
  margin-bottom: 12px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 24px;
  color: var(--color-text);
  font-weight: 700;
  flex: 1;
  min-width: 0;
  transition: max-height 0.3s ease;
}

.user-message-header .message-text.collapsed {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  max-height: 1.6em; // line-height * 1
  margin-bottom: 0;
}

.toggle-icon {
  cursor: pointer;
  color: #6b7280;
  font-size: 12px;
  margin-top: 2px;
  flex-shrink: 0;
  transition: color 0.2s ease;
}

.toggle-icon:hover {
  color: #1f2937;
}

/* 高级筛选容器 */
.advanced-filter-container {
  width: 90%;
  margin: 0 auto;
  display: flex;
  gap: 12px;
  padding: 10px 0px;
  align-items: flex-start;
}

/* 高级筛选按钮样式 */
.advanced-filter-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  flex-shrink: 0;
  margin-top: 4px;

  .filter-icon {
    width: 16px;
    height: 16px;
    object-fit: contain;
  }

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

/* 筛选标签包装器 */
.filter-tags-wrapper {
  flex: 1;
  display: flex;
  align-items: flex-start;
  gap: 8px;
  min-width: 0;
}

/* 筛选标签容器 */
.filter-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  min-width: 0;
  flex: 1;
  transition: max-height 0.3s ease;
}

.filter-tags.collapsed {
  overflow: hidden;
  max-height: 32px; // 大约1行的高度
}

/* 筛选标签样式 */
.filter-tag {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 4px 8px;
  border: 1px solid #1890ff;
  border-radius: 6px;
  background: var(--color-bg, #fff);
  color: #1890ff;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  box-shadow: 0 0 0 0 rgba(24, 144, 255, 0.2);
  flex-shrink: 0;

  /* 选中状态的发光效果 */
  &:hover {
    border-color: #40a9ff;
    color: #40a9ff;
    box-shadow: 0 0 4px rgba(24, 144, 255, 0.3);
  }

  /* 更多选项标签样式 */
  &.filter-tag-more {
    cursor: default;
    font-weight: 600;
    padding: 6px 10px;
  }
}

/* 加载状态样式 */
.chat-loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  gap: 16px;
  width: 90%;
  margin: 0 auto;
  min-height: 200px;
}

.loading-spinner {
  font-size: 32px;
  color: var(--color-primary);
}

.loading-spinner i {
  animation: spin 1.5s linear infinite;
}

.chat-loading-state .loading-text {
  font-size: 16px;
  color: var(--color-text);
  font-weight: 500;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 全局 Tab 切换栏样式 - 固定在顶部 */
.global-tabs {
  display: flex;
  align-items: center;
  gap: 0;
  border-bottom: 1px solid #e5e7eb;
  flex-shrink: 0;
  width: 90%;
  margin: 0 auto;
  position: sticky;
  top: 0;
  z-index: 100;
  margin-bottom: 30px;
  padding: 10px 0px;
  flex-wrap: wrap; /* 允许在窄屏下换行 */
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  width: 90%;
  margin: 0 auto;
  box-sizing: border-box;

  /* 隐藏滚动条 */
  &::-webkit-scrollbar {
    width: 0;
    display: none;
  }

  scrollbar-width: none;
  -ms-overflow-style: none;
}

.message {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.message.user {
  align-items: flex-start;
}

.message.assistant {
  align-items: flex-start;
}

.message-content {
  width: 100%;
  max-width: 100%;
  min-width: 0; /* 改为 0 */
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: anywhere; /* 增强换行能力 */
  box-sizing: border-box;
  overflow: hidden; /* 额外保护 */
}

/* 用户消息 */
.user-message {
  color: var(--user-question-text);
  padding: 12px 0px;
}

.user-message .message-text {
  margin-bottom: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-word;
  font-size: 14px;
}

.model-status {
  display: flex;
  align-items: center;
  gap: 6px;
  color: var(--color-text);

}

.status-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;

  i {
    font-size: 12px;
  }

  &.success {
    background: rgba(34, 197, 94, 0.15);
    border: 1px solid rgba(34, 197, 94, 0.3);
    color: #22c55e;
  }

  &.generating {
    background: rgba(59, 130, 246, 0.15);
    border: 1px solid rgba(59, 130, 246, 0.3);
    color: #3b82f6;
  }

  &.searching {
    background: rgba(245, 158, 11, 0.15);
    border: 1px solid rgba(245, 158, 11, 0.3);
    color: #f59e0b;
  }

  &.pending {
    background: rgba(156, 163, 175, 0.15);
    border: 1px solid rgba(156, 163, 175, 0.3);
    color: #9ca3af;
  }

  &.error {
    background: rgba(239, 68, 68, 0.15);
    border: 1px solid rgba(239, 68, 68, 0.3);
    color: var(--color-primary);
  }

  &.warning {
    background: rgba(245, 158, 11, 0.15);
    border: 1px solid rgba(245, 158, 11, 0.3);
    color: #f59e0b;
  }
}

/* AI 消息 */
.assistant-message {
  background: transparent;
  border-radius: 8px;
  margin-bottom: 16px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

/* 时间线容器样式 */
.timeline-container {
  position: relative;
  padding-left: 0; /* 取消左侧padding,因为不再需要连接线 */
}

.timeline-node {
  position: relative;
  margin-bottom: 16px;
  background: var(--color-bg, #141518);

  &.start-node {
    margin-bottom: 16px;
  }

  &.agent-node {
    margin-bottom: 16px;
    border-radius: 8px;
  }
}

.timeline-icon {
  position: relative; /* 改为相对定位,不再需要绝对定位 */
  top: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  z-index: 2;
  margin-right: 12px; /* 添加右边距 */

  &.start-icon {
    background: var(--color-primary);
    color: #ffffff;
    font-size: 12px;
  }

  &.agent-icon {
    background: #ffffff;
    border: 2px solid var(--color-primary);
    color: var(--color-primary);
    font-size: 10px;
    font-weight: 600;
  }
}

.timeline-content {
  position: relative;
  display: flex;
  flex-direction: column;
  min-width: 0; /* 允许内容在必要时收缩 */

  .timeline-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    padding: 16px;
    background: var(--color-card);
    min-width: 0; /* 允许 header 收缩 */
  }

  .timeline-header-left {
    display: flex;
    align-items: center;
    gap: 6px;
    min-width: 0; /* 允许左侧内容收缩 */
  }

  .timeline-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--color-text);
    line-height: 1.4;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis; /* 标题过长时显示省略号 */
    min-width: 0;
  }

  .expand-toggle-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    cursor: pointer;
    transition: all 0.2s ease;
    color: #6b7280;
    border: none;
    background: transparent;
    padding: 0;
    outline: none;

    i {
      font-size: 14px;
    }
  }

  .timeline-line {
    display: none; /* 隐藏垂直连接线 */
  }
}

.tab-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 16px;
  border: none;
  background: transparent;
  border: 1px solid transparent;
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  position: relative;
  white-space: nowrap;

  i {
    font-size: 14px;
    color: inherit;
    margin-top: 4px;
  }

  &:hover:not(.active):not(:disabled) {
    background: transparent;
    color: #374151;

    i {
      color: #374151;
    }
  }

  &.active {
    background: #e6f4ff;
    border: 1px solid transparent;
    color: var(--color-primary);

    i {
      color: var(--color-primary);
      margin-top: 4px;
    }

    &::after {
      display: none;
    }
  }

  &.disabled,
  &:disabled {
    opacity: 0.4;
    cursor: not-allowed;
    color: #9ca3af;

    i {
      color: #9ca3af;
      opacity: 0.4;
    }

    &:hover {
      background: transparent;
      color: #9ca3af;

      i {
        color: #9ca3af;
        opacity: 0.4;
      }
    }
  }
}

/* Agent Content Wrapper */
.agent-content-wrapper {
  backdrop-filter: blur(10px);
  padding: 0 10px;
}

/* Tab Content 样式 */
.plan-tab-content,
.reasoning-tab-content,
.results-tab-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  width: 100%;
  max-width: 100%;
  overflow-x: hidden;
  box-sizing: border-box;
  min-width: 0;
}

/* 推理过程容器样式 - 只在有内容时显示边框 */
.reasoning-tab-content {
  border-radius: 8px;
  background: var(--color-bg, #141518);

  /* 只在有内容时显示边框 */
  &.has-content {
    border: 2px solid var(--color-border);
  }
}

/* 暂无结果提示 */
.no-results-message,
.no-content-message {
  padding: 40px 20px;
  text-align: center;
  color: var(--color-text-secondary, #999);
  font-size: 14px;
}

/* 计划操作按钮包装器 */
.plan-actions-wrapper {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e5e7eb;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  justify-content: flex-end;
}

/* 流式数据加载动画 */
.streaming-loading {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 12px;
  padding: 12px 0;
  color: var(--color-text-secondary, #999);
}

.loading-dots {
  display: flex;
  gap: 4px;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--color-primary, #409eff);
  animation: loading-bounce 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}
.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

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

@keyframes loading-bounce {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* AI 思考状态 */
.ai-thinking {
  display: flex;
  align-items: center;
  gap: 12px;
  color: var(--color-text-secondary, #999);
}

.thinking-dots {
  margin: 8px 0;
  display: flex;
  gap: 4px;
}

.thinking-dots span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: var(--color-primary, #409eff);
  animation: thinking 1.4s infinite ease-in-out;
}

.thinking-dots span:nth-child(1) {
  animation-delay: -0.32s;
}
.thinking-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes thinking {
  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.thinking-text {
  font-size: 14px;
}

/* 工具图标 */
.message-tools {
  display: flex;
  margin: 12px 0 8px 0;
  flex-wrap: wrap;
  align-items: center;
  column-gap: 12px;
  background: var(--ai-answer-bg);
  color: var(--ai-answer-text);
  border: 1px solid transparent;
  transition: border-color 0.2s ease;

  .feedback-tools {
    display: flex;
    align-items: center;
    gap: 10px;

    .feedback-icon {
      cursor: pointer;
      font-size: 16px;
      color: var(--color-text-secondary);
      opacity: 0.6;
      transition: all 0.2s;

      &:hover {
        opacity: 1;
        transform: scale(1.1);
      }

      &.is-active {
        opacity: 1;
        color: var(--color-primary);
      }

      &.fa-thumbs-down.is-active {
        color: var(--el-color-danger);
      }

      &.is-disabled {
        cursor: not-allowed;
        pointer-events: none;
        filter: grayscale(1);
        opacity: 0.3;
      }
    }
  }

  .divider-vertical {
    width: 1px;
    height: 12px;
    background: var(--color-border);
    opacity: 0.4;
  }

  .icon-svg {
    width: 16px;
    height: 16px;
    cursor: pointer;
    opacity: 0.7;
    transition: opacity 0.2s;

    &:hover:not(.disabled) {
      opacity: 1;
      transform: scale(1.1);
    }

    &.disabled {
      opacity: 0.3;
      cursor: not-allowed;
    }
  }
}

.feedback-tags-container {
  padding: 4px;

  .feedback-title {
    font-size: 13px;
    font-weight: 500;
    margin-bottom: 12px;
    color: var(--color-text);
  }

  .tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;

    .feedback-tag {
      cursor: pointer;
      transition: all 0.2s;
      border-radius: 6px;
      user-select: none;
      font-size: 11px;
      padding: 2px 8px;

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .feedback-footer {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid var(--color-border);
    padding-top: 12px;
  }
}

:deep(.feedback-popover) {
  border-radius: 12px;
  padding: 12px;
  border: 1px solid var(--color-border);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  background: var(--color-card, #fff);
}

/* Multi-Agent 容器 */
.multi-agent-container {
  width: 100%;
  max-width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
  box-sizing: border-box;
  min-width: 0;
}

/* Agent 区块样式 */
.agent-section {
  margin-bottom: 0;
  border-radius: 8px;
  overflow: hidden;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.agent-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  border-radius: 6px;
  font-weight: 500;
}

.agent-header i {
  font-size: 16px;
}

/* Agent 名称样式 */
.agent-header .agent-name {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-primary, #409eff);
}

/* 推理内容样式 */
.reasoning-section {
  margin-bottom: 16px;
  padding: 14px 16px;
  background: rgba(59, 130, 246, 0.06);
  border-left: 3px solid rgba(59, 130, 246, 0.6);
  border-radius: 6px;
  backdrop-filter: blur(5px);
}

.reasoning-content {
  color: rgba(255, 255, 255, 0.7);
  font-size: 13px;
  line-height: 1.65;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: anywhere;
}

/* 内容区域样式 */
.content-section {
  .content {
    line-height: 1.8;
    color: var(--color-text, #eee);
    word-wrap: break-word;
    word-break: break-word;

    &.typing {
      position: relative;
    }
  }
}

/* 确保代码块和预格式化文本也能正确处理 */
.content pre,
.content code {
  max-width: 100%;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.content pre::-webkit-scrollbar,
.content code::-webkit-scrollbar {
  display: none;
}

/* ========== Markdown 内容样式 ========== */
/* 为所有包含 markdown 渲染内容的元素添加样式 */

/* 标题样式 - 应用到所有容器 */
.content h1,
.content h2,
.content h3,
.content h4,
.content h5,
.content h6,
.thought-content h1,
.thought-content h2,
.thought-content h3,
.thought-content h4,
.thought-content h5,
.thought-content h6,
.step-title h1,
.step-title h2,
.step-title h3,
.step-title h4,
.step-title h5,
.step-title h6,
.step-description h1,
.step-description h2,
.step-description h3,
.step-description h4,
.step-description h5,
.step-description h6,
.reasoning-content h1,
.reasoning-content h2,
.reasoning-content h3,
.reasoning-content h4,
.reasoning-content h5,
.reasoning-content h6 {
  margin: 16px 0 8px 0;
  font-weight: 600;
  line-height: 1.4;
  color: var(--color-text, #eee);
}

.content h1,
.thought-content h1,
.step-title h1,
.step-description h1,
.reasoning-content h1 {
  font-size: 24px;
  border-bottom: 2px solid var(--color-border, #333);
  padding-bottom: 8px;
}

.content h2,
.thought-content h2,
.step-title h2,
.step-description h2,
.reasoning-content h2 {
  font-size: 22px;
  border-bottom: 1px solid var(--color-border, #333);
  padding-bottom: 6px;
}

.content h3,
.thought-content h3,
.step-title h3,
.step-description h3,
.reasoning-content h3 {
  font-size: 20px;
  color: var(--color-primary, #409eff);
}

.content h4,
.thought-content h4,
.step-title h4,
.step-description h4,
.reasoning-content h4 {
  font-size: 18px;
}

.content h5,
.thought-content h5,
.step-title h5,
.step-description h5,
.reasoning-content h5 {
  font-size: 16px;
}

.content h6,
.thought-content h6,
.step-title h6,
.step-description h6,
.reasoning-content h6 {
  font-size: 14px;
}

/* 段落样式 */
.content p,
.thought-content p,
.step-description p,
.reasoning-content p {
  margin: 8px 0;
  line-height: 1.6;
}

/* 列表样式 */
.content ul,
.content ol,
.thought-content ul,
.thought-content ol,
.step-description ul,
.step-description ol,
.reasoning-content ul,
.reasoning-content ol {
  margin: 8px 0;
  padding-left: 20px;
}

.content li,
.thought-content li,
.step-description li,
.reasoning-content li {
  margin: 4px 0;
  line-height: 1.5;
}

/* 行内代码样式 */
.content code,
.thought-content code,
.step-title code,
.step-description code,
.reasoning-content code {
  background: rgba(40, 113, 246, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
  font-family: "Consolas", "Monaco", "Courier New", monospace;
  font-size: 1em;
  color: var(--color-text, #eee);
}

/* 代码块样式 */
.content pre,
.thought-content pre,
.step-description pre,
.reasoning-content pre {
  background: rgba(40, 113, 246, 0.05);
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto;
  margin: 12px 0;
}

.content pre code,
.thought-content pre code,
.step-description pre code,
.reasoning-content pre code {
  background: none;
  padding: 0;
}

/* 引用块样式 */
.content blockquote,
.thought-content blockquote,
.step-description blockquote,
.reasoning-content blockquote {
  margin: 16px 0;
  padding: 8px 16px;
  border-left: 4px solid var(--color-primary, #409eff);
  background: rgba(40, 113, 246, 0.05);
  font-style: italic;
  color: var(--color-text-secondary, #999);
}

/* 表格样式 */
.content table,
.thought-content table,
.step-description table,
.reasoning-content table {
  border-collapse: collapse;
  width: 100%;
  margin: 12px 0;
}

.content th,
.content td,
.thought-content th,
.thought-content td,
.step-description th,
.step-description td,
.reasoning-content th,
.reasoning-content td {
  border: 1px solid var(--color-border, #333);
  padding: 8px 12px;
  text-align: left;
}

.content th,
.thought-content th,
.step-description th,
.reasoning-content th {
  background: rgba(40, 113, 246, 0.1);
  font-weight: 600;
}

/* 链接样式 */
.content a,
.thought-content a,
.step-description a,
.reasoning-content a {
  color: var(--color-primary, #409eff);
  text-decoration: none;

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

/* 加粗和斜体 */
.content strong,
.thought-content strong,
.step-description strong,
.reasoning-content strong {
  font-weight: 600;
  color: var(--color-text, #eee);
}

.content em,
.thought-content em,
.step-description em,
.reasoning-content em {
  font-style: italic;
}

/* 分隔线样式 */
.content hr,
.thought-content hr,
.step-description hr,
.reasoning-content hr {
  border: none;
  border-top: 1px solid var(--color-border, #333);
  margin: 16px 0;
}

/* 图片样式 */
.content img,
.thought-content img,
.step-description img,
.reasoning-content img {
  max-width: 100%;
  height: auto;
  border-radius: 4px;
  margin: 8px 0;
}

/* ========== PlanCard 样式 ========== */
.plan-card {
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  color: var(--color-text, #333333);
}

/* 计划标题容器 */
.plan-title-container {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.plan-title {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text, #333333);
  min-width: 0;
  word-wrap: break-word;
  word-break: break-word;
}

/* 计划内容样式 */
.plan-content {
  width: 100%;
}

.plan-card-container {
  width: 100%;
}

.plan-body {
  width: 100%;
}

/* 计划思路样式 */
.plan-thought {
  margin-bottom: 20px;
  padding: 14px 16px;
  background: rgba(59, 130, 246, 0.04);
  border-radius: 8px;
  border: 1px solid rgba(59, 130, 246, 0.1);
  color: var(--color-text, #333333);

  .thought-content {
    color: var(--color-text, #333333);
    line-height: 1.6;
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: anywhere;
  }
}

.thought-content {
  padding: 0;
  line-height: 1.7;
  color: rgba(255, 255, 255, 0.75);
  font-size: 16px;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: anywhere;
}

.thought-content.typing {
  position: relative;
}

/* 步骤容器样式 */
.plan-steps {
  margin-top: 16px;
  color: var(--color-text, #333333);
}

.steps-container {
  padding: 0;
  margin: 0;
}

.step-item {
  position: relative;
  padding: 16px 16px 16px 52px;
  opacity: 0;
  animation: fadeInStep 0s ease-in-out forwards;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 10px;
  border: 1px solid rgba(255, 255, 255, 0.05);
  transition: all 0.3s ease;
  color: var(--color-text, #333333);

  &.step-editing {
    background: rgba(37, 99, 235, 0.05);
    border: 1px solid rgba(37, 99, 235, 0.2);
  }
}

.step-item::before {
  content: attr(data-step-number);
  position: absolute;
  left: 18px;
  top: 18px;
  width: 24px;
  height: 24px;
  color: #ffffff;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 12px;
  box-shadow: 0 2px 6px rgba(59, 130, 246, 0.3);
}

.step-content {
  transition: all 0.2s ease;
}

.step-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.step-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text, #333333);
  flex: 1;
  line-height: 1.5;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: anywhere;
  min-width: 0;
}

.step-title.typing {
  position: relative;
}

.tools-badge {
  display: flex;
  align-items: center;
  gap: 4px;
  background: rgba(59, 130, 246, 0.15);
  color: #60a5fa;
  padding: 4px 10px;
  font-size: 11px;
  font-weight: 600;
  border-radius: 12px;
  border: 1px solid rgba(59, 130, 246, 0.25);
}

.step-description {
  line-height: 1.7;
  color: var(--color-text-secondary, #666666);
  margin-bottom: 0;
  font-size: 16px;
  word-wrap: break-word;
  word-break: break-word;
  overflow-wrap: anywhere;
}

.step-description.typing {
  position: relative;
}

.step-tools {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

/* 编辑模式输入框样式 */
.step-title-input {
  width: 100%;
  padding: 8px 12px;
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text, #333333);
  background: #ffffff;
  border: 2px solid #3b82f6;
  border-radius: 6px;
  outline: none;
  transition: all 0.3s ease;

  &:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
  }

  &::placeholder {
    color: #9ca3af;
  }
}

.step-description-textarea {
  width: 100%;
  padding: 8px 12px;
  font-size: 13px;
  line-height: 1.7;
  color: var(--color-text-secondary, #666666);
  background: #ffffff;
  border: 2px solid #3b82f6;
  border-radius: 6px;
  outline: none;
  resize: vertical;
  min-height: 80px;
  transition: all 0.3s ease;
  font-family: inherit;

  &:focus {
    border-color: #2563eb;
    box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
  }

  &::placeholder {
    color: #9ca3af;
  }
}

/* 步骤淡入动画 */
@keyframes fadeInStep {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 计划操作按钮区域 */
.plan-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
  padding-top: 16px;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
}

.plan-action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  i {
    font-size: 14px;
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  &:not(:disabled):hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  &:not(:disabled):active {
    transform: translateY(0);
  }
}

.btn-blue-outline {
  background: #eff6ff;
  color: #2563eb;
  border: 1px solid #2563eb;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;

  &:not(:disabled):hover {
    background: #dbeafe;
    box-shadow: 0 2px 8px rgba(37, 99, 235, 0.2);
  }

  &:not(:disabled):active {
    background: #bfdbfe;
  }
}

.btn-edit {
  color: var(--color-primary);
  border: 1px solid var(--color-primary);
}

.btn-accept {
  color: var(--color-primary);
  border: 1px solid var(--color-primary);
}

.btn-continue {
  color: #22c55e;
  border: 1px solid #22c55e;

  &:not(:disabled):hover {
    background: #dcfce7;
    box-shadow: 0 2px 8px rgba(34, 197, 94, 0.2);
  }

  &:not(:disabled):active {
    background: #bbf7d0;
  }
}

/* planner-message 特殊样式 */
.planner-message.agent-section {
  .plan-card {
    background: linear-gradient(
      135deg,
      rgba(30, 30, 35, 0.5) 0%,
      rgba(25, 25, 30, 0.4) 100%
    );
    border-radius: 12px;
    border: 1px solid rgba(255, 255, 255, 0.06);
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .message-content {
    max-width: 95%;
  }

  .content h1 {
    font-size: 20px;
  }

  .content h2 {
    font-size: 18px;
  }

  .content h3 {
    font-size: 16px;
  }

  /* PlanCard 响应式样式 */
  .step-item {
    padding-left: 32px;
  }

  .step-item::before {
    width: 20px;
    height: 16px;
    font-size: 12px;
    left: 16px;
  }
}

@media (max-width: 480px) {
  .status-badge {
    font-size: 10px;
    padding: 3px 8px;
  }
}

/* ==================== 状态提示样式 ==================== */

/* 状态提示容器 */
.status-indicator {
  margin: 20px 0;
  border-radius: 12px;
  display: flex;
  align-items: center;
  animation: statusFadeIn 0.4s ease-in-out;
  backdrop-filter: blur(10px);
}

/* 状态内容 */
.status-content {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 15px;
  font-weight: 500;
  color: #333;
}

/* 加载图标旋转动画 */
.status-content i {
  font-size: 18px;
  animation: statusSpin 1s linear infinite;
}

.plan-generating .status-content i {
  color: #2196f3;
}

.research-progress .status-content i {
  color: #ff9800;
}

/* ==================== Complete 节点样式 ==================== */

.complete-node {
  position: relative;
}

/* ==================== 深度检索启动弹窗样式 ==================== */
.deep-search-starting-card {
  position: fixed;
  left: 54px; /* 更贴近左侧边栏 */
  bottom: 60px;
  width: 320px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  z-index: 3000;
  font-size: 13px;
  color: #333;
}

.deep-search-card-inner {
  padding: 16px 16px 12px;
}

.deep-search-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.deep-search-card-header .header-left {
  display: flex;
  align-items: center;
  gap: 6px;
}

.deep-search-card-header{
  font-size: 16px;
  color: #1890ff;
}

.deep-search-card-header .header-title {
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.deep-search-card-header .header-close {
  font-size: 14px;
  color: #bfbfbf;
  cursor: pointer;
}

.deep-search-card-header .header-close:hover {
  color: #8c8c8c;
}

.deep-search-card-body {
  margin-bottom: 12px;
}

.deep-search-card-body .info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  line-height: 1.6;
  color: #555;
  margin-bottom: 4px;
}

.deep-search-card-body .info-item:last-child {
  margin-bottom: 0;
}

.deep-search-card-body .info-icon {
  font-size: 12px;
  color: #555;
  margin-top: 4px;
}

.deep-search-card-footer {
  display: flex;
  justify-content: flex-end;
}

.deep-search-card-footer .confirm-btn {
  height: 28px;
  padding: 0 14px;
  border-radius: 8px;
  font-size: 12px;
}

.starting-modal-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;

  .modal-title {
    font-size: 20px;
    font-weight: 600;
    color: #1890ff;
    margin-bottom: 24px;
  }

  .info-list {
    width: 100%;
    background: #f8f9fa;
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 24px;
    text-align: left;

    .info-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 12px;
      gap: 10px;

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

      i {
        margin-top: 3px;
        color: #666;
        font-size: 14px;
      }

      &.warning {
        i {
          color: #faad14;
        }
        .info-text {
          font-size: 12px;
          color: #faad14;
          line-height: 1.6;
        }
      }

      .info-right {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        font-size: 14px;
        line-height: 1.5;

        .info-label {
          color: #333;
          font-weight: 500;
        }

        .info-value {
          color: #666;
        }
      }
    }
  }

  .modal-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 100%;

    .action-btn {
      margin: 0;
      height: 40px;
      border-radius: 20px;
      font-weight: 500;

      &.main-btn {
        background: #1890ff;
        border-color: #1890ff;
      }

      &.secondary-btn {
        background: #fff;
        color: #666;
        border-color: #d9d9d9;

        &:hover {
          color: #1890ff;
          border-color: #1890ff;
        }
      }
    }
  }
}

.complete-actions {
  margin-top: 12px;
  display: flex;
  justify-content: flex-start;
}

/* View Report 按钮 */
.view-report-btn {
  padding: 8px 16px;
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.2s ease;
}

.view-report-btn:hover {
  background: var(--color-primary-dark, #409eff);
  opacity: 0.9;
}

.view-report-btn:active {
  opacity: 0.8;
}

.view-report-btn i {
  font-size: 14px;
}

/* ==================== 动画定义 ==================== */

/* 状态提示淡入动画 */
@keyframes statusFadeIn {
  from {
    opacity: 0;
    transform: translateY(-15px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载图标旋转动画 */
@keyframes statusSpin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* ==================== 响应式设计 ==================== */

@media (max-width: 768px) {
  .status-indicator {
    padding: 12px 16px;
    margin: 16px 0;
  }

  .status-content {
    font-size: 14px;
  }

  .view-report-btn {
    padding: 8px 16px;
    font-size: 13px;
    width: 100%;
    justify-content: center;
  }
}
</style>