BaichuanChat.vue 58.5 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
<template>
  <div class="baichuan-chat-container">
    <!-- 消息列表区域 -->
    <div class="messages-area" ref="messagesArea">
      <div
        v-for="message in displayMessages"
        :key="message.questionId"
        class="message-group"
      >
        <!-- 用户问题 -->
        <div class="message-item user-message">
          <div class="message-content">
            <div class="message-text">{{ message.question }}</div>
          </div>
          <!-- 复制按钮 -->
          <div class="message-tools">
            <img
              src="/fuzhi.svg"
              alt="复制"
              class="icon-svg"
              title="复制"
              @click="handleCopyQuestion(message)"
            />
          </div>
        </div>

        <!-- AI 回答 -->
        <div
          v-for="(answer, answerIndex) in message.answers"
          :key="answerIndex"
          class="message-item ai-message"
        >
          <div class="message-content-wrapper">
            <!-- 思考状态区域 / 加载动画 -->
            <div
              v-if="
                answer.thinking || (!answer.answerContent && !answer.isComplete)
              "
              class="thinking-section"
            >
              <!-- 思考中或回答内容为空:显示三个点动画 -->
              <div
                v-if="
                  (!answer.answerContent ||
                    answer.answerContent.trim() === '') &&
                  !answer.isComplete &&
                  (!answer.thinking ||
                    !answer.thinking.steps ||
                    answer.thinking.steps.length === 0)
                "
                class="thinking-loading"
              >
                <div class="thinking-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
                <span class="thinking-text">AI思考中...</span>
              </div>

              <!-- 思考中:有步骤内容时且回答内容为空,显示步骤详情 -->
              <div
                v-if="
                  answer.thinking &&
                  answer.thinking.status === 'in_progress' &&
                  answer.thinking.steps &&
                  answer.thinking.steps.length > 0 &&
                  (!answer.answerContent || answer.answerContent.trim() === '')
                "
                class="thinking-progress"
              >
                <div class="thinking-steps-list">
                  <div
                    v-for="(step, stepIdx) in answer.thinking.steps"
                    :key="stepIdx"
                    class="thinking-step-item"
                  >
                    <i
                      class="fas step-icon"
                      :class="{
                        'fa-check-circle': step.status === 'completed',
                        'fa-spinner fa-spin': step.status === 'in_progress',
                      }"
                    ></i>
                    <span class="step-label">{{ step.label }}</span>
                  </div>
                </div>
              </div>

              <!-- 完成思考:回答开始后可折叠展示详细步骤 -->
              <div
                v-if="
                  answer.thinking &&
                  answer.thinking.status === 'completed' &&
                  answer.thinking.steps &&
                  answer.thinking.steps.length > 0 &&
                  answer.answerContent &&
                  answer.answerContent.trim() !== ''
                "
                class="thinking-completed"
              >
                <div
                  class="thinking-completed-header"
                  @click="toggleThinking(message.questionId)"
                >
                  <i
                    class="fas fa-chevron-down toggle-icon"
                    :class="{
                      expanded: isThinkingExpanded(message.questionId),
                    }"
                  ></i>
                  <span>完成思考</span>
                </div>
                <div
                  v-show="isThinkingExpanded(message.questionId)"
                  class="thinking-steps-completed"
                >
                  <div
                    v-for="(step, stepIdx) in answer.thinking.steps"
                    :key="stepIdx"
                    class="thinking-step-completed"
                  >
                    <i class="fas fa-check-circle step-icon-completed"></i>
                    <span class="step-label-completed">{{ step.label }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 回答内容 -->
            <div v-if="answer.answerContent" class="answer-content">
              <!-- 错误消息样式 -->
              <div v-if="isErrorMessage(answer)" class="error-message-wrapper">
                <i class="fas fa-exclamation-triangle error-icon"></i>
                <div
                  class="markdown-body error-message-content"
                  v-html="
                    renderMarkdown(answer.answerContent, answer.grounding)
                  "
                ></div>
              </div>
              <!-- 正常回答内容 -->
              <div
                v-else
                class="markdown-body"
                v-html="renderMarkdown(answer.answerContent, answer.grounding)"
              ></div>
            </div>

            <!-- 全部引用 - 直接渲染在回答内容之后 -->
            <div
              v-if="
                answer.grounding &&
                answer.grounding.length > 0 &&
                answer.isComplete
              "
              class="grounding-section-inline"
            >
              <div class="grounding-title">
                全部引用 ({{ answer.grounding.length }})
              </div>
              <div class="grounding-list">
                <div
                  v-for="(evidence, idx) in answer.grounding"
                  :key="idx"
                  class="evidence-item-inline"
                >
                  <div class="evidence-header-inline">
                    <span class="evidence-index-inline"
                      >[{{ Number(idx) + 1 }}]</span
                    >
                    <span class="evidence-title-inline">
                      {{ evidence.title || "未命名引用" }}
                    </span>
                  </div>
                  <div v-if="evidence.content" class="evidence-content-inline">
                    {{ evidence.content }}
                  </div>
                  <div v-if="evidence.url" class="evidence-url-inline">
                    <a
                      :href="evidence.url"
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <i class="fas fa-external-link-alt"></i>
                      {{ evidence.url }}
                    </a>
                  </div>
                </div>
              </div>
            </div>

            <!-- 回答内容为空提示 -->
            <div
              v-if="
                answer.isComplete &&
                (!answer.answerContent || answer.answerContent.trim() === '')
              "
              class="empty-answer-hint"
            >
              <i class="fas fa-info-circle"></i>
              <span>功能服务暂时异常,无法使用,请稍后再试~</span>
            </div>

            <!-- 工具图标 -->
            <div
              class="message-tools"
              v-if="
                answer.answerContent &&
                answer.isComplete &&
                !isErrorMessage(answer)
              "
            >
              <img
                src="/bianji.svg"
                alt="生成文档并编辑"
                class="icon-svg"
                :class="{ disabled: !answer.isComplete }"
                title="生成文档并编辑"
                @click="handleSaveAndEdit(message, answer)"
              />
              <img
                src="/fuzhi.svg"
                alt="复制"
                class="icon-svg"
                :class="{ disabled: !answer.isComplete }"
                title="复制"
                @click="handleCopyAnswer(answer)"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="messages.length === 0" class="empty-state">
        <i class="fas fa-comments"></i>
        <p>开始与AI 对话</p>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <CentralInput
        :loading="isSending"
        :service-price="servicePrice"
        @submit="handleSubmit"
        @stop="handleStop"
      />
      <!-- AI 生成内容提示 -->
      <div class="ai-generated-disclaimer">
        {{ t("chat.aiGeneratedDisclaimer") }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick, computed } from "vue";
import { useI18n } from "vue-i18n";
import { useChatApiStore } from "@/stores/chatApi";
import { useAppStore } from "@/stores/app";
import { ElMessage, ElLoading } from "element-plus";
import { useRouter } from "vue-router";
import CentralInput from "@/components/WorkspaceWelcome/CentralInput.vue";
import { markdownToHtml, ensureKatexReady } from "@/utils/renderMarkdown";
import {
  apiCreateDraftFromQuestion,
  apiSaveDraftToKnowledge,
} from "@/api/drafts";
import { getFiles, createFolder, getFileContent } from "@/api/files";
import { getBeansBalance, getServicePrice, consumeBeans } from "@/api/pay";
// 引入 KaTeX 样式以支持数学公式渲染(仅样式,JS 通过 ensureKatexReady 按需加载)
import "katex/dist/katex.min.css";

interface Props {
  currentSession?: any;
  initialMessage?: string;
}

const props = defineProps<Props>();
const emit = defineEmits([
  "session-created",
  "message-sent",
  "answer-completed",
]);

const { t } = useI18n();
const router = useRouter();
const chatApiStore = useChatApiStore();
const messagesArea = ref<HTMLElement | null>(null);

// 状态判断:是否正在发送或接收消息
const isSending = computed(() => {
  return chatApiStore.aiThinking || chatApiStore.streamingAnswer || false;
});

const expandedThinkings = ref<Set<string>>(new Set());
const servicePrice = ref<number | null>(null); // 服务价格

// 计算属性:消息列表
const messages = computed(() => chatApiStore.messages);

// 展示用消息列表:合并/去重连续重复的用户问题(避免同一条问题被渲染多次)
const displayMessages = computed(() => {
  const list = messages.value || [];
  const result: any[] = [];

  for (const msg of list) {
    const last = result[result.length - 1];
    const curQuestion = (msg?.question || "").trim();
    const lastQuestion = (last?.question || "").trim();

    const normalizeAnswers = (answers: any) => {
      if (!Array.isArray(answers) || answers.length === 0) return [];
      // 只展示最后一个回答,避免 answers 内部重复渲染
      return [answers[answers.length - 1]];
    };

    // 如果相邻两条问题文本一致,则认为是重复渲染来源(本地插入 + 服务端回写等),合并展示
    if (last && curQuestion && curQuestion === lastQuestion) {
      result[result.length - 1] = {
        // 以“最后一条消息”为准(通常包含更完整的最新 answers)
        ...msg,
        // key 仍用第一条的 questionId,避免 DOM 重建导致闪烁
        questionId: last.questionId,
        answers: normalizeAnswers(msg.answers),
      };
      continue;
    }

    result.push({
      ...msg,
      answers: normalizeAnswers(msg.answers),
    });
  }

  return result;
});

// 按需加载 KaTeX:只有在进入该聊天组件时才会真正加载 katex 相关 JS
onMounted(() => {
  ensureKatexReady().catch(() => {
    // 加载失败时降级为普通 Markdown 渲染
  });
});

// 渲染 Markdown,并处理引用序号的悬浮提示
const renderMarkdown = (text: string, grounding?: any[]): string => {
  if (!text) return "";
  try {
    let htmlContent = markdownToHtml(text);

    // 如果有引用信息,为引用序号添加悬浮提示
    if (grounding && grounding.length > 0) {
      htmlContent = addCitationTooltips(htmlContent, grounding);
    }

    return htmlContent;
  } catch (error) {
    console.error("Markdown 渲染失败:", error);
    return text.replace(/\n/g, "<br>");
  }
};

// 为引用序号添加悬浮提示
const addCitationTooltips = (htmlContent: string, grounding: any[]): string => {
  if (!htmlContent || !grounding || grounding.length === 0) return htmlContent;

  // 匹配引用序号格式:[1], [2], [3] 等
  // 先排除 markdown 链接格式 [text](url),只匹配纯引用序号
  const citationRegex = /\[(\d+)\]/g;

  // 先标记所有链接,避免替换链接内的内容
  const linkPlaceholders: { placeholder: string; original: string }[] = [];
  let placeholderIndex = 0;

  // 保护链接格式
  let protectedContent = htmlContent.replace(/<a[^>]*>.*?<\/a>/gi, (match) => {
    const placeholder = `__LINK_PLACEHOLDER_${placeholderIndex}__`;
    linkPlaceholders.push({ placeholder, original: match });
    placeholderIndex++;
    return placeholder;
  });

  // 在保护后的内容中替换引用序号
  protectedContent = protectedContent.replace(
    citationRegex,
    (match, indexStr) => {
      const index = parseInt(indexStr, 10) - 1; // 转换为数组索引(从0开始)

      // 检查索引是否有效
      if (index >= 0 && index < grounding.length) {
        const evidence = grounding[index];

        // 构建 tooltip 内容
        let tooltipContent = "";
        if (evidence.title) {
          tooltipContent += `<div class="citation-tooltip-title">${escapeHtml(evidence.title)}</div>`;
        }
        if (evidence.content) {
          // 限制内容长度,避免 tooltip 过大
          const content =
            evidence.content.length > 200
              ? evidence.content.substring(0, 200) + "..."
              : evidence.content;
          tooltipContent += `<div class="citation-tooltip-content">${escapeHtml(content)}</div>`;
        }

        if (tooltipContent) {
          // 创建带 tooltip 的 span,使用 data 属性存储引用索引和 URL
          const url = evidence.url || "";
          return `<span class="citation-number" data-citation-index="${index}" data-citation-url="${escapeHtml(url)}">${match}</span>`;
        }
      }

      return match;
    },
  );

  // 恢复链接
  linkPlaceholders.forEach(({ placeholder, original }) => {
    protectedContent = protectedContent.replace(placeholder, original);
  });

  return protectedContent;
};

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

// 切换思考详情展开状态
const toggleThinking = (questionId: string) => {
  if (expandedThinkings.value.has(questionId)) {
    expandedThinkings.value.delete(questionId);
  } else {
    expandedThinkings.value.add(questionId);
  }
};

// 判断思考详情是否展开
const isThinkingExpanded = (questionId: string): boolean => {
  return expandedThinkings.value.has(questionId);
};

// 判断是否为错误消息
const isErrorMessage = (answer: any): boolean => {
  // 检查状态是否为 error
  if (answer.status === "error") {
    return true;
  }

  // 检查内容是否包含错误提示
  if (answer.answerContent) {
    const content = answer.answerContent;

    // 直接检查原始内容
    if (content.includes("快问快答系统修复中...")) {
      return true;
    }

    // 移除 HTML 标签后检查纯文本内容(如果内容被 HTML 包装)
    const textContent = content
      .replace(/<[^>]*>/g, "")
      .replace(/&nbsp;/g, " ")
      .replace(/&amp;/g, "&")
      .replace(/&lt;/g, "<")
      .replace(/&gt;/g, ">")
      .trim();
    if (textContent.includes("快问快答系统修复中...")) {
      return true;
    }
  }

  return false;
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesArea.value) {
      messagesArea.value.scrollTop = messagesArea.value.scrollHeight;
    }
  });
};

