<?php
/**
 * 官网聊天 - 后台嵌入版
 * 通过API连接官网聊天
 */
require_once __DIR__ . '/../MPHX/common.php';

if (!is_admin_login()) {
    header('Location: /admin/login.php');
    exit;
}

$admin = is_admin_login();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>官网聊天</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css?v=2026040422">
    <link rel="stylesheet" href="/static/css/all.min.css?v=2026040422">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        html, body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: #f5f7fa;
            height: 100%;
            overflow: hidden;
        }
        .chat-wrapper {
            display: flex;
            height: 100%;
            width: 100%;
        }
        .chat-main {
            display: flex;
            flex-direction: column;
            background: white;
            flex: 1;
            width: 100%;
            min-height: 0;
        }
        .online-count {
            font-size: 13px;
            color: #6b7280;
        }

        /* 响应式布局 */
        @media (max-width: 768px) {
            .chat-wrapper {
                height: 100%;
            }
            .chat-header {
                padding: 8px 15px;
            }
            .chat-header h3 {
                font-size: 14px;
                margin-bottom: 0;
            }
            .online-count {
                font-size: 12px;
            }
            .chat-messages {
                padding: 15px;
            }
            .message {
                display: flex;
                gap: 10px;
                margin-bottom: 15px;
                align-items: flex-start;
            }
            .message-avatar {
                width: 36px;
                height: 36px;
                font-size: 14px;
            }
            .message-content {
                flex: 1;
                min-width: 0;
                max-width: calc(100% - 46px);
                display: flex;
                flex-direction: column;
                align-items: flex-start;
            }
            .message.own .message-content {
                align-items: flex-end;
            }
            .message-header {
                font-size: 11px;
                white-space: nowrap;
            }
            .message-bubble {
                padding: 10px 14px;
                font-size: 14px;
                display: inline-block;
                word-break: break-word;
                max-width: 100%;
                white-space: pre-wrap;
            }
            .message-image {
                max-width: 150px;
                max-height: 150px;
            }
            .chat-input-area {
                padding: 8px 15px;
            }
            .input-tools {
                margin-bottom: 6px;
            }
            .tool-btn {
                width: 28px;
                height: 28px;
            }
            .chat-input {
                padding: 8px 10px;
                font-size: 16px; /* 防止 iOS 缩放 */
                min-height: 36px;
            }
            .input-footer {
                margin-top: 6px;
            }
            .input-footer-left {
                display: flex;
                align-items: center;
                gap: 8px;
            }
            .input-footer-left .input-tools {
                display: flex;
                gap: 6px;
                margin-bottom: 0;
            }
            .char-count {
                font-size: 11px;
            }
            .send-btn {
                padding: 8px 14px;
                font-size: 12px;
            }
        }

        @media (max-width: 480px) {
            .chat-messages {
                padding: 10px;
            }
            .message {
                gap: 8px;
                margin-bottom: 12px;
            }
            .message-avatar {
                width: 32px;
                height: 32px;
                font-size: 12px;
            }
            .message-content {
                flex: 1;
                min-width: 0;
                max-width: calc(100% - 38px);
                display: flex;
                flex-direction: column;
                align-items: flex-start;
            }
            .message.own .message-content {
                align-items: flex-end;
            }
            .message-header {
                font-size: 11px;
                white-space: nowrap;
            }
            .message-bubble {
                padding: 8px 10px;
                font-size: 14px;
                display: inline-block;
                word-break: break-word;
                max-width: 100%;
                white-space: pre-wrap;
            }
            .message-image {
                max-width: 120px;
                max-height: 120px;
            }
        }
        .chat-header {
            padding: 12px 20px;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .chat-header h3 {
            font-size: 14px;
            color: #111827;
            margin-bottom: 0;
        }
        .chat-header .online-count {
            font-size: 12px;
            color: #6b7280;
        }
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f9fafb;
        }
        .message {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            align-items: flex-start;
        }
        .message.own {
            flex-direction: row-reverse;
        }
        .message-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #3b82f6, #8b5cf6);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            flex-shrink: 0;
        }
        .message.own .message-avatar {
            background: linear-gradient(135deg, #10b981, #059669);
        }
        .message-content {
            flex: 1;
            min-width: 0;
            max-width: calc(100% - 52px);
            display: flex;
            flex-direction: column;
            align-items: flex-start;
        }
        .message.own .message-content {
            align-items: flex-end;
        }
        .message-header {
            font-size: 12px;
            color: #6b7280;
            margin-bottom: 4px;
            white-space: nowrap;
        }
        .message.own .message-header {
            text-align: right;
        }
        .message-bubble {
            background: white;
            padding: 12px 16px;
            border-radius: 12px;
            box-shadow: 0 1px 2px rgba(0,0,0,0.05);
            word-break: break-word;
            display: inline-block;
            max-width: 100%;
            white-space: pre-wrap;
        }
        .message.own .message-bubble {
            background: #dcfce7;
        }
        .message-image {
            max-width: 200px;
            max-height: 200px;
            border-radius: 8px;
            cursor: pointer;
        }
        .message-deleted {
            color: #9ca3af;
            font-style: italic;
            padding: 8px 12px;
        }
        .chat-input-area {
            padding: 10px 20px;
            border-top: 1px solid #e5e7eb;
            background: white;
            flex-shrink: 0;
        }
        .input-tools {
            display: flex;
            gap: 8px;
            margin-bottom: 8px;
        }
        .tool-btn {
            width: 36px;
            height: 36px;
            border: none;
            background: #f8fafc;
            border-radius: 8px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6b7280;
            transition: all 0.3s;
        }
        .tool-btn:hover {
            background: #3b82f6;
            color: white;
        }
        .input-wrapper {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .chat-input {
            flex: 1;
            padding: 8px 12px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 14px;
            resize: none;
            min-height: 36px;
            max-height: 100px;
            width: 100%;
        }
        .chat-input:focus {
            outline: none;
            border-color: #3b82f6;
        }
        .input-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            margin-top: 8px;
        }
        .input-footer-left {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .input-footer-left .input-tools {
            display: flex;
            gap: 8px;
            margin-bottom: 0;
        }
        .char-count {
            font-size: 12px;
            color: #6b7280;
        }
        .char-count.warning {
            color: #f59e0b;
        }
        .char-count.danger {
            color: #ef4444;
        }
        .send-btn {
            padding: 12px 24px;
            background: #3b82f6;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.3s;
        }
        .send-btn:hover {
            background: #2563eb;
        }
        .send-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }
        .emoji-picker {
            display: none;
            position: absolute;
            bottom: 100%;
            left: 0;
            background: white;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            padding: 10px;
            box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
            z-index: 100;
            grid-template-columns: repeat(8, 1fr);
            gap: 5px;
        }
        .emoji-picker.show {
            display: grid;
        }
        .emoji-btn {
            width: 30px;
            height: 30px;
            border: none;
            background: none;
            cursor: pointer;
            font-size: 20px;
        }
        .emoji-btn:hover {
            background: #f3f4f6;
            border-radius: 4px;
        }
        .image-upload {
            display: none;
        }
        .loading {
            text-align: center;
            padding: 40px;
            color: #9ca3af;
        }
        .empty {
            text-align: center;
            padding: 40px;
            color: #9ca3af;
        }
        .image-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.8);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }
        .image-modal.show {
            display: flex;
        }
        .image-modal img {
            max-width: 90%;
            max-height: 90%;
            border-radius: 8px;
        }
        .image-modal .close {
            position: absolute;
            top: 20px;
            right: 20px;
            color: white;
            font-size: 30px;
            cursor: pointer;
        }
        .admin-badge {
            display: inline-block;
            padding: 2px 8px;
            background: #3b82f6;
            color: white;
            font-size: 11px;
            border-radius: 4px;
            margin-left: 5px;
        }
        
        /* 编辑用户信息弹窗 */
        .edit-profile-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            opacity: 0;
            transition: opacity 0.3s;
        }
        .edit-profile-overlay.show {
            opacity: 1;
        }
        .edit-profile-modal {
            background: white;
            border-radius: 12px;
            padding: 30px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.2);
            transform: scale(0.9);
            transition: transform 0.3s;
        }
        .edit-profile-overlay.show .edit-profile-modal {
            transform: scale(1);
        }
        .edit-profile-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
            text-align: center;
        }
        .edit-profile-avatar {
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, #3b82f6, #8b5cf6);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 40px;
            color: white;
            cursor: pointer;
            position: relative;
        }
        .edit-profile-avatar:hover::after {
            content: '更换';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
        }
        .edit-profile-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            font-size: 16px;
            margin-bottom: 20px;
            box-sizing: border-box;
        }
        .edit-profile-input:focus {
            outline: none;
            border-color: #3b82f6;
        }
        .edit-profile-buttons {
            display: flex;
            gap: 10px;
        }
        .edit-profile-buttons button {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.2s;
        }
        .edit-profile-cancel {
            background: #f3f4f6;
            color: #6b7280;
        }
        .edit-profile-cancel:hover {
            background: #e5e7eb;
        }
        .edit-profile-save {
            background: #3b82f6;
            color: white;
        }
        .edit-profile-save:hover {
            background: #2563eb;
        }
    </style>
