chat.html 29.1 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
<!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="clearChat()">清空对话</button>
        </div>
    </div>

    <div class="chat-body">
        <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 userid= "17706006510007934913359242990000";
    let userid= "17502321750004978169421209637000";
    let username= "admin";
    let brandsid= "1111111111";
    let subsidiaryid= "1111111111";
    let usertype= "sysadmin";
    // let usertype= "General";
    let authorization="1EDB99C9BF070115F7A57AC43D8CB09F0B8C49F979DAB63A2AEA84B372B2B42BF3419238942A93E9AD666629E18D159AF7FE144A6407DE745BA0AEC8B235FC1D2D86C92E4DCE571A8ECF0767494BBDE2495FD8E662F2065F9430347C7E4472B5538155B7ADAEE71E899235DC1122F426";
        //"1EDB99C9BF070115F7A57AC43D8CB09F0B8C49F979DAB63A2AEA84B372B2B42BF3419238942A93E9AD666629E18D159AF7FE144A6407DE745BA0AEC8B235FC1DC16A7526DEC4395CF09285C2BD330B9FD8668502224FF2D5675E74B8CDD2ABFB538155B7ADAEE71E899235DC1122F426";
    let hrefLock = window.location.origin+"/xlyAi";
    // ==================== 配置部分 ====================
    const CONFIG = {
        // Spring Boot 后端 API 地址
        backendUrl: hrefLock,
        // 请求头
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },

        // 聊天历史
        maxHistory: 20,

        // 流式响应配置
        // streaming: true
    };

    // 初始化变量
    let chatHistory = [];
    let currentModel = 'general';
    const md = window.markdownit({
        html: true,
        linkify: true,
        typographer: true
    });

    // ==================== 初始化函数 ====================
    $(document).ready(function() {
        // 设置欢迎消息时间
        document.getElementById('welcomeTime').textContent = getCurrentTime();
        // init();
        // 检查后端连接
        // checkBackendStatus();

        // 加载聊天历史(从本地存储)
        // loadChatHistory();

        // 聚焦输入框
        $('#messageInput').focus();
        // 绑定键盘事件
        bindKeyboardEvents();

        // 确保输入区域在底部
        ensureInputAtBottom();
    });

    // ==================== 核心功能函数 ====================
    // 生成指定长度的随机字符串(包含大小写字母和数字)
    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(){
        // 准备请求数据
        const data = {
            text: "",
            userid: userid,
            username: username,
            brandsid: brandsid,
            subsidiaryid: subsidiaryid,
            // usertype: "General",
            usertype: usertype,
            authorization: authorization,
            voice: "zh-CN-XiaoxiaoNeural",
            rate: "+10%",
            volume: "+0%",
            voiceless: false
        };

        let initUrl=CONFIG.backendUrl+"/api/tts/init";
        $.ajax({
            url: initUrl,
            type: 'POST', // 或 'GET'
            async: false, // 关键参数:设置为 false 表示同步
            data:JSON.stringify(data),
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            success: function(response) {
                debugger;
                $("#ts").html((response.processedText + response.systemText) );
            },
            error: function(xhr, status, error) {
                console.log('请求失败:', error);
            }
        });

    }
    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);
    }

    // 最简单版本 - 直接放在sendMessage函数里
    async function doMessage(input,message,button) {
        // 添加用户消息
        addMessage(message, 'user');

        // 显示"正在思考"
        showTypingIndicator();

        try {
            // 准备请求数据
            const requestData = {
                text: message,
                userid: userid,
                // usertype: "General",
                usertype: usertype,
                authorization: authorization,
                voice: "zh-CN-XiaoxiaoNeural",
                rate: "+10%",
                volume: "+0%",
                voiceless: false
            };

            // 发送请求
            const response = await fetch(`${CONFIG.backendUrl}/api/tts/stream/query`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(requestData)
            });

            const data = await response.json();

            // 隐藏"正在思考"
            hideTypingIndicator();
           // console.log("data==",data)
            // 显示AI回复文字
            addMessage((data.processedText + data.systemText) || data.originalText || message, 'ai');

            // 播放音频
            if (data.audioBase64) {
                const audioBlob = base64ToBlob(data.audioBase64);
                const audio = new Audio(URL.createObjectURL(audioBlob));
                audio.play();
            }

        } catch (error) {
            console.error('错误:', error);
            hideTypingIndicator();
            addMessage(message, 'ai'); // 出错也显示原消息
        } finally {
            // 恢复输入框
            input.prop('disabled', false);
            button.prop('disabled', false);
            input.focus();
            scrollToBottom();
        }
    }

    // 工具函数
    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 {
            console.log("requestData",requestData);
            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}`);
            }
            console.log("123",response);

            // // 流式请求
            // const audioBlob = await response.blob();
            // currentAudioBlob = audioBlob;
            // currentAudioUrl = URL.createObjectURL(audioBlob);
            // elements.audioPlayer.src = currentAudioUrl
            // elements.audioPlayer.play();
            //
            // const messageDetail = await response.messageDetail;
            // hideTypingIndicator();
            // // 添加AI回复
            // if (data.data) {
            //     addMessage(data.data, 'ai');
            //     saveToHistory('assistant', data.content);
            //     updateStatus('回答完成', 'connected');
            // }

        } 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 updateMessage(messageId, content) {
    //     const messageDiv = $(`#${messageId}`);
    //     if (messageDiv.length) {
    //         messageDiv.find('.message-content').html(md.render(content));
    //         scrollToBottom();
    //     }
    // }

    // 显示/隐藏打字机效果
    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');
        // 添加延迟确保DOM更新完成
        setTimeout(() => {
            messagesDiv.scrollTop(messagesDiv[0].scrollHeight);
        }, 10);
    }

    // 确保输入区域在底部
    function ensureInputAtBottom() {
        // 添加一个小的延迟,确保DOM更新完成
        setTimeout(() => {
            scrollToBottom();

            // 添加一个空div来确保底部有空间
            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 askPresetQuestion(question) {
    //     $('#messageInput').val(question);
    //     sendMessage();
    // }

    // 清空对话
    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 ="";
            // 确保输入区域在底部
            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) {
            // Ctrl + Enter 发送
            if (e.ctrlKey && e.key === 'Enter') {
                sendMessage();
            }

            // ESC 清空输入框
            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>