// 发送消息
const handleSubmit = async (content: string) => {
  if (!content.trim() || isSending.value) return;
  try {
    // 先获取领医豆余额和服务单价
    const balanceResponse = await getBeansBalance();
    const balance = balanceResponse.data.balance;

    const priceResponse = await getServicePrice({ serviceTypeId: 1 });
    const servicePrice = priceResponse.data;

    // 判断领医豆余额是否大于服务单价
    if (balance < servicePrice) {
      ElMessage.error("领医豆余额不足,无法使用该服务");
      return;
    }

    // 发送消息到百川模型后,消费领医豆
    const question = content.trim();
    // 截断 question,最多 200 个字符(用于发送消息)
    const questionForMessage =
      question.length > 200 ? question.substring(0, 200) : question;
    isSending.value = true;
    // 如果没有当前会话,先创建一个
    let sessionId = props.currentSession?.id;
    if (!sessionId) {
      // 使用用户输入的问题作为会话名称(完整内容)
      const result = await chatApiStore.createSession(question);
      if (result.success && result.data) {
        sessionId = result.data.id;
        emit("session-created", result.data);
      } else {
        throw new Error(result.error || "创建会话失败");
      }
    }
    // 发送消息(Welcome.vue 主页默认使用百川模型)
    const result = await chatApiStore.sendMessage({
      sessionId,
      question: questionForMessage,
      context: [],
      provider: "baichuan", // Welcome.vue 主页默认使用 baichuan
    });
    // 通知父组件刷新左侧历史/任务列表(需要 provider 来区分)
    emit("message-sent", {
      questionId: result.data?.questionId,
      provider: "baichuan",
    });
    if (result.success) {
      scrollToBottom();
    } else {
      throw new Error(result.error || "发送消息失败");
    }
    // 消费领医豆
    try {
      await consumeBeans({
        serviceType: "快问快答",
        beanQuantity: servicePrice,
        agentTaskId: result.data?.questionId,
      });
    } catch (consumeError) {
      console.error("消费领医豆失败:", consumeError);
    }
  } catch (error: any) {
    console.error("[BaichuanChat] 发送失败:", error);
    ElMessage.error(error.message || "发送失败,请重试");
  }
};

