chat.html 28.4 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
<!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= "17522967560005776104370282597000";
    let username= "钱豹";
    let brandsid= "1111111111";
    let subsidiaryid= "1111111111";
    let usertype= "sysadmin";
    let authorization="CE444885A9BCFDDE1FD793F8A0931301E9D7DE6CEDD9DE4B83ECE2219C7829A8F3419238942A93E9AD666629E18D159AF7FE144A6407DE745BA0AEC8B235FC1D4CAE6F9AC893752209A98011A981375391D4466816B7D3D1AF306E28B989121C538155B7ADAEE71E899235DC1122F426";
    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();
    });

    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: 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',
            async: false,
            data:JSON.stringify(data),
            dataType: 'json',
            contentType: 'application/json; charset=UTF-8',
            success: function(response) {
                $("#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);
    }

    // ======================
    // 🔥 已修复:完整 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();
    }

    async function doMessage(input, message, button) {
        addMessage(message, 'user');
        showTypingIndicator();

        try {
            const requestData = {
                text: message,
                userid: userid,
                usertype: usertype,
                authorization: authorization,
                voice: "zh-CN-XiaoxiaoNeural",
                rate: "+10%",
                volume: "+0%",
                voiceless: true
            };

            const response = await fetch(`${CONFIG.backendUrl}/api/tts/stream/query`, {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=UTF-8" },
                body: JSON.stringify(requestData)
            });

            const data = await response.json();
            hideTypingIndicator();
            const replyText = (data.processedText || "") + (data.systemText || "");
            addMessage(replyText, 'ai');

            // ==============================================
            // 👇 【关键】用 cacheKey 取音频(绝对不串音)
            // ==============================================
            const cacheKey = data.cacheKey;
            if (!cacheKey) return;
            const audioSize = data.audioSize; // 总分几段

            let retry = 0;
            const checkAudio = async () => {
                retry++;
                if (retry > 20) return;

                try {
                    // ==============================================
                    // 👇 用 cacheKey 获取自己的音频(别人拿不到)
                    // ==============================================
                    const res = await fetch(`${CONFIG.backendUrl}/api/tts/audio?cacheKey=${encodeURIComponent(cacheKey)}`);
                    const audioData = await res.json();

                    if (audioData.audioBase64) {
                        const blob = base64ToBlob(audioData.audioBase64);
                        const audio = new Audio(URL.createObjectURL(blob));
                        audio.play().catch(err => console.log('播放异常', err));
                    } else {
                        setTimeout(checkAudio, 800);
                    }
                } catch (e) {
                    setTimeout(checkAudio, 800);
                }
            };
            setTimeout(checkAudio, 1200);
            playByIndex(cacheKey, 0, audioSize);

        } catch (error) {
            console.error('错误:', error);
            hideTypingIndicator();
            addMessage("服务异常,请重试", 'ai');
        } finally {
            input.prop('disabled', false);
            button.prop('disabled', false);
            input.focus();
            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 ="";
            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>