chat.html 42.2 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 印刷助手</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .chat-container {
            width: 100%;
            max-width: 900px;
            height: 85vh;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.15);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .chat-header {
            background: linear-gradient(90deg, #2c3e50, #4a6491);
            color: white;
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-shrink: 0;
        }

        .header-left h1 {
            font-size: 24px;
            font-weight: 600;
            margin-bottom: 5px;
        }

        .header-left p {
            opacity: 0.8;
            font-size: 14px;
        }

        .header-right {
            display: flex;
            gap: 15px;
        }

        .model-selector {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            color: #180a4b;
            padding: 8px 15px;
            border-radius: 20px;
            font-size: 14px;
            outline: none;
            cursor: pointer;
        }

        .model-selector:hover {
            background: rgba(255,255,255,0.2);
        }

        .chat-body {
            display: flex;
            flex: 1;
            overflow: hidden;
            min-height: 0;
        }

        .sidebar {
            width: 250px;
            background: #f8f9fa;
            border-right: 1px solid #e9ecef;
            padding: 20px;
            overflow-y: auto;
            flex-shrink: 0;
        }

        .sidebar-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #2c3e50;
        }

        .preset-question {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 10px;
            padding: 12px 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
        }

        .preset-question:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
            transform: translateX(5px);
        }

        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
        }

        .messages-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            min-height: 0;
            position: relative;
        }

        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: white;
        }

        .message {
            margin-bottom: 20px;
            max-width: 80%;
            animation: fadeIn 0.3s ease;
        }

        .user-message {
            margin-left: auto;
        }

        .ai-message {
            margin-right: auto;
        }

        .message-bubble {
            padding: 15px 20px;
            border-radius: 20px;
            position: relative;
            word-wrap: break-word;
            line-height: 1.6;
        }

        .user-message .message-bubble {
            background: linear-gradient(90deg, #667eea, #764ba2);
            color: white;
            border-bottom-right-radius: 5px;
        }

        .ai-message .message-bubble {
            background: #f8f9fa;
            color: #333;
            border: 1px solid #e9ecef;
            border-bottom-left-radius: 5px;
        }

        .message-content {
            font-size: 15px;
        }

        .ai-message .message-content code {
            background: #e9ecef;
            padding: 2px 6px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }

        .ai-message .message-content pre {
            background: #f1f3f5;
            padding: 10px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 10px 0;
            border: 1px solid #dee2e6;
        }

        .message-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 8px;
            font-size: 12px;
        }

        .message-time {
            color: #6c757d;
        }

        .message-actions {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            background: none;
            border: none;
            color: #6c757d;
            cursor: pointer;
            font-size: 12px;
            padding: 2px 5px;
            border-radius: 3px;
            transition: all 0.2s;
        }

        .action-btn:hover {
            background: #e9ecef;
            color: #495057;
        }

        .typing-indicator {
            display: flex;
            align-items: center;
            padding: 10px 20px;
            background: #f8f9fa;
            border-radius: 20px;
            width: fit-content;
            border: 1px solid #e9ecef;
            margin-bottom: 20px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: #667eea;
            border-radius: 50%;
            margin: 0 2px;
            animation: typing 1.4s infinite;
        }

        .typing-dot:nth-child(2) { animation-delay: 0.2s; }
        .typing-dot:nth-child(3) { animation-delay: 0.4s; }

        .input-section {
            border-top: 1px solid #e9ecef;
            background: white;
            flex-shrink: 0;
        }

        .chat-input-container {
            padding: 20px;
        }

        .input-wrapper {
            display: flex;
            gap: 10px;
        }

        #messageInput {
            flex: 1;
            padding: 15px 20px;
            border: 2px solid #e9ecef;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }

        #messageInput:focus {
            border-color: #667eea;
        }

        #sendButton {
            padding: 15px 30px;
            background: linear-gradient(90deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 25px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
            white-space: nowrap;
        }

        #sendButton:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        #sendButton:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .status-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 20px;
            font-size: 14px;
            color: #666;
            background: #f8f9fa;
            border-top: 1px solid #e9ecef;
        }

        .api-status {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .status-indicator {
            width: 8px;
            height: 8px;
            border-radius: 50%;
        }

        .status-connected {
            background: #28a745;
            animation: pulse 2s infinite;
        }

        .status-disconnected {
            background: #dc3545;
        }

        .status-connecting {
            background: #ffc107;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-10px); }
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        /* 滚动条样式 */
        .chat-messages::-webkit-scrollbar,
        .sidebar::-webkit-scrollbar {
            width: 6px;
        }

        .chat-messages::-webkit-scrollbar-track,
        .sidebar::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .chat-messages::-webkit-scrollbar-thumb,
        .sidebar::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }

        .chat-messages::-webkit-scrollbar-thumb:hover,
        .sidebar::-webkit-scrollbar-thumb:hover {
            background: #a1a1a1;
        }

        /* 底部间隔 */
        .bottom-spacer {
            height: 20px;
            flex-shrink: 0;
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .chat-container {
                height: 95vh;
                border-radius: 10px;
            }

            .sidebar {
                display: none;
            }

            .message {
                max-width: 90%;
            }

            #sendButton {
                padding: 15px 20px;
            }

            .header-right {
                flex-direction: column;
                gap: 8px;
            }
        }
    </style>