const handleStop = () => {
  chatApiStore.closeAllEventSources();
  ElMessage.info(t("chat.stopStreaming") || "已中止当前生成");
};

// 处理复制
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) {
    try {
      const textArea = document.createElement("textarea");
      textArea.value = content;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      ElMessage.success(t("chat.contentCopied") || "内容已复制到剪贴板");
    } catch (fallbackError) {
      console.error("降级复制也失败:", fallbackError);
      ElMessage.error(t("chat.copyFailed") || "复制失败,请手动复制");
    }
  }
};

// 处理复制用户问题
const handleCopyQuestion = async (message: any) => {
  await handleCopy(message.question);
};

// 处理复制回答
const handleCopyAnswer = async (answer: any) => {
  if (!answer.answerContent) {
    ElMessage.warning(t("chat.noContentToCopy") || "没有可复制的内容");
    return;
  }

  // 构建复制内容
  let copyContent = answer.answerContent;

  // 如果有引用,添加到复制内容中
  if (answer.grounding && answer.grounding.length > 0) {
    copyContent += "\n\n参考文献:\n";
    answer.grounding.forEach((evidence: any, idx: number) => {
      copyContent += `\n[${idx + 1}] ${evidence.title || "未命名引用"}\n`;
      if (evidence.content) {
        copyContent += `${evidence.content}\n`;
      }
      if (evidence.url) {
        copyContent += `${evidence.url}\n`;
      }
    });
  }

  await handleCopy(copyContent);
};