</head>
<body>
    <div class="chat-wrapper">
        <div class="chat-main">
            <div class="chat-header">
                <div>
                    <h3>公共聊天室</h3>
                </div>
                <span class="online-count" id="onlineCount">0 人在线</span>
            </div>
            <div class="chat-messages" id="chatMessages">
                <div class="loading">
                    <i class="fas fa-spinner fa-spin"></i> 加载消息中...
                </div>
            </div>
            <div class="chat-input-area">
                <div class="input-wrapper">
                    <textarea class="chat-input" id="chatInput" placeholder="请输入消息..." maxlength="1000"></textarea>
                    <div class="input-footer">
                        <div class="input-footer-left">
                            <div class="input-tools">
                                <div style="position: relative;">
                                    <button class="tool-btn" id="emojiBtn" title="表情">
                                        <i class="far fa-smile"></i>
                                    </button>
                                    <div class="emoji-picker" id="emojiPicker"></div>
                                </div>
                                <button class="tool-btn" id="imageBtn" title="发送图片">
                                    <i class="far fa-image"></i>
                                </button>
                                <input type="file" id="imageUpload" class="image-upload" accept="image/*">
                            </div>
                            <span class="char-count" id="charCount">0/1000</span>
                        </div>
                        <button class="send-btn" id="sendBtn"><i class="fas fa-paper-plane"></i> 发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片预览模态框 -->
    <div class="image-modal" id="imageModal" onclick="closeImageModal()">
        <span class="close">&times;</span>
        <img src="" alt="预览" id="modalImage">
    </div>

    <script src="/static/js/jquery.min.js"></script>
    <script>
        // API地址 - 使用本地代理连接官网聊天系统
        const API_BASE = 'chat_proxy.php';
        
        // 用户信息 - 与官网保持一致，使用随机生成的用户 ID
        let userId = localStorage.getItem('chat_user_id');
        if (!userId) {
            userId = 'user_' + Math.random().toString(36).substr(2, 9);
            localStorage.setItem('chat_user_id', userId);
        }
        
        // 管理员用户名 - 使用 let 以便可以修改
        let userName = '<?php echo htmlspecialchars($admin); ?>';
        
        // 从本地存储加载用户名（如果存在）
        const savedUserName = localStorage.getItem('chat_user_name');
        if (savedUserName) {
            userName = savedUserName;
        }
        
        let lastMessageId = 0;
        let isLoadingMessages = false;
        
        // DOM 元素
        const chatMessages = document.getElementById('chatMessages');
        const chatInput = document.getElementById('chatInput');
        const sendBtn = document.getElementById('sendBtn');
        const charCount = document.getElementById('charCount');
        const emojiBtn = document.getElementById('emojiBtn');
        const emojiPicker = document.getElementById('emojiPicker');
        const imageBtn = document.getElementById('imageBtn');
        const imageUpload = document.getElementById('imageUpload');
        const onlineCount = document.getElementById('onlineCount');
        
        // 表情列表
        const emojis = ['😀', '😃', '😄', '😁', '😅', '😂', '🤣', '😊', '😇', '🙂', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🥸', '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬', '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗', '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😬', '🙄', '😯', '😦', '😧', '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐', '🥴', '🤢', '🤮', '🤧', '😷', '🤒', '🤕'];
        
        // 初始化表情选择器
        emojis.forEach(emoji => {
            const btn = document.createElement('button');
            btn.className = 'emoji-btn';
            btn.textContent = emoji;
            btn.onclick = () => {
                chatInput.value += emoji;
                chatInput.focus();
            };
            emojiPicker.appendChild(btn);
        });
        
        // 表情按钮点击
        emojiBtn.onclick = () => {
            emojiPicker.classList.toggle('show');
        };
        
        // 点击外部关闭表情选择器
        document.addEventListener('click', (e) => {
            if (!emojiBtn.contains(e.target) && !emojiPicker.contains(e.target)) {
                emojiPicker.classList.remove('show');
            }
        });
        
        // 图片上传
        imageBtn.onclick = () => imageUpload.click();
        
        imageUpload.onchange = async (e) => {
            const file = e.target.files[0];
            if (!file) return;
            
            if (!file.type.startsWith('image/')) {
                alert('请选择图片文件');
                return;
            }
            
            if (file.size > 5 * 1024 * 1024) {
                alert('图片大小不能超过5MB');
                return;
            }
            
            const formData = new FormData();
            formData.append('image', file);
            formData.append('user_id', userId);
            formData.append('user_name', userName);

            try {
                sendBtn.disabled = true;
                sendBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 发送中...';

                const response = await fetch(API_BASE + '?action=upload', {
                    method: 'POST',
                    mode: 'cors',
                    credentials: 'omit',
                    body: formData
                });

                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }

                const data = await response.json();

                if (data.success) {
                    setTimeout(() => loadMessages(), 100);
                } else {
                    alert(data.msg || '发送失败');
                }
            } catch (error) {
                console.error('图片发送失败:', error);
                alert('网络错误，请稍后重试');
            } finally {
                sendBtn.disabled = false;
                sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i> 发送';
                imageUpload.value = '';
            }
        };
        
        // 发送消息
        async function sendMessage() {
            const content = chatInput.value.trim();
            if (!content) return;

            try {
                sendBtn.disabled = true;

                const response = await fetch(API_BASE + '?action=send', {
                    method: 'POST',
                    mode: 'cors',
                    credentials: 'omit',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        user_id: userId,
                        user_name: userName,
                        content: content
                    })
                });

                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }

                const data = await response.json();

                if (data.success) {
                    chatInput.value = '';
                    setTimeout(() => loadMessages(), 100);
                } else {
                    alert(data.msg || '发送失败');
                }
            } catch (error) {
                console.error('发送失败:', error);
                alert('网络错误，请稍后重试');
            } finally {
                sendBtn.disabled = false;
            }
        }
        
        sendBtn.addEventListener('click', sendMessage);
        
        chatInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
        
        // 字符计数
        chatInput.addEventListener('input', () => {
            const length = chatInput.value.length;
            const maxLen = 1000;
            charCount.textContent = length + '/' + maxLen;
            
            if (length > maxLen * 0.9) {
                charCount.classList.add('danger');
                charCount.classList.remove('warning');
            } else if (length > maxLen * 0.7) {
                charCount.classList.add('warning');
                charCount.classList.remove('danger');
            } else {
                charCount.classList.remove('warning');
                charCount.classList.remove('danger');
            }
        });
        
        // 加载消息
        async function loadMessages() {
            if (isLoadingMessages) return;
            isLoadingMessages = true;

            try {
                const response = await fetch(API_BASE + '?action=get&last_id=0', {
                    method: 'GET',
                    mode: 'cors',
                    credentials: 'omit'
                });

                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }

                const data = await response.json();

                if (data.success && data.messages) {
                    renderMessages(data.messages);
                } else {
                    chatMessages.innerHTML = '<div class="empty">暂无消息</div>';
                }
            } catch (error) {
                console.error('加载消息失败:', error);
                chatMessages.innerHTML = '<div class="empty">连接失败，请检查网络</div>';
            } finally {
                isLoadingMessages = false;
            }
        }
        
        // 渲染消息
        function renderMessages(messages) {
            if (messages.length === 0) {
                chatMessages.innerHTML = '<div class="empty">暂无消息，快来发送第一条消息吧！</div>';
                return;
            }
            
            chatMessages.innerHTML = '';
            
            messages.forEach(msg => {
                if (!msg || !msg.user_name) return;
                
                const div = document.createElement('div');
                div.className = 'message' + (msg.user_id === userId ? ' own' : '');
                div.dataset.id = msg.id;
                
                const isDeleted = msg.is_deleted == 1;
                const isAdmin = msg.user_id.startsWith('admin_');
                
                let contentHtml = '';
                if (isDeleted) {
                    contentHtml = '<div class="message-deleted">此消息已被删除</div>';
                } else if (msg.message_type === 'image' || msg.image_path) {
                    let imgSrc = msg.image_path || msg.message;
                    // 如果是相对路径，添加官网域名
                    if (imgSrc && !imgSrc.startsWith('http')) {
                        imgSrc = 'https://ww.a116.vip/' + imgSrc;
                    }
                    contentHtml = `<img src="${imgSrc}" class="message-image" onclick="showImagePreview('${imgSrc}')" alt="图片">`;
                } else {
                    contentHtml = `<div class="message-bubble">${escapeHtml(msg.content || msg.message || '')}</div>`;
                }
                
                const adminBadge = isAdmin ? '<span class="admin-badge">管理员</span>' : '';
                
                div.innerHTML = `
                    <div class="message-avatar" onclick="showEditProfileModal()" style="cursor: pointer;">${(msg.user_name || '?').charAt(0)}</div>
                    <div class="message-content">
                        <div class="message-header">${msg.user_name}${adminBadge} · ${msg.created_at || ''}</div>
                        ${contentHtml}
                    </div>
                `;
                
                chatMessages.appendChild(div);
                
                if (msg.id > lastMessageId) {
                    lastMessageId = msg.id;
                }
            });
            
            // 滚动到底部
            chatMessages.scrollTop = chatMessages.scrollHeight;
        }
        
        // 显示图片预览
        function showImagePreview(src) {
            document.getElementById('modalImage').src = src;
            document.getElementById('imageModal').classList.add('show');
        }
        
        function closeImageModal() {
            document.getElementById('imageModal').classList.remove('show');
        }
        
        // HTML 转义
        function escapeHtml(text) {
            if (!text) return '';
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 显示编辑用户信息弹窗
        function showEditProfileModal() {
            // 移除已存在的弹窗
            const existingModal = document.querySelector('.edit-profile-overlay');
            if (existingModal) {
                existingModal.remove();
            }

            const overlay = document.createElement('div');
            overlay.className = 'edit-profile-overlay';
            overlay.innerHTML = `
                <div class="edit-profile-modal">
                    <div class="edit-profile-title">编辑个人信息</div>
                    <div class="edit-profile-avatar" id="editAvatar">${userName.charAt(0)}</div>
                    <input type="text" class="edit-profile-input" id="editNameInput" value="${userName}" placeholder="请输入昵称" maxlength="20">
                    <div class="edit-profile-buttons">
                        <button class="edit-profile-cancel" onclick="closeEditProfileModal()">取消</button>
                        <button class="edit-profile-save" onclick="saveProfile()">保存</button>
                    </div>
                </div>
            `;

            document.body.appendChild(overlay);
            
            // 点击遮罩关闭
            overlay.addEventListener('click', function(e) {
                if (e.target === overlay) {
                    closeEditProfileModal();
                }
            });

            // 强制重绘以触发过渡动画
            overlay.offsetHeight;
            overlay.classList.add('show');

            // 聚焦输入框
            setTimeout(() => {
                document.getElementById('editNameInput').focus();
                document.getElementById('editNameInput').select();
            }, 100);
        }

        // 关闭编辑弹窗
        function closeEditProfileModal() {
            const overlay = document.querySelector('.edit-profile-overlay');
            if (overlay) {
                overlay.classList.remove('show');
                setTimeout(() => overlay.remove(), 300);
            }
        }

        // 保存用户信息
        function saveProfile() {
            const newName = document.getElementById('editNameInput').value.trim();
            
            if (!newName) {
                alert('昵称不能为空');
                return;
            }
            
            if (newName.length > 20) {
                alert('昵称不能超过 20 个字符');
                return;
            }

            // 调用 API 更新历史消息中的用户名
            fetch(API_BASE + '?action=update_username', {
                method: 'POST',
                mode: 'cors',
                credentials: 'omit',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_id: userId,
                    new_username: newName
                })
            }).catch(error => {
                console.error('更新用户名失败:', error);
            });

            // 更新本地存储
            localStorage.setItem('chat_user_name', newName);
            userName = newName;

            // 关闭弹窗
            closeEditProfileModal();

            // 刷新页面以更新显示
            setTimeout(() => {
                window.location.reload();
            }, 300);
        }

        // 加载在线人数
        async function loadOnlineCount() {
            try {
                const response = await fetch(API_BASE + '?action=online', {
                    method: 'GET',
                    mode: 'cors',
                    credentials: 'omit'
                });

                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }

                const data = await response.json();

                if (data.success && data.count !== undefined) {
                    onlineCount.textContent = data.count + ' 人在线';
                }
            } catch (error) {
                console.error('加载在线人数失败:', error);
            }
        }

        // 更新在线状态
        async function updateOnlineStatus() {
            try {
                await fetch(API_BASE + '?action=heartbeat', {
                    method: 'POST',
                    mode: 'cors',
                    credentials: 'omit',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        user_id: userId,
                        user_name: userName
                    })
                });
            } catch (error) {
                console.error('更新在线状态失败:', error);
            }
        }

        // 初始化
        loadMessages();
        loadOnlineCount();
        updateOnlineStatus();

        // 定时刷新
        setInterval(loadMessages, 1000);
        setInterval(loadOnlineCount, 5000);
        setInterval(updateOnlineStatus, 10000);
    </script>
</body>
</html>