</head>
<body>
<div class="chat-container">
    <div class="chat-header">
        <div class="header-left">
            <h1>小羚羊Ai-agent智能体</h1>
        </div>
        <div class="header-right">
            <select class="model-selector" id="modelSelector">
                <option value="process">小羚羊印刷行业大模型</option>
                <option value="general">qwen2.5:14b</option>
            </select>
            <button class="model-selector" onclick="newConversation()">新建会话</button>
        </div>
    </div>

    <div class="chat-body">
        <div class="sidebar">
            <div class="sidebar-title">会话</div>
            <button class="preset-question" style="text-align:center;font-weight:600;background:#eef;" onclick="newConversation()">+ 新建会话</button>
            <div id="convList"></div>
        </div>
        <div class="chat-main">
            <div class="messages-container">
                <div class="chat-messages" id="chatMessages">
                    <!-- 初始欢迎消息 -->
                    <div class="message ai-message">
                        <div class="message-bubble">
                            <div class="message-content" id="ts">
                                <strong></strong><br><br>
                            </div>
                            <div class="message-meta">
                                <span class="message-time" id="welcomeTime"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="input-section">
                <div class="chat-input-container">
                    <div class="input-wrapper">
                        <input type="text" id="messageInput" placeholder="输入您的问题..." autocomplete="off">
                        <audio id="audioPlayer" controls hidden="hidden"></audio>
                        <button id="sendButton" onclick="sendMessage()">发送</button>
                        <button id="reset" onclick="reset('重置')">重置</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let sessionId ="";
    let conversationId = "c-" + Date.now() + "-" + Math.random().toString(36).slice(2, 8);
    let userid= "17522967560005776104370282597000";
    let username= "qianb";
    let brandsid= "1111111111";
    let subsidiaryid= "1111111111";
    let usertype= "sysadmin";
    // ERP 登录 token(透传给后端 → 转发给 ERP,用于按真实用户身份读写;绝不进 prompt)。
    // 本地独立聊天页无浏览器登录流程,留空 → 后端回退 dev-login(admin)读写;
    // 生产环境由 ERP 外壳把用户的实时有效 token 注入这里,即启用逐用户 token 透传 + 表单权限收紧。
    let authorization="";
    let hrefLock = window.location.origin+"/xlyAi";

    const CONFIG = {
        backendUrl: hrefLock,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        maxHistory: 20,
    };

    let chatHistory = [];
    let audioQueue = [];
    let isPlaying = false;

    let currentModel = 'general';
    const md = window.markdownit({
        html: true,
        linkify: true,
        typographer: true
    });

    $(document).ready(function() {
        document.getElementById('welcomeTime').textContent = getCurrentTime();
        $('#messageInput').focus();
        bindKeyboardEvents();
        ensureInputAtBottom();
        initConversations();
    });

    // ====================== 多命名会话(侧栏) ======================
    function convApi(path, opts) {
        return fetch(CONFIG.backendUrl + '/api/agent/conversations' + path, opts || {});
    }

    async function initConversations() {
        try {
            const res = await convApi('?userid=' + encodeURIComponent(userid));
            const list = await res.json();
            renderConvList(list);
            if (list && list.length > 0) {
                await switchConversation(list[0].id);
            }
        } catch (e) { console.log('会话初始化失败', e); }
    }

    async function loadConversations() {
        try {
            const res = await convApi('?userid=' + encodeURIComponent(userid));
            renderConvList(await res.json());
        } catch (e) { /* ignore */ }
    }

    function renderConvList(list) {
        const box = $('#convList');
        box.empty();
        (list || []).forEach(c => {
            const isActive = c.id === conversationId;
            const item = $('<div class="preset-question conv-item"></div>')
                .css({display:'flex', justifyContent:'space-between', alignItems:'center', gap:'6px'});
            if (isActive) item.css({background:'#667eea', color:'#fff', borderColor:'#667eea'});
            const title = $('<span></span>').text(c.title || '会话')
                .css({flex:'1', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'});
            const del = $('<span title="删除">×</span>').css({cursor:'pointer', fontWeight:'bold', opacity:'0.6'});
            title.on('click', () => switchConversation(c.id));
            del.on('click', (ev) => { ev.stopPropagation(); deleteConversation(c.id); });
            item.append(title).append(del);
            box.append(item);
        });
    }

    async function switchConversation(convId) {
        if (convId === conversationId) return;
        conversationId = convId;
        $('#chatMessages').empty();
        try {
            const res = await convApi('/' + convId + '/messages');
            const msgs = await res.json();
            (msgs || []).forEach(m => addMessage(m.content, m.role === 'user' ? 'user' : 'ai'));
            if (!msgs || msgs.length === 0) addMessage('(空会话)请提问。', 'ai');
        } catch (e) { console.log('加载历史失败', e); }
        renderConvList(await (await convApi('?userid=' + encodeURIComponent(userid))).json());
        ensureInputAtBottom();
    }

    async function newConversation() {
        try {
            const res = await convApi('', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({userid: userid}) });
            conversationId = (await res.json()).conversationId;
        } catch (e) {
            conversationId = 'c-' + Date.now() + '-' + Math.random().toString(36).slice(2,8);
        }
        $('#chatMessages').empty();
        addMessage('新会话已开始,请提问。', 'ai');
        loadConversations();
        $('#messageInput').focus();
    }

    async function deleteConversation(convId) {
        if (!confirm('删除这个会话?')) return;
        try { await convApi('/' + convId + '?userid=' + encodeURIComponent(userid), { method:'DELETE' }); } catch (e) {}
        if (convId === conversationId) {
            conversationId = 'c-' + Date.now() + '-' + Math.random().toString(36).slice(2,8);
            $('#chatMessages').empty();
            addMessage('会话已删除,可新建或选择其它会话。', 'ai');
        }
        loadConversations();
    }

    function generateRandomString(length) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let result = '';
        for (let i = 0; i < length; i++) {
            result += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return result;
    }

    window.onload = function(){
        $("#ts").html("<strong>你好,我是小羚羊 🦌</strong><br><br>我可以帮你查 ERP 里的业务单据。试试问我:<br>· “有哪些和报价相关的表单?”<br>· “客户资料在哪张表单里?”");
    }

    function reset(message){
        const input = $('#messageInput');
        const button = $('#sendButton');
        input.val('');
        input.prop('disabled', true);
        button.prop('disabled', true);
        doMessage(input,message,button);
    }

    async function sendMessage() {
        const input = $('#messageInput');
        const button = $('#sendButton');
        const message = input.val();
        if (!message) return;
        input.val('');
        input.prop('disabled', true);
        button.prop('disabled', true);
        doMessage(input, message, button);
    }

    // ======================
    // 🔥 已修复:完整 fetch 流式交互
    // ======================
    // ============================
    // 核心:按序号 0,1,2... 顺序获取 + 播放
    // ===========================
    async function playByIndex(cacheKey, currentIndex, totalSize) {
        if (currentIndex >= totalSize) return;

        async function checkPiece() {
            try {
                // 你原来的 fetch 写法 100% 保留
                const res = await fetch(`${CONFIG.backendUrl}/api/tts/audio/piece?cacheKey=${cacheKey}&index=${currentIndex}`);
                const piece = await res.json();

                if (piece && piece.audio) {
                    // 你原来的 base64 播放方式
                    const blob = base64ToBlob(piece.audio);
                    const audio = new Audio(URL.createObjectURL(blob));

                    audio.onended = () => {
                        // 自动播放下一段
                        playByIndex(cacheKey, currentIndex + 1, totalSize);
                    };

                    audio.play().catch(err => {
                        console.log('播放异常,自动下一段', err);
                        playByIndex(cacheKey, currentIndex + 1, totalSize);
                    });

                } else {
                    // 没获取到,等待再取(你原来的 800ms)
                    setTimeout(checkPiece, 800);
                }
            } catch (e) {
                setTimeout(checkPiece, 800);
            }
        }

        checkPiece();
    }

    // ======================
    // 单 agent 流式对话:POST /api/agent/chat -> SSE(text/event-stream)
    // 每帧一条 JSON:{type:"token|done|error", content:"..."}
    // ======================
    async function doMessage(input, message, button) {
        addMessage(message, 'user');
        showTypingIndicator();

        let aiText = '';
        let aiMsgId = null;

        try {
            const response = await fetch(`${CONFIG.backendUrl}/api/agent/chat`, {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=UTF-8" },
                body: JSON.stringify({
                    text: message,
                    userid: userid,
                    conversationId: conversationId,
                    // 透传身份 + ERP 登录 token(后端据此按用户真实权限收紧;token 只用于转发给 ERP,不进 prompt)
                    authorization: authorization,
                    username: username,
                    brandsid: brandsid,
                    subsidiaryid: subsidiaryid,
                    usertype: usertype
                })
            });
            if (!response.ok) throw new Error("HTTP " + response.status);

            const reader = response.body.getReader();
            const decoder = new TextDecoder("utf-8");
            let buffer = '';

            while (true) {
                const { value, done } = await reader.read();
                if (done) break;
                buffer += decoder.decode(value, { stream: true });

                let sep;
                while ((sep = buffer.indexOf("\n\n")) >= 0) {
                    const frame = buffer.slice(0, sep);
                    buffer = buffer.slice(sep + 2);
                    const dataLine = frame.split("\n").find(l => l.startsWith("data:"));
                    if (!dataLine) continue;
                    const payload = dataLine.slice(5).trim();
                    if (!payload) continue;
                    let evt;
                    try { evt = JSON.parse(payload); } catch (e) { continue; }

                    if (evt.type === "token") {
                        if (aiMsgId === null) { hideTypingIndicator(); aiMsgId = addMessage('', 'ai'); }
                        aiText += evt.content;
                        updateMessage(aiMsgId, aiText);
                    } else if (evt.type === "reset") {
                        // 工具执行前的旁白作废,清空气泡,等最终答复流入
                        aiText = '';
                        if (aiMsgId === null) { hideTypingIndicator(); aiMsgId = addMessage('', 'ai'); }
                        $(`#${aiMsgId} .message-content`).html('🔎 正在处理…');
                    } else if (evt.type === "write_proposal") {
                        renderProposalCard(evt.opId, evt.summary);
                    } else if (evt.type === "form_collect") {
                        renderFormCollect(evt.entity, evt.fields || []);
                    } else if (evt.type === "question") {
                        renderQuestion(evt.question, evt.options || []);
                    } else if (evt.type === "error") {
                        if (aiMsgId === null) { hideTypingIndicator(); aiMsgId = addMessage('', 'ai'); }
                        aiText += (aiText ? "\n\n" : "") + "⚠️ " + evt.content;
                        updateMessage(aiMsgId, aiText);
                    }
                    // evt.type === "done" -> 结束,无需处理
                }
            }

            hideTypingIndicator();
            if (aiMsgId === null) addMessage("(无响应,请重试)", 'ai');

        } catch (error) {
            console.error('错误:', error);
            hideTypingIndicator();
            if (aiMsgId === null) addMessage("服务异常,请重试:" + error.message, 'ai');
        } finally {
            input.prop('disabled', false);
            button.prop('disabled', false);
            input.focus();
            scrollToBottom();
            loadConversations();
        }
    }

    function updateMessage(messageId, content) {
        $(`#${messageId} .message-content`).html(md.render(content));
        scrollToBottom();
    }

    function escapeHtml(s){ return (s==null?'':String(s)).replace(/[&<>"']/g, m=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m])); }

    // ====================== 写操作确认卡片(人在环) ======================
    function renderProposalCard(opId, summary) {
        hideTypingIndicator();
        const cardId = 'op-' + opId;
        if (document.getElementById(cardId)) return;
        const html = `
          <div class="message ai-message" id="${cardId}">
            <div class="message-bubble" style="border:1px solid #ffd27f;background:#fff8ec;">
              <div class="message-content">
                <div style="font-weight:600;margin-bottom:8px;">⚠️ 待确认的修改</div>
                <div style="margin-bottom:12px;">${escapeHtml(summary)}</div>
                <div class="op-actions">
                  <button onclick="confirmOp('${opId}')" style="padding:8px 18px;border:none;border-radius:16px;background:linear-gradient(90deg,#28a745,#20913c);color:#fff;cursor:pointer;font-weight:600;margin-right:8px;">确认执行</button>
                  <button onclick="cancelOp('${opId}')" style="padding:8px 18px;border:1px solid #ccc;border-radius:16px;background:#fff;cursor:pointer;">取消</button>
                </div>
                <div class="op-result" style="margin-top:10px;color:#555;"></div>
              </div>
            </div>
          </div>`;
        $('#chatMessages').append(html);
        scrollToBottom();
    }

    async function confirmOp(opId) {
        const card = $('#op-' + opId);
        card.find('.op-actions button').prop('disabled', true);
        card.find('.op-result').text('处理中…');
        try {
            const res = await fetch(CONFIG.backendUrl + '/api/agent/op/' + opId + '/confirm', { method:'POST', headers:{ 'Authorization': authorization } });
            const data = await res.json();
            if (data.status === 'executed') {
                card.find('.op-actions').remove();
                card.find('.op-result').html('✅ ' + escapeHtml(data.msg || '已修改'));
            } else {
                card.find('.op-result').html('❌ ' + escapeHtml(data.msg || '执行失败') + '(可重试)');
                card.find('.op-actions button').prop('disabled', false);
            }
        } catch (e) {
            card.find('.op-result').text('❌ 请求失败:' + e.message);
            card.find('.op-actions button').prop('disabled', false);
        }
    }

    async function cancelOp(opId) {
        const card = $('#op-' + opId);
        try { await fetch(CONFIG.backendUrl + '/api/agent/op/' + opId + '/cancel', { method:'POST', headers:{ 'Authorization': authorization } }); } catch (e) {}
        card.find('.op-actions').remove();
        card.find('.op-result').text('已取消');
    }

    // ====================== FormCollect:type-aware 动态表单 ======================
    // fields = [{name,label,type,required,default,options?,fkTable?}](新版)或 ["中文名",...](旧版兼容)
    // type: text | number | date | select(固定选项) | fkselect(选项从对应表实时取)
    function renderFormCollect(entity, fields) {
        hideTypingIndicator();
        const fid = 'fc-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6);
        const norm = (fields || []).map(f => (typeof f === 'string') ? { name: f, label: f, type: 'text' } : f);
        const st = 'padding:6px 10px;border:1px solid #ccc;border-radius:8px;width:55%;';
        const inputs = norm.map((f, i) => {
            const label = escapeHtml(f.label || f.name);
            const req = f.required ? ' <span style="color:#e00;">*</span>' : '';
            const defv = f.default != null ? escapeHtml(String(f.default)) : '';
            const type = f.type || 'text';
            const ph = f.hint ? ` placeholder="${escapeHtml(String(f.hint))}"` : '';
            let control;
            if (type === 'select' && Array.isArray(f.options)) {
                const opts = ['<option value=""></option>']
                    .concat(f.options.map(o => `<option${String(o)===defv?' selected':''}>${escapeHtml(String(o))}</option>`)).join('');
                control = `<select data-label="${label}" class="fc-input" style="${st}">${opts}</select>`;
            } else if (type === 'fkselect') {
                const dlId = `${fid}-dl-${i}`;
                control = `<input data-label="${label}" class="fc-input fc-fk" list="${dlId}" data-fk="${escapeHtml(f.fkTable||'')}" placeholder="输入以搜索…" autocomplete="off" style="${st}"><datalist id="${dlId}"></datalist>`;
            } else if (type === 'number') {
                control = `<input type="number" step="any" data-label="${label}" value="${defv}" class="fc-input" style="${st}"${ph}>`;
            } else if (type === 'date') {
                control = `<input type="date" data-label="${label}" value="${defv}" class="fc-input" style="${st}">`;
            } else {
                control = `<input type="text" data-label="${label}" value="${defv}" class="fc-input" style="${st}"${ph}>`;
            }
            return `<div style="margin-bottom:8px;"><label style="display:inline-block;width:130px;color:#555;vertical-align:middle;">${label}${req}</label>${control}</div>`;
        }).join('');
        const html = `
          <div class="message ai-message" id="${fid}">
            <div class="message-bubble" style="border:1px solid #b9d6ff;background:#f2f8ff;">
              <div class="message-content">
                <div style="font-weight:600;margin-bottom:10px;">📝 填写「${escapeHtml(entity)}」信息</div>
                ${inputs}
                <div style="margin-top:8px;">
                  <button class="fc-submit" style="padding:8px 18px;border:none;border-radius:16px;background:linear-gradient(90deg,#667eea,#764ba2);color:#fff;cursor:pointer;font-weight:600;">提交</button>
                </div>
              </div>
            </div>
          </div>`;
        $('#chatMessages').append(html);
        // 外键下拉:聚焦拉一批候选,输入按关键词刷新(选项来自对应表)
        $(`#${fid} .fc-fk`).each(function () {
            const el = this, dlId = $(el).attr('list'), fkTable = $(el).data('fk');
            const load = (q) => fetch(`${CONFIG.backendUrl}/api/agent/form/options?table=${encodeURIComponent(fkTable)}&brandsid=${encodeURIComponent(brandsid)}&q=${encodeURIComponent(q||'')}`)
                .then(r => r.json()).then(list => {
                    const dl = document.getElementById(dlId);
                    if (dl) dl.innerHTML = (list||[]).map(o => `<option value="${escapeHtml(String(o))}"></option>`).join('');
                }).catch(() => {});
            let t = null;
            $(el).on('focus', () => load(''));
            $(el).on('input', function () { clearTimeout(t); const v = this.value; t = setTimeout(() => load(v), 250); });
        });
        $(`#${fid} .fc-submit`).on('click', function () {
            const parts = [];
            $(`#${fid} .fc-input`).each(function () {
                const v = ($(this).val() || '').trim();
                if (v) parts.push($(this).data('label') + '=' + v);
            });
            if (parts.length === 0) { alert('请至少填写一个字段'); return; }
            $(this).prop('disabled', true).text('已提交');
            $('#messageInput').val('为「' + entity + '」新增,字段如下:' + parts.join(',') + '。请调用 proposeWrite(action=create) 生成待确认的新增。');
            sendMessage();
        });
        scrollToBottom();
    }

    // ====================== AskUser:带可点选项的澄清问题 ======================
    function renderQuestion(question, options) {
        hideTypingIndicator();
        const qid = 'q-' + Date.now() + '-' + Math.random().toString(36).slice(2, 6);
        const chips = (options || []).map(o =>
            `<button class="q-opt" data-val="${escapeHtml(String(o))}" style="margin:4px 6px 0 0;padding:6px 14px;border:1px solid #667eea;border-radius:16px;background:#fff;color:#667eea;cursor:pointer;">${escapeHtml(String(o))}</button>`
        ).join('');
        const html = `
          <div class="message ai-message" id="${qid}">
            <div class="message-bubble" style="border:1px solid #d9c6ff;background:#f7f2ff;">
              <div class="message-content">
                <div style="font-weight:600;margin-bottom:8px;"> ${escapeHtml(question)}</div>
                <div class="q-opts">${chips}</div>
              </div>
            </div>
          </div>`;
        $('#chatMessages').append(html);
        $(`#${qid} .q-opt`).on('click', function () {
            const val = $(this).data('val');
            $(`#${qid} .q-opt`).prop('disabled', true).css('opacity', '0.6');
            $(this).css({background:'#667eea', color:'#fff'});
            $('#messageInput').val(String(val));
            sendMessage();
        });
        scrollToBottom();
    }

    // ==============================
    // 👇 语音排队播放函数(保证顺序)
    // ==============================
    function playNextAudio() {
        if (isPlaying || audioQueue.length === 0) return;

        isPlaying = true;
        const base64 = audioQueue.shift();
        const blob = base64ToBlob(base64);
        const audio = new Audio(URL.createObjectURL(blob));

        audio.onended = () => {
            isPlaying = false;
            playNextAudio(); // 播放下一条
        };

        audio.play().catch(err => {
            isPlaying = false;
            playNextAudio();
        });
    }

    function base64ToBlob(base64) {
        const byteCharacters = atob(base64);
        const byteNumbers = new Array(byteCharacters.length);
        for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        return new Blob([new Uint8Array(byteNumbers)], { type: 'audio/mpeg' });
    }

    async function handleNormalResponse(requestData) {
        try {
            const response = await fetch(`${CONFIG.backendUrl}/api/tts/stream/query`, {
                method: 'POST',
                headers: CONFIG.headers,
                body: JSON.stringify(requestData)
            });
            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }
        } catch (error) {
            hideTypingIndicator();
            throw error;
        } finally {
            ensureInputAtBottom();
        }
    }

    function getCurrentTime() {
        const now = new Date();
        return now.getHours().toString().padStart(2, '0') + ':' +
            now.getMinutes().toString().padStart(2, '0');
    }

    function addMessage(content, type = 'ai') {
        const messagesDiv = $('#chatMessages');
        const messageId = `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

        const messageHtml = `
                <div class="message ${type}-message" id="${messageId}">
                    <div class="message-bubble">
                        <div class="message-content">${type === 'ai' ? md.render(content) : content}</div>
                        <div class="message-meta">
                            <span class="message-time">${getCurrentTime()}</span>
                            <div class="message-actions">
                                <button class="action-btn" onclick="copyMessage('${messageId}')">复制</button>
                            </div>
                            <div class="message-actions">
                                 <button class="action-btn" onclick="regenerateMessage('${messageId}')">重新生成</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;

        messagesDiv.append(messageHtml);
        scrollToBottom();
        return messageId;
    }

    function showTypingIndicator() {
        const messagesDiv = $('#chatMessages');
        const typingHtml = `
                <div class="message ai-message" id="typingIndicator">
                    <div class="typing-indicator">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <span style="margin-left: 10px; color: #666; font-size: 14px;">正在思考...</span>
                    </div>
                </div>
            `;
        messagesDiv.append(typingHtml);
        scrollToBottom();
    }

    function hideTypingIndicator() {
        $('#typingIndicator').remove();
    }

    function updateStatus(text, type = 'connected') {
        const indicator = $('#statusIndicator');
        const statusText = $('#statusText');
        statusText.text(text);
        indicator.removeClass('status-connected status-disconnected status-connecting');
        switch(type) {
            case 'connected':
                indicator.addClass('status-connected');
                break;
            case 'error':
                indicator.addClass('status-disconnected');
                break;
            case 'connecting':
                indicator.addClass('status-connecting');
                break;
        }
    }

    function scrollToBottom() {
        const messagesDiv = $('#chatMessages');
        setTimeout(() => {
            messagesDiv.scrollTop(messagesDiv[0].scrollHeight);
        }, 10);
    }

    function ensureInputAtBottom() {
        setTimeout(() => {
            scrollToBottom();
            const messagesDiv = $('#chatMessages');
            let bottomSpacer = messagesDiv.find('.bottom-spacer');
            if (bottomSpacer.length === 0) {
                messagesDiv.append('<div class="bottom-spacer"></div>');
            }
        }, 100);
    }

    function saveToHistory(role, content) {
        chatHistory.push({
            role: role,
            content: content,
            timestamp: Date.now()
        });

        if (chatHistory.length > CONFIG.maxHistory) {
            chatHistory = chatHistory.slice(-CONFIG.maxHistory);
        }
        localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
    }

    function loadChatHistory() {
        const saved = localStorage.getItem('chatHistory');
        if (saved) {
            try {
                chatHistory = JSON.parse(saved);
                if (chatHistory.length > 0) {
                    chatHistory.forEach(item => {
                        if (item.role === 'user' || item.role === 'assistant') {
                            addMessage(item.content, item.role === 'user' ? 'user' : 'ai');
                        }
                    });
                    ensureInputAtBottom();
                }
            } catch (e) {
                console.error('加载聊天历史失败:', e);
                chatHistory = [];
            }
        }
    }

    function clearChat() {
        if (confirm('确定要清空当前对话吗?')) {
            $('#chatMessages').html(`
                    <div class="message ai-message">
                        <div class="message-bubble">
                            <div class="message-content">
                                对话已清空,请开始新的对话。
                            </div>
                            <div class="message-meta">
                                <span class="message-time">${getCurrentTime()}</span>
                            </div>
                        </div>
                    </div>
                `);
            chatHistory = [];
            localStorage.removeItem('chatHistory');
            updateStatus('对话已清空', 'connected');
            sessionId ="";
            conversationId = "c-" + Date.now() + "-" + Math.random().toString(36).slice(2, 8);
            ensureInputAtBottom();
        }
    }

    function copyMessage(messageId) {
        const messageContent = $(`#${messageId}`).find('.message-content').text();
        navigator.clipboard.writeText(messageContent).then(() => {
            const button = $(`#${messageId} .action-btn:first-child`);
            const originalText = button.text();
            button.text('已复制');
            setTimeout(() => {
                button.text(originalText);
            }, 2000);
        });
    }

    function regenerateMessage(messageId) {
        const messageDiv = $(`#${messageId}`);
        const content = messageDiv.find('.message-content').text();
        chatHistory = chatHistory.filter(item =>
            item.role !== 'assistant' || item.content !== content
        );
        $('#messageInput').val(content);
        sendMessage();
        messageDiv.remove();
    }

    function handleError(error) {
        hideTypingIndicator();
        const errorMessage = `
                抱歉,请求出现错误:${error.message}<br><br>
                <strong>可能的原因:</strong><br>
                1. Spring Boot 后端服务未启动<br>
                2. API 接口路径不正确<br>
                3. 网络连接问题<br><br>
                <strong>检查步骤:</strong><br>
                1. 确保后端服务在端口 8099 运行<br>
                2. 检查浏览器控制台查看详细错误<br>
                3. 刷新页面重试
            `;
        addMessage(errorMessage, 'ai');
        updateStatus('请求失败', 'error');
        ensureInputAtBottom();
    }

    function bindKeyboardEvents() {
        $('#messageInput').on('keypress', function(e) {
            if (e.which === 13 && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        $(document).on('keydown', function(e) {
            if (e.ctrlKey && e.key === 'Enter') {
                sendMessage();
            }
            if (e.key === 'Escape') {
                $('#messageInput').val('');
            }
            if (e.key === 'ArrowUp' && $('#messageInput').val() === '') {
                const lastUserMessage = chatHistory
                    .filter(item => item.role === 'user')
                    .pop();
                if (lastUserMessage) {
                    $('#messageInput').val(lastUserMessage.content);
                    e.preventDefault();
                }
            }
        });
    }

    $('#modelSelector').on('change', function() {
        currentModel = $(this).val();
        updateStatus(`切换到${$(this).find('option:selected').text()}模式`, 'connected');
    });

    $(window).on('resize', function() {
        ensureInputAtBottom();
    });
</script>
</body>
</html>