// 处理保存并编辑
const handleSaveAndEdit = async (message: any, answer: any) => {
  try {
    if (!answer.answerContent) {
      ElMessage.warning("暂无内容可保存");
      return;
    }
    // 检查回答是否完成
    if (!answer.isComplete) {
      ElMessage.warning("回答尚未完成,请稍候");
      return;
    }
    if (!message.questionId) {
      ElMessage.error("缺少问题ID,无法保存");
      return;
    }
    if (!props.currentSession) {
      ElMessage.error("缺少会话信息,无法保存");
      return;
    }
    try {
      // 1. 获取文件名 (前20个字符)
      let title = message.question || "未命名文档";
      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 apiCreateDraftFromQuestion(message.questionId, {
        title,
      });
      console.log("保存响应:", response);

      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. 添加到对话框引用 (Baichuan 目前不直接支持在输入框显示文件引用)
          // 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) {
    console.error("保存并编辑失败:", error);
    ElMessage.error("操作失败,请重试");
  }
};

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

  try {
    console.log("准备在工作台中打开文件:", fileInfo);

    // 先下载文件内容,确保文件可以正常访问
    let fileContent = fileInfo.preloadContent || "";
    try {
      if (!fileContent) {
        console.log("开始下载文件内容,fileId:", fileInfo.id);
        if (fileInfo.isDraft === false) {
          // 统一使用常规文件 API
          const contentResponse = await getFileContent(fileInfo.id);
          fileContent = contentResponse.data;
          console.log("文件内容下载成功,内容长度:", fileContent.length);
        }
      } else {
        console.log("使用预传递的文件内容,内容长度:", fileContent.length);
      }
    } catch (downloadError) {
      console.error("下载文件内容失败:", downloadError);
      // 如果下载失败,仍然尝试跳转,让工作台组件自己处理
      ElMessage.warning("文件内容预加载失败,将尝试在工作台中加载");
    }

    // 构建跳转参数,包含文件内容
    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("打开编辑器失败,请重试");
  } finally {
    loading.close();
  }
};

// 执行路由跳转的辅助方法
const performRouterNavigation = async (params: any) => {
  try {
    console.log("开始执行路由跳转,参数:", params);

    // 首先尝试使用路由名称跳转
    try {
      await router.push({
        name: "Workspace",
        query: params,
      });
      console.log("使用路由名称跳转成功");
      return;
    } catch (nameError) {
      console.warn("路由名称跳转失败:", nameError);
    }

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

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

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

    // 如果所有Vue Router方式都失败,显示错误信息
    console.error("所有路由跳转方式都失败");
    ElMessage.error("无法跳转到工作台页面");

    // 可选:提供手动跳转的提示
    const queryString = new URLSearchParams(params).toString();
    const targetUrl = `#/app/workspace?${queryString}`;
    console.log("如需手动跳转,请访问:", targetUrl);
  } catch (error) {
    console.error("路由跳转过程中发生错误:", error);
    ElMessage.error("跳转失败,请重试");
  }
};

// 用于跟踪已完成的回答,避免重复触发
const completedAnswers = ref<Set<string>>(new Set());

// 监听消息变化,自动滚动和展开引用
watch(
  () => messages.value,
  (newMessages) => {
    // 消息变化时关闭参考文献弹窗
    hideCitationModal();

    // 检测回答是否完成
    newMessages.forEach((msg) => {
      if (msg.answers) {
        msg.answers.forEach((answer) => {
          // 检测回答是否完成
          if (answer.isComplete && answer.id) {
            const answerId = answer.id;
            // 如果这个回答之前没有被标记为完成,则触发刷新事件
            if (!completedAnswers.value.has(answerId)) {
              completedAnswers.value.add(answerId);
              // 触发事件通知父组件刷新历史列表
              emit("answer-completed", {
                questionId: msg.questionId,
                answerId: answerId,
              });
            }
          }
        });
      }
    });
    // scrollToBottom();
  },
  { deep: true },
);

// 获取服务价格
const fetchServicePrice = async () => {
  try {
    const response = await getServicePrice({ serviceTypeId: 1 });
    servicePrice.value = response.data;
  } catch (error) {
    console.error("获取服务价格失败:", error);
    servicePrice.value = null;
  }
};

// 清理函数
let cleanupCitationTooltips: (() => void) | null = null;

// 组件挂载时处理初始消息
onMounted(async () => {
  // 设置引用序号点击弹窗的事件监听
  cleanupCitationTooltips = setupCitationTooltips();

  // 初始化时获取服务价格
  await fetchServicePrice();

  if (props.initialMessage) {
    await nextTick();
    await handleSubmit(props.initialMessage);
  }
});

// 组件卸载时清理
onUnmounted(() => {
  // 清理引用弹窗事件监听
  if (cleanupCitationTooltips) {
    cleanupCitationTooltips();
    cleanupCitationTooltips = null;
  }
  // 清理弹窗元素
  hideCitationModal();
});

// 设置引用序号点击弹窗
let citationModalElement: HTMLElement | null = null;
let citationClickOutsideHandler: ((event: MouseEvent) => void) | null = null;
let citationScrollHandler: (() => void) | null = null;

let citationClickHandler: ((event: MouseEvent) => void) | null = null;

const setupCitationTooltips = () => {
  const handleClick = (event: MouseEvent) => {
    const target = event.target as HTMLElement;
    const citationNumber = target.closest(".citation-number") as HTMLElement;

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

      const citationIndex = citationNumber.getAttribute("data-citation-index");
      if (citationIndex !== null) {
        // 找到对应的 answer 和 grounding
        const markdownBody = citationNumber.closest(".markdown-body");
        if (markdownBody) {
          const answerContent = markdownBody.closest(".answer-content");
          if (answerContent) {
            const aiMessage = answerContent.closest(".ai-message");
            if (aiMessage) {
              const messageGroup = aiMessage.closest(".message-group");
              if (messageGroup) {
                // 通过消息索引找到对应的 message
                const messageGroups = Array.from(
                  document.querySelectorAll(".message-group"),
                );
                const groupIndex = messageGroups.indexOf(messageGroup);
                if (groupIndex >= 0 && groupIndex < messages.value.length) {
                  const message = messages.value[groupIndex];
                  if (message && message.answers) {
                    // 找到包含这个 markdown-body 的 answer
                    const aiMessages = Array.from(
                      messageGroup.querySelectorAll(".ai-message"),
                    );
                    const answerIndex = aiMessages.indexOf(aiMessage);
                    const answer = message.answers[answerIndex];

                    if (answer && answer.grounding) {
                      const index = parseInt(citationIndex, 10);
                      if (index >= 0 && index < answer.grounding.length) {
                        showCitationModal(
                          citationNumber,
                          answer.grounding[index],
                        );
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  };

  citationClickHandler = handleClick;

  // 监听整个消息区域的点击事件
  if (messagesArea.value) {
    messagesArea.value.addEventListener("click", handleClick);
  }

  // 返回清理函数
  return () => {
    if (messagesArea.value && citationClickHandler) {
      messagesArea.value.removeEventListener("click", citationClickHandler);
      citationClickHandler = null;
    }
  };
};

// 显示引用弹窗
const showCitationModal = (target: HTMLElement, evidence: any) => {
  // 立即同步移除已存在的弹窗(不延迟)
  if (citationClickOutsideHandler) {
    document.removeEventListener("click", citationClickOutsideHandler);
    citationClickOutsideHandler = null;
  }
  // 移除旧的滚动事件监听
  if (citationScrollHandler) {
    window.removeEventListener("scroll", citationScrollHandler, true);
    if (messagesArea.value) {
      messagesArea.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">
  `;

  // 引用标题
  if (evidence.title) {
    modalHTML += `<div class="citation-modal-citation">${escapeHtml(evidence.title)}</div>`;
  }

  // 引用内容摘要
  if (evidence.content) {
    const content =
      evidence.content.length > 500
        ? evidence.content.substring(0, 500) + "..."
        : evidence.content;
    modalHTML += `<div class="citation-modal-summary">${escapeHtml(content)}</div>`;
  }

  modalHTML += `</div>`;

  // 查看原文按钮
  if (evidence.url) {
    modalHTML += `
      <div class="citation-modal-footer">
        <a href="${escapeHtml(evidence.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 (messagesArea.value) {
      messagesArea.value.removeEventListener("scroll", citationScrollHandler);
    }
  }

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

  // 监听窗口滚动和消息区域滚动
  window.addEventListener("scroll", citationScrollHandler, true);
  if (messagesArea.value) {
    messagesArea.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 (messagesArea.value) {
      messagesArea.value.removeEventListener("scroll", citationScrollHandler);
    }
    citationScrollHandler = null;
  }

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

<style lang="scss" scoped>
.baichuan-chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background: var(--color-bg, #f5f5f5);
}

.messages-area {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;

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

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

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

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

.message-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
  width: 100%;
  max-width: 800px;
}

.message-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  width: 100%;

  &.user-message {
    flex-direction: row-reverse;
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    .message-content {
      background: var(--color-card);
      color: var(--user-question-text);
      border-radius: 8px;
      max-width: 100%;
      word-wrap: break-word;
      font-size: 14px;
      line-height: 1.5;
      white-space: pre-wrap;
      transition: background-color 0.2s ease;
      position: relative;
    }
  }

  &.ai-message {
    .message-content-wrapper {
      flex: 1;
      display: flex;
      flex-direction: column;
      width: 100%;
    }
  }
}

.message-content {
  padding: 12px 16px;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
}

.thinking-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

// 思考加载动画(三个点)
.thinking-loading {
  display: flex;
  align-items: center;
  gap: 12px;
}

.thinking-dots {
  display: flex;
  align-items: center;
  gap: 6px;

  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #1890ff;
    animation: thinking-dot 1.4s infinite ease-in-out both;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }

    &:nth-child(2) {
      animation-delay: -0.16s;
    }

    &:nth-child(3) {
      animation-delay: 0s;
    }
  }
}

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

.thinking-text {
  font-size: 13px;
  color: var(--color-text-secondary, #666);
  font-weight: 500;
}

// 思考进行中(有步骤)
.thinking-progress {
  overflow: hidden;
}

.thinking-steps-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.thinking-step-item {
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s;

  .step-icon {
    font-size: 15px;
    flex-shrink: 0;

    &.fa-check-circle {
      color: #52c41a;
    }

    &.fa-spinner {
      color: #1890ff;
    }
  }

  .step-label {
    flex: 1;
    font-size: 14px;
    color: var(--color-text, #333);
    line-height: 1.6;
  }
}

// 完成思考(可折叠)
.thinking-completed {
  overflow: hidden;
}

.thinking-completed-header {
  display: flex;
  justify-self: flex-start;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  transition: background 0.2s;
  user-select: none;

  i.fa-check-circle {
    color: #52c41a;
    font-size: 15px;
  }

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

  .toggle-icon {
    color: var(--color-text-secondary, #999);
    transition: transform 0.2s;
    font-size: 12px;

    &.expanded {
      transform: rotate(180deg);
    }
  }
}

.thinking-steps-completed {
  padding-top: 10px;
  display: flex;
  flex-direction: column;
}

.thinking-step-completed {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px 14px;
  background: var(--color-bg, #fafafa);
  border-radius: 6px;

  .step-icon-completed {
    font-size: 15px;
    color: #52c41a;
    flex-shrink: 0;
  }

  .step-label-completed {
    flex: 1;
    font-size: 14px;
    color: var(--color-text, #333);
    line-height: 1.6;
  }
}

.markdown-body {
  font-size: 14px;
  line-height: 1.8;
  color: var(--color-text, #333);

  :deep(h1),
  :deep(h2),
  :deep(h3),
  :deep(h4),
  :deep(h5),
  :deep(h6) {
    font-weight: bold !important;
    margin: 16px 0 8px 0 !important;
    line-height: 1.3 !important;
    display: block !important;
  }

  :deep(h1) {
    font-size: 1.5em !important;
  }

  :deep(h2) {
    font-size: 1.3em !important;
  }

  :deep(h3) {
    font-size: 1.2em !important;
  }

  :deep(h4) {
    font-size: 1.1em !important;
  }

  :deep(h5) {
    font-size: 1em !important;
  }

  :deep(h6) {
    font-size: 0.9em !important;
  }

  :deep(p) {
    margin: 8px 0 !important;
    line-height: 1.6 !important;
    white-space: normal !important;
    display: block !important;
  }

  :deep(strong) {
    font-weight: bold !important;
  }

  :deep(em) {
    font-style: italic !important;
  }

  :deep(ul),
  :deep(ol) {
    margin: 8px 0 !important;
    padding-left: 20px !important;
    display: block !important;
    white-space: normal !important;
  }

  :deep(li) {
    margin: 4px 0 !important;
    line-height: 1.5 !important;
    white-space: normal !important;
    display: list-item !important;
    list-style: disc !important;
  }

  :deep(blockquote) {
    margin: 16px 0 !important;
    padding: 8px 16px !important;
    border-left: 4px solid var(--color-primary, #2871f6) !important;
    background: rgba(40, 113, 246, 0.05) !important;
    font-style: italic !important;
  }

  :deep(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: 0.9em !important;
  }

  :deep(pre) {
    background: rgba(40, 113, 246, 0.05) !important;
    padding: 12px !important;
    border-radius: 6px !important;
    overflow-x: auto !important;
    margin: 12px 0 !important;

    code {
      background: none !important;
      padding: 0 !important;
    }
  }

  :deep(table) {
    border-collapse: collapse !important;
    width: 100% !important;
    margin: 12px 0 !important;
  }

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

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

  :deep(a) {
    color: var(--color-primary, #2871f6) !important;
    text-decoration: none !important;

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

  :deep(hr) {
    border: none !important;
    border-top: 1px solid var(--color-border, #e0e0e0) !important;
    margin: 16px 0 !important;
  }

  // 引用序号样式 - 确保大小一致
  :deep(.citation-number) {
    font-size: inherit !important;
    display: inline !important;
    vertical-align: baseline !important;
    line-height: inherit !important;
  }
}

// 回答内容为空提示样式
.empty-answer-hint {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 8px;
  color: #ad6800;
  font-size: 14px;
  line-height: 1.6;

  i {
    font-size: 16px;
    color: #faad14;
    flex-shrink: 0;
  }

  span {
    flex: 1;
  }
}

// 错误消息样式
.answer-content .error-message-wrapper {
  display: flex !important;
  align-items: flex-start;
  gap: 12px;
  padding: 2px 16px !important;
  background: #fff7e6 !important;
  border: 1px solid #ffd591 !important;
  border-left: 4px solid #fa8c16 !important;
  border-radius: 8px;
  margin: 8px 0;
  width: 100%;
  box-sizing: border-box;

  .error-icon {
    font-size: 18px;
    color: #fa8c16 !important;
    flex-shrink: 0;
    margin-top: 10px;
  }

  .error-message-content {
    flex: 1;
    color: #d46b08 !important;
    font-size: 14px;
    line-height: 1.6;

    :deep(p),
    :deep(span),
    :deep(div) {
      color: #d46b08 !important;
    }
  }
}

.grounding-section {
  overflow: hidden;
}

.grounding-header {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: background 0.2s;
  user-select: none;
  margin-top: 10px;

  i.fa-quote-left {
    color: #1890ff;
    font-size: 14px;
  }

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

  .toggle-icon {
    color: var(--color-text-secondary, #999);
    transition: transform 0.2s;
    font-size: 12px;

    &.expanded {
      transform: rotate(180deg);
    }
  }
}

/* 内联引用样式 - 直接显示在回答内容之后 */
.grounding-section-inline {
  margin: 16px 0;
  padding-top: 24px;
  border-top: 1px solid var(--color-border, #e5e7eb);
}

.grounding-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--color-text, #333);
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 8px;

  &::before {
    content: "";
    display: inline-block;
    width: 4px;
    height: 16px;
    background: #1890ff;
    border-radius: 2px;
  }
}

.grounding-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.evidence-item-inline {
  padding: 0;
  line-height: 1.8;
}

.evidence-header-inline {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 8px;
}

.evidence-index-inline {
  color: #1890ff;
  font-weight: 600;
  font-size: 14px;
  flex-shrink: 0;
}

.evidence-title-inline {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text, #333);
  flex: 1;
  word-wrap: break-word;
  word-break: break-word;
}

.evidence-content-inline {
  font-size: 13px;
  line-height: 1.7;
  color: var(--color-text-secondary, #666);
  margin-bottom: 8px;
  padding-left: 24px;
  word-wrap: break-word;
  word-break: break-word;
}

.evidence-url-inline {
  font-size: 12px;
  padding-left: 24px;
  max-width: 800px;
  overflow: hidden;

  a {
    color: #1890ff;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: color 0.2s;
    max-width: 100%;
    word-break: break-all;
    overflow-wrap: break-word;

    &:hover {
      color: #40a9ff;
      text-decoration: underline;
    }

    i {
      font-size: 11px;
      flex-shrink: 0;
    }
  }
}

.grounding-content {
  display: flex;
  flex-direction: column;
  margin-top: 15px;
}

.evidence-item {
  padding: 14px 0px;
  transition: all 0.2s;

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

.evidence-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 5px;
}

.evidence-index {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--color-text, #333);
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.evidence-title {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text, #333);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.evidence-content {
  font-size: 13px;
  line-height: 1.7;
  color: var(--color-text-secondary, #666);
  margin-bottom: 5px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  padding-left: 22px;
}

.evidence-url {
  font-size: 12px;
  padding-left: 22px;

  a {
    color: #1890ff;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: color 0.2s;

    &:hover {
      color: #40a9ff;
      text-decoration: underline;
    }

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

/* 工具图标 */
.message-tools {
  display: flex;
  flex-wrap: wrap;
  column-gap: 12px;

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

    &:hover {
      opacity: 1;
    }

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

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--color-text-secondary, #999);
  gap: 12px;

  i {
    font-size: 48px;
    opacity: 0.3;
  }

  p {
    font-size: 14px;
  }
}

.input-area {
  padding-bottom: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

/* AI 生成内容提示 */
.ai-generated-disclaimer {
  margin-top: 6px;
  font-size: 12px;
  color: #9ca3af;
  text-align: center;
  line-height: 1.5;
}

// 深色主题适配
:root.theme-dark {
  .message-content {
    background: var(--color-card, #1f1f1f);
    color: var(--color-text, #e0e0e0);
  }

  .thinking-loading {
    background: var(--color-card, #1f1f1f);

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

  .thinking-progress {
    background: var(--color-card, #1f1f1f);
    border-color: var(--color-border, #333);
  }

  .thinking-step-item {
    .step-label {
      color: var(--color-text, #e0e0e0);
    }
  }

  .thinking-completed {
    background: var(--color-card, #1f1f1f);
    border-color: var(--color-border, #333);
  }

  .thinking-completed-header {
    background: var(--color-bg, #151515);

    span {
      color: var(--color-text, #e0e0e0);
    }
  }

  .thinking-step-completed {
    background: var(--color-bg, #151515);

    .step-label-completed {
      color: var(--color-text, #e0e0e0);
    }
  }

  .answer-content {
    background: var(--color-card, #1f1f1f);
  }

  .empty-answer-hint {
    background: rgba(255, 193, 7, 0.1);
    border-color: rgba(255, 193, 7, 0.3);
    color: #ffc107;

    i {
      color: #ffc107;
    }
  }

  .answer-content .error-message-wrapper {
    background: rgba(250, 140, 22, 0.15) !important;
    border-color: rgba(250, 140, 22, 0.4) !important;
    border-left-color: #fa8c16 !important;

    .error-icon {
      color: #ffa940 !important;
    }

    .error-message-content {
      color: #ffa940 !important;

      :deep(p),
      :deep(span),
      :deep(div) {
        color: #ffa940 !important;
      }
    }
  }

  .grounding-section {
    background: var(--color-card, #1f1f1f);
    border-color: var(--color-border, #333);
  }

  .grounding-header {
    background: var(--color-bg, #151515);
  }

  .evidence-item {
    background: var(--color-bg, #151515);
  }
}
</style>

<!-- 全局 Markdown 样式 - 不使用 scoped 以确保正确渲染 -->
<style>
/* 全局 Markdown 样式 - 确保优先级 */
.baichuan-chat-container .markdown-body h1,
.baichuan-chat-container .markdown-body h2,
.baichuan-chat-container .markdown-body h3,
.baichuan-chat-container .markdown-body h4,
.baichuan-chat-container .markdown-body h5,
.baichuan-chat-container .markdown-body h6 {
  font-weight: bold !important;
  margin: 16px 0 8px 0 !important;
  line-height: 1.3 !important;
  display: block !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body h1 {
  font-size: 1.5em !important;
}
.baichuan-chat-container .markdown-body h2 {
  font-size: 1.3em !important;
}
.baichuan-chat-container .markdown-body h3 {
  font-size: 1.2em !important;
}
.baichuan-chat-container .markdown-body h4 {
  font-size: 1.1em !important;
}
.baichuan-chat-container .markdown-body h5 {
  font-size: 1em !important;
}
.baichuan-chat-container .markdown-body h6 {
  font-size: 0.9em !important;
}

.baichuan-chat-container .markdown-body strong {
  font-weight: bold !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body ul,
.baichuan-chat-container .markdown-body ol {
  margin: 8px 0 !important;
  padding-left: 20px !important;
  display: block !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body li {
  display: list-item !important;
  list-style: disc !important;
  margin: 4px 0 !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body p {
  margin: 8px 0 !important;
  line-height: 1.6 !important;
  display: block !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body 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: 0.9em !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body pre {
  background: rgba(40, 113, 246, 0.05) !important;
  padding: 12px !important;
  border-radius: 6px !important;
  overflow-x: auto !important;
  margin: 12px 0 !important;
}

.baichuan-chat-container .markdown-body pre code {
  background: none !important;
  padding: 0 !important;
}

.baichuan-chat-container .markdown-body blockquote {
  margin: 16px 0 !important;
  padding: 8px 16px !important;
  border-left: 4px solid var(--color-primary, #2871f6) !important;
  background: rgba(40, 113, 246, 0.05) !important;
  font-style: italic !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body table {
  border-collapse: collapse !important;
  width: 100% !important;
  margin: 12px 0 !important;
}

.baichuan-chat-container .markdown-body th,
.baichuan-chat-container .markdown-body td {
  border: 1px solid var(--color-border, #e0e0e0) !important;
  padding: 8px 12px !important;
  text-align: left !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body th {
  background: rgba(40, 113, 246, 0.1) !important;
  font-weight: 600 !important;
}

.baichuan-chat-container .markdown-body a {
  color: var(--color-primary, #2871f6) !important;
  text-decoration: none !important;
}

.baichuan-chat-container .markdown-body a:hover {
  text-decoration: underline !important;
}

.baichuan-chat-container .markdown-body em {
  font-style: italic !important;
}

.baichuan-chat-container .markdown-body hr {
  border: none !important;
  border-top: 1px solid var(--color-border, #e0e0e0) !important;
  margin: 16px 0 !important;
}

/* KaTeX 数学公式样式 */
.baichuan-chat-container .markdown-body .katex {
  font-size: 1.1em !important;
  color: inherit !important;
}

.baichuan-chat-container .markdown-body .katex-display {
  margin: 16px 0 !important;
  overflow-x: auto !important;
  overflow-y: hidden !important;
}

.baichuan-chat-container .markdown-body .katex-display > .katex {
  display: inline-block !important;
  text-align: initial !important;
}

/* 引用序号样式 */
.baichuan-chat-container .markdown-body .citation-number {
  color: #1890ff !important;
  cursor: pointer !important;
  font-weight: 500 !important;
  font-size: inherit !important;
  display: inline !important;
  vertical-align: baseline !important;
  line-height: inherit !important;
  transition: all 0.2s !important;
  padding: 1px 2px !important;
  border-radius: 2px !important;
}

.baichuan-chat-container .markdown-body .citation-number:hover {
  color: #40a9ff !important;
  background-color: rgba(24, 144, 255, 0.1) !important;
}

.baichuan-chat-container .markdown-body .citation-number:active {
  color: #096dd9 !important;
  background-color: rgba(24, 144, 255, 0.2) !important;
}

/* 引用弹窗样式 */
.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 16px;
  max-height: 400px;
  overflow-y: auto;
}

.citation-modal-citation {
  font-size: 14px;
  line-height: 1.6;
  color: var(--color-text, #e0e0e0);
  margin-bottom: 12px;
  word-wrap: break-word;
  font-weight: 500;
}

.citation-modal-summary {
  font-size: 13px;
  line-height: 1.7;
  color: #4b5563;
  word-wrap: break-word;
}

.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-citation {
    color: #e0e0e0;
  }

  .citation-modal-summary {
    color: #aaa;
  }

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