<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('客服系统')" />
    <link th:href="@{/css/plugins/webuploader/webuploader.thumbnail.css}" rel="stylesheet"/>
    <style>
        .customer-service-container {
            height: calc(100vh - 30px);
            display: flex;
            background: #fff;
        }
        
        .session-list {
            width: 300px;
            border-right: 1px solid #e7eaec;
            overflow-y: auto;
        }
        
        .session-item {
            padding: 15px;
            border-bottom: 1px solid #f1f1f1;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        
        .session-item:hover {
            background-color: #f8f8f9;
        }
        
        .session-item.active {
            background-color: #e6f7ff;
            border-left: 3px solid #1890ff;
        }
        
        .session-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #1890ff;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 10px;
        }
        
        .session-info {
            flex: 1;
        }
        
        .session-name {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .session-last-msg {
            color: #666;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .session-time {
            font-size: 11px;
            color: #999;
        }
        
        .session-status {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-left: 5px;
        }
        
        .status-online { background: #52c41a; }
        .status-offline { background: #d9d9d9; }
        .status-busy { background: #faad14; }
        
        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        
        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid #e7eaec;
            background: #fafafa;
        }
        
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f8f9;
        }
        
        .message-item {
            margin-bottom: 20px;
            display: flex;
        }
        
        .message-item.sent {
            justify-content: flex-end;
        }
        
        .message-content {
            max-width: 60%;
            padding: 10px 15px;
            border-radius: 8px;
            position: relative;
        }
        
        .message-item.received .message-content {
            background: #fff;
            border: 1px solid #e7eaec;
        }
        
        .message-item.sent .message-content {
            background: #1890ff;
            color: white;
        }
        
        .message-time {
            font-size: 11px;
            color: #999;
            margin-top: 5px;
        }
        
        .chat-input {
            padding: 15px 20px;
            border-top: 1px solid #e7eaec;
            background: #fff;
        }
        
        .input-toolbar {
            margin-bottom: 10px;
        }
        
        .input-area {
            display: flex;
            align-items: flex-end;
        }
        
        .input-text {
            flex: 1;
            min-height: 60px;
            max-height: 120px;
            resize: none;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            padding: 10px;
            margin-right: 10px;
        }
        
        .manual-service-panel {
            width: 280px;
            border-left: 1px solid #e7eaec;
            background: #fafafa;
            overflow-y: auto;
        }
        
        .panel-header {
            padding: 15px;
            border-bottom: 1px solid #e7eaec;
            font-weight: bold;
        }
        
        .manual-request-item {
            padding: 15px;
            border-bottom: 1px solid #f1f1f1;
        }
        
        .request-user {
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .request-reason {
            color: #666;
            font-size: 12px;
            margin-bottom: 10px;
        }
        
        .request-time {
            font-size: 11px;
            color: #999;
            margin-bottom: 10px;
        }
        
        .request-actions {
            display: flex;
            gap: 5px;
        }
        
        .btn-sm {
            padding: 2px 8px;
            font-size: 11px;
        }
        
        /* 闪烁动画样式 */
        @keyframes blink {
            0% { background-color: inherit; }
            50% { background-color: #ff4d4f; }
            100% { background-color: inherit; }
        }
        
        .blink-notification {
            animation: blink 1s ease-in-out infinite;
        }
        
        .manual-service-panel.blink-notification {
            animation: blink 1s ease-in-out 5;
        }
        
        .panel-header.blink-notification {
            animation: blink 1s ease-in-out 5;
            color: #fff !important;
        }
        
        /* 会话分隔符样式 */
        .session-separator {
            margin: 20px 0;
            text-align: center;
            position: relative;
        }
        
        .session-separator::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 1px;
            background: #e7eaec;
        }
        
        .session-separator-text {
            background: #f8f8f9;
            padding: 5px 15px;
            color: #666;
            font-size: 12px;
            border: 1px solid #e7eaec;
            border-radius: 15px;
            display: inline-block;
        }
        
        .session-separator.current-session .session-separator-text {
            background: #e6f7ff;
            border-color: #1890ff;
            color: #1890ff;
            font-weight: bold;
        }
        
        /* 历史消息样式 */
        .history-message {
            opacity: 0.8;
        }
        
        .history-message .message-content {
            border-style: dashed;
        }
        
        /* 加载状态样式 */
        .loading-message {
            text-align: center;
            color: #666;
            font-style: italic;
            margin: 20px 0;
        }
        
        .no-history-message {
            text-align: center;
            color: #999;
            font-style: italic;
            margin: 40px 0;
        }
    </style>
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="customer-service-container">
        <!-- 左侧会话列表 -->
        <div class="session-list">
            <div class="panel-header">
                <i class="fa fa-comments"></i> 会话列表
                <span class="badge badge-primary pull-right" id="sessionCount">0</span>
            </div>
            <div id="sessionListContainer">
                <!-- 会话列表将通过JavaScript动态加载 -->
            </div>
        </div>
        
        <!-- 中间聊天区域 -->
        <div class="chat-area">
            <div class="chat-header">
                <div id="currentSessionInfo">
                    <span class="text-muted">请选择一个会话开始对话</span>
                </div>
            </div>
            
            <div class="chat-messages" id="chatMessages">
                <!-- 聊天消息将通过JavaScript动态加载 -->
            </div>
            
            <div class="chat-input">
                <div class="input-toolbar">
                    <!-- <button type="button" class="btn btn-sm btn-default" onclick="insertEmoji('😊')">
                        <i class="fa fa-smile-o"></i> 表情
                    </button>
                    <button type="button" class="btn btn-sm btn-default" onclick="uploadFile()">
                        <i class="fa fa-paperclip"></i> 文件
                    </button> -->
                    <!-- <button type="button" class="btn btn-sm btn-warning pull-right" onclick="transferToManual()">
                        <i class="fa fa-user"></i> 转人工
                    </button> -->
                </div>
                <div class="input-area">
                    <textarea class="form-control input-text" id="messageInput" 
                             placeholder="请输入消息内容..." 
                             onkeydown="handleKeyDown(event)"></textarea>
                    <button type="button" class="btn btn-primary" onclick="sendMessage()">
                        <i class="fa fa-send"></i> 发送
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 右侧转人工消息列表 -->
        <div class="manual-service-panel">
            <div class="panel-header">
                <i class="fa fa-user-plus"></i> 转人工请求
                <span class="badge badge-warning pull-right" id="manualRequestCount">0</span>
            </div>
            <div id="manualRequestContainer">
                <!-- 转人工请求列表将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>
</div>

<th:block th:include="include :: footer" />
<script th:src="@{/js/plugins/layer/layer.min.js}"></script>
<script th:src="@{/js/plugins/webuploader/webuploader.min.js}"></script>
<script>
    var currentSessionId = null;
    var wsConnection = null;
    
    $(document).ready(function() {
        // 获取当前客服ID并建立WebSocket连接
        getCurrentUserId(function(serviceId) {
            if (serviceId) {
                console.log('[DEBUG] 页面加载时获取到客服ID:', serviceId);
                initWebSocket(serviceId);
            } else {
                console.error('[ERROR] 无法获取当前客服ID，WebSocket连接失败');
            }
        });
        
        loadSessionList();
        loadManualRequests();
        
        // 每30秒刷新一次数据
        setInterval(function() {
            loadSessionList();
            loadManualRequests();
        }, 30000);
    });
    
    // 初始化WebSocket连接
    function initWebSocket(serviceId) {
        console.log("[DEBUG] 开始初始化WebSocket连接，客服ID:", serviceId);
        
        if (typeof(WebSocket) == "undefined") {
            console.error("[ERROR] 您的浏览器不支持WebSocket");
            return;
        }
        
        if (serviceId) {
            createWebSocketConnection(serviceId);
        } else {
            console.error("[ERROR] 客服ID为空，无法建立WebSocket连接");
        }
    }
    
    // 心跳相关变量
    var heartbeatTimer = null;
    var heartbeatInterval = 30000; // 30秒心跳间隔
    var manualClose = false; // 手动关闭标志
    
    // 创建WebSocket连接
    function createWebSocketConnection(userId) {
        // 根据当前页面协议动态选择WebSocket协议
        var protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
        var wsUrl = protocol + "//bwy.opsoul.com/websocket/customer/" + userId;
        console.log("[DEBUG] WebSocket连接URL:", wsUrl);
        console.log("[DEBUG] 当前页面协议:", window.location.protocol, "选择WebSocket协议:", protocol);
        
        try {
            // 如果已有连接，先关闭
            if (wsConnection && wsConnection.readyState !== WebSocket.CLOSED) {
                manualClose = true;
                stopHeartbeat();
                wsConnection.close();
            }
            
            manualClose = false;
            wsConnection = new WebSocket(wsUrl);
            console.log("[DEBUG] WebSocket对象创建成功");
        } catch (e) {
            console.error("[ERROR] WebSocket对象创建失败:", e);
            // 添加更详细的错误信息
            if (e.name === 'SecurityError') {
                console.error("[ERROR] 安全错误: HTTPS页面无法连接到不安全的WebSocket端点");
                console.error("[ERROR] 请确保服务器支持WSS连接或在HTTP环境下访问页面");
            }
            return;
        }
        
        setupWebSocketHandlers();
    }
    
    // 获取当前用户ID
    function getCurrentUserId(callback) {
        $.ajax({
            url: ctx + "customer/service/current-user",
            type: "GET",
            dataType: "json",
            success: function(response) {
                if (response.code === 0 && response && response.userId) {
                    console.log("[DEBUG] 获取到当前用户ID:", response.userId);
                    callback(response.userId);
                } else {
                    console.error("[ERROR] 获取用户ID失败:", response);
                    callback(null);
                }
            },
            error: function(xhr, status, error) {
                console.error("[ERROR] 获取用户ID请求失败:", error);
                callback(null);
            }
        });
    }
    
    // 设置WebSocket事件处理器
    function setupWebSocketHandlers() {
        if (!wsConnection) {
            console.error("[ERROR] WebSocket连接对象不存在");
            return;
        }
        
        wsConnection.onopen = function() {
            console.log("[SUCCESS] WebSocket连接已建立");
            console.log("[DEBUG] WebSocket readyState:", wsConnection.readyState);
            // 启动心跳机制
            startHeartbeat();
        };
        
        wsConnection.onmessage = function(event) {
            console.log("[DEBUG] 收到WebSocket原始消息:", event.data);
            
            // 处理pong消息
            if (event.data === 'pong') {
                console.log("[DEBUG] 收到服务端pong响应");
                return;
            }
            
            try {
                var message = JSON.parse(event.data);
                console.log("[DEBUG] 解析后的消息对象:", message);
                handleWebSocketMessage(message);
            } catch (e) {
                console.error("[ERROR] 解析WebSocket消息失败:", e, "原始数据:", event.data);
            }
        };
        
        wsConnection.onclose = function(event) {
            console.log("[WARN] WebSocket连接已关闭", {
                code: event.code,
                reason: event.reason,
                wasClean: event.wasClean
            });
            
            // 停止心跳
            stopHeartbeat();
            
            // 如果不是手动关闭，则尝试重连
            if (!manualClose) {
                console.log("[DEBUG] 5秒后尝试重连WebSocket...");
                setTimeout(function() {
                    getCurrentUserId(function(serviceId) {
                        if (serviceId) {
                            initWebSocket(serviceId);
                        }
                    });
                }, 5000);
            }
        };
        
        wsConnection.onerror = function(error) {
            console.error("[ERROR] WebSocket连接错误:", error);
            console.log("[DEBUG] WebSocket readyState:", wsConnection ? wsConnection.readyState : 'undefined');
        };
    }
    
    // 启动心跳机制
    function startHeartbeat() {
        console.log("[DEBUG] 启动心跳机制，间隔:", heartbeatInterval + "ms");
        stopHeartbeat(); // 先停止之前的心跳
        heartbeatTimer = setInterval(function() {
            sendPing();
        }, heartbeatInterval);
    }
    
    // 停止心跳机制
    function stopHeartbeat() {
        if (heartbeatTimer) {
            console.log("[DEBUG] 停止心跳机制");
            clearInterval(heartbeatTimer);
            heartbeatTimer = null;
        }
    }
    
    // 发送ping消息
    function sendPing() {
        if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
            console.log("[DEBUG] 发送ping心跳消息");
            wsConnection.send('ping');
        } else {
            console.log("[WARN] WebSocket连接不可用，无法发送ping消息");
        }
    }
    
    // 处理WebSocket消息
    function handleWebSocketMessage(message) {
        console.log('[DEBUG] 开始处理WebSocket消息:', message);
        console.log('[DEBUG] 消息类型:', message.type);
        
        switch(message.type) {
            case 'NEW_MESSAGE':
                // 处理新消息
                console.log('[DEBUG] 处理新消息:', message);
                if (message.sessionId == currentSessionId) {
                    appendMessage(message.content, false, message.timestamp);
                    console.log('[DEBUG] 新消息已添加到当前会话');
                } else {
                    console.log('[DEBUG] 新消息不属于当前会话，sessionId:', message.sessionId, '当前会话:', currentSessionId);
                }
                loadSessionList(); // 刷新会话列表
                break;
            case 'SESSION_UPDATE':
                // 处理会话更新
                console.log('[DEBUG] 处理会话更新:', message);
                loadSessionList();
                break;
            case 'MANUAL_REQUEST':
                // 处理转人工请求
                console.log('[SUCCESS] 收到转人工请求通知:', message);
                console.log('[DEBUG] 开始刷新转人工请求列表...');
                loadManualRequests();
                // 添加闪烁动画效果
                triggerManualRequestBlink();
                
                // 触发父页面的菜单闪烁功能
                try {
                    if (parent && parent.startMenuBlink && typeof parent.startMenuBlink === 'function') {
                        parent.startMenuBlink('客服系统', 5000);
                        console.log('[DEBUG] 已触发父页面客服系统菜单闪烁');
                    } else {
                        console.log('[DEBUG] 父页面菜单闪烁功能不可用');
                    }
                } catch (e) {
                    console.error('[ERROR] 调用父页面菜单闪烁功能失败:', e);
                }
                
                // 显示通知
                console.log('[DEBUG] 显示转人工请求通知...');
                if (typeof $.modal !== 'undefined') {
                    $.modal.msg('收到新的转人工请求');
                    console.log('[DEBUG] 使用$.modal显示通知');
                } else {
                    alert('收到新的转人工请求');
                    console.log('[DEBUG] 使用alert显示通知');
                }
                break;
            case 'MANUAL_ACCEPTED':
                // 处理转人工请求被接受的通知
                console.log('[SUCCESS] 转人工请求已被接受:', message);
                // 刷新转人工请求列表
                loadManualRequests();
                // 显示成功通知
                if (typeof layer !== 'undefined') {
                    layer.msg('您的转人工请求已被客服接受，即将为您服务');
                } else {
                    alert('您的转人工请求已被客服接受，即将为您服务');
                }
                // 如果有会话ID，可以切换到对应会话
                if (message.sessionId && message.sessionId != currentSessionId) {
                    selectSession(message.sessionId);
                }
                break;
            case 'message':
                // 处理APP端发送的普通消息
                console.log('[DEBUG] 处理message类型消息:', message);
                console.log('[DEBUG] 消息内容:', message.message);
                console.log('[DEBUG] 发送者ID:', message.fromUserId);
                console.log('[DEBUG] 会话ID:', message.sessionId);
                
                // 如果消息属于当前会话，添加到聊天区域
                if (message.sessionId && message.sessionId == currentSessionId) {
                    appendMessage(message.message, true, message.timestamp);
                    console.log('[DEBUG] message类型消息已添加到当前会话');
                } else {
                    console.log('[DEBUG] message类型消息不属于当前会话，sessionId:', message.sessionId, '当前会话:', currentSessionId);
                }
                
                // 刷新会话列表以更新最新消息
                loadSessionList();
                break;
            default:
                console.warn('[WARN] 未知的消息类型:', message.type, '完整消息:', message);
                break;
        }
        
        console.log('[DEBUG] WebSocket消息处理完成');
    }
    
    // 加载会话列表
    function loadSessionList() {
        $.get('/customer/service/sessions', function(data) {
            var html = '';
            if (data.code === 0 && data.data) {
                data.data.forEach(function(session) {
                    var statusClass = getStatusClass(session.status);
                    var avatar = session.customerName ? session.customerName.charAt(0).toUpperCase() : 'U';
                    var activeClass = session.sessionId == currentSessionId ? 'active' : '';
                    
                    html += '<div class="session-item ' + activeClass + '" onclick="selectSession(\'' + session.sessionId + '\')">';
                    html += '  <div style="display: flex; align-items: center;">';
                    html += '    <div class="session-avatar">' + avatar + '</div>';
                    html += '    <div class="session-info">';
                    // 构建显示名称：用户名：手机号
                    var displayName = '';
                     if (session.userId) {
                        displayName = '访客：' + session.userId;
                    } else {
                        displayName = '访客：未知号码';
                    }
                    html += '      <div class="session-name">' + displayName + '</div>';
                    html += '      <div class="session-last-msg">' + (session.lastMessage || '暂无消息') + '</div>';
                    html += '      <div class="session-time">' + formatTime(session.lastMessageTime) + '</div>';
                    html += '    </div>';
                    html += '    <div class="session-status ' + statusClass + '"></div>';
                    html += '  </div>';
                    html += '</div>';
                });
                $('#sessionCount').text(data.data.length);
            }
            $('#sessionListContainer').html(html);
        });
    }
    
    // 选择会话
    function selectSession(sessionId) {
        currentSessionId = sessionId;
        $('.session-item').removeClass('active');
        $('[onclick="selectSession(\'' + sessionId + '\')"]').addClass('active');
        
        console.log('[DEBUG] 选择会话:', sessionId, '不重新建立WebSocket连接');
        
        // 直接加载聊天历史和更新会话信息，不重新建立WebSocket连接
        loadChatHistory(sessionId);
        updateCurrentSessionInfo(sessionId);
    }
    
    // 加载聊天历史
    function loadChatHistory(sessionId) {
        console.log('[DEBUG] 开始加载聊天历史 - sessionId:', sessionId);
        
        // 显示加载状态
        $('#chatMessages').html('<div class="loading-message">正在加载聊天历史...</div>');
        
        // 首先获取会话信息以获取用户ID
        $.get('/customer/service/sessions')
            .done(function(sessionsData) {
                if (sessionsData.code === 0 && sessionsData.data) {
                    // 查找当前会话
                    var currentSession = sessionsData.data.find(function(session) {
                        return session.sessionId === sessionId;
                    });
                    
                    if (currentSession && currentSession.userId) {
                        console.log('[DEBUG] 找到会话用户ID:', currentSession.userId);
                        // 通过用户ID获取所有历史记录
                        loadChatHistoryByUserId(currentSession.userId, sessionId);
                    } else {
                        console.log('[DEBUG] 未找到用户ID，使用原有方式加载会话历史');
                        // 如果没有用户ID，回退到原有方式
                        loadChatHistoryBySessionId(sessionId);
                    }
                } else {
                    console.log('[DEBUG] 获取会话列表失败，使用原有方式加载会话历史');
                    loadChatHistoryBySessionId(sessionId);
                }
            })
            .fail(function(xhr, status, error) {
                console.error('[ERROR] 获取会话列表失败:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    error: error
                });
                // 回退到原有方式
                loadChatHistoryBySessionId(sessionId);
            });
    }
    
    // 通过用户ID加载聊天历史
    function loadChatHistoryByUserId(userId, currentSessionId) {
        console.log('[DEBUG] 通过用户ID加载聊天历史 - userId:', userId);
        
        $.get('/system/chatHistory/app/user/' + userId)
            .done(function(data) {
                console.log('[DEBUG] 用户聊天历史API响应:', data);
                
                var html = '';
                if (data.code === 0 && data.data && data.data.length > 0) {
                    console.log('[DEBUG] 用户聊天历史消息数量:', data.data.length);
                    
                    // 按时间排序
                    var sortedMessages = data.data.sort(function(a, b) {
                        return new Date(a.createTime) - new Date(b.createTime);
                    });
                    
                    // 按会话分组显示
                    var sessionGroups = {};
                    sortedMessages.forEach(function(message) {
                        if (!sessionGroups[message.sessionId]) {
                            sessionGroups[message.sessionId] = [];
                        }
                        sessionGroups[message.sessionId].push(message);
                    });
                    
                    // 渲染消息，当前会话高亮显示
                    Object.keys(sessionGroups).forEach(function(sessionId) {
                        var isCurrentSession = sessionId === currentSessionId;
                        var separatorClass = isCurrentSession ? 'session-separator current-session' : 'session-separator';
                        var separatorText = isCurrentSession ? '当前会话' : '历史会话 - ' + sessionId;
                        
                        html += '<div class="' + separatorClass + '">';
                        html += '  <span class="session-separator-text">' + separatorText + '</span>';
                        html += '</div>';
                        
                        sessionGroups[sessionId].forEach(function(message) {
                        console.log('[DEBUG] 消息类型:', message.messageType, '消息内容:', message.content);
                        // messageType为"user"的消息显示在左边(received=true)，其他消息显示在右边(received=false)
                        // received样式：左对齐，白色背景；sent样式：右对齐，蓝色背景
                        var isReceived = message.messageType === 'user';
                        html += createMessageHtml(message.content, isReceived, message.createTime, isCurrentSession);
                        });
                    });
                } else {
                    console.log('[DEBUG] 用户聊天历史数据为空');
                    html = '<div class="no-history-message">暂无聊天记录</div>';
                }
                
                $('#chatMessages').html(html);
                scrollToBottom();
                console.log('[DEBUG] 用户聊天历史加载完成');
            })
            .fail(function(xhr, status, error) {
                console.error('[ERROR] 用户聊天历史API调用失败:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    error: error,
                    response: xhr.responseText
                });
                // 回退到原有方式
                loadChatHistoryBySessionId(currentSessionId);
            });
    }
    
    // 通过会话ID加载聊天历史（原有方式）
    function loadChatHistoryBySessionId(sessionId) {
        console.log('[DEBUG] 通过会话ID加载聊天历史 - sessionId:', sessionId);
        
        $.get('/customer/service/messages/' + sessionId)
            .done(function(data) {
                console.log('[DEBUG] 会话聊天历史API响应:', data);
                
                var html = '';
                if (data.code === 0 && data.data) {
                    console.log('[DEBUG] 会话聊天历史消息数量:', data.data.length);
                    data.data.forEach(function(message) {
                    console.log('[DEBUG] 消息类型:', message.messageType, '消息内容:', message.content);
                    // messageType为"user"的消息显示在左边(received=true)，其他消息显示在右边(received=false)
                    // received样式：左对齐，白色背景；sent样式：右对齐，蓝色背景
                    var isReceived = message.messageType === 'user';
                    html += createMessageHtml(message.content, isReceived, message.createTime, true);
                    });
                } else {
                    console.log('[DEBUG] 会话聊天历史数据为空或返回错误:', data);
                    html = '<div class="no-history-message">暂无聊天记录</div>';
                }
                
                $('#chatMessages').html(html);
                scrollToBottom();
                console.log('[DEBUG] 会话聊天历史加载完成');
            })
            .fail(function(xhr, status, error) {
                console.error('[ERROR] 会话聊天历史API调用失败:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    error: error,
                    response: xhr.responseText
                });
                $('#chatMessages').html('<div class="no-history-message" style="color: #f5222d;">加载聊天历史失败，请稍后重试</div>');
            });
    }
    
    // 创建消息HTML
    function createMessageHtml(content, isReceived, timestamp, isCurrentSession) {
        var messageClass = isReceived ? 'received' : 'sent';
        if (isCurrentSession === false) {
            messageClass += ' history-message';
        }
        var html = '<div class="message-item ' + messageClass + '">';
        html += '  <div class="message-content">';
        html += '    <div>' + content + '</div>';
        html += '    <div class="message-time">' + formatTime(timestamp) + '</div>';
        html += '  </div>';
        html += '</div>';
        return html;
    }
    
    // 发送消息
    function sendMessage() {
        if (!currentSessionId) {
            layer.msg('请先选择一个会话');
            return;
        }
        
        var content = $('#messageInput').val().trim();
        if (!content) {
            layer.msg('请输入消息内容');
            return;
        }
        
        // 检查WebSocket连接状态
        if (!wsConnection || wsConnection.readyState !== WebSocket.OPEN) {
            layer.confirm('WebSocket连接已断开，消息可能无法实时推送给客户。是否继续发送？', {
                btn: ['继续发送', '重新连接']
            }, function(index) {
                // 继续发送
                doSendMessage(content);
                layer.close(index);
            }, function(index) {
                // 重新连接
                initWebSocket();
                layer.close(index);
                layer.msg('正在重新连接WebSocket...');
            });
            return;
        }
        
        doSendMessage(content);
    }
    
    // 执行发送消息
    function doSendMessage(content) {
        var messageData = {
            sessionId: currentSessionId,
            content: content,
            senderType: 'SERVICE'
        };
        
        $.post('/customer/service/send', messageData, function(data) {
            if (data.code === 0) {
                appendMessage(content, false, new Date());
                $('#messageInput').val('');
                loadSessionList(); // 刷新会话列表
            } else {
                layer.msg('发送失败: ' + data.msg);
            }
        }).fail(function() {
            layer.msg('网络错误，消息发送失败');
        });
    }
    
    // 添加消息到聊天区域
    function appendMessage(content, isReceived, timestamp) {
        var messageHtml = createMessageHtml(content, isReceived, timestamp);
        $('#chatMessages').append(messageHtml);
        scrollToBottom();
    }
    
    // 滚动到底部
    function scrollToBottom() {
        var chatMessages = document.getElementById('chatMessages');
        chatMessages.scrollTop = chatMessages.scrollHeight;
    }
    
    // 处理键盘事件
    function handleKeyDown(event) {
        if (event.ctrlKey && event.keyCode === 13) {
            sendMessage();
        }
    }
    
    // 转人工
    function transferToManual() {
        if (!currentSessionId) {
            layer.msg('请先选择一个会话');
            return;
        }
        
        layer.prompt({
            title: '转人工服务',
            formType: 2,
            value: '',
            area: ['300px', '200px']
        }, function(reason, index) {
            $.post('/customer/service/transfer', {
                sessionId: currentSessionId,
                reason: reason
            }, function(data) {
                if (data.code === 0) {
                    layer.msg('转人工请求已提交');
                    loadManualRequests();
                } else {
                    layer.msg('转人工失败: ' + data.msg);
                }
            });
            layer.close(index);
        });
    }
    
    // 加载转人工请求列表
    function loadManualRequests() {
        console.log('开始加载转人工请求列表...');
        
        $.get('/customer/service/manual-requests')
            .done(function(data) {
                console.log('转人工请求API响应:', data);
                
                if (data.code === 0) {
                    var html = '';
                    var requests = data.data || [];
                    
                    console.log('转人工请求数量:', requests.length);
                    
                    if (requests.length === 0) {
                        html = '<div class="empty-state">暂无转人工请求</div>';
                    } else {
                        requests.forEach(function(request, index) {
                            console.log('处理转人工请求 ' + (index + 1) + ':', request);
                            html += '<div class="manual-request-item" data-id="' + request.manualSessionId + '">';
                            html += '  <div class="request-info">';
                            html += '    <div class="session-id">访客: ' + request.userId + '</div>';
                           // html += '    <div class="reason">原因: ' + (request.reason || '无') + '</div>';
                            html += '    <div class="time">' + formatTime(request.createTime) + '</div>';
                            html += '  </div>';
                            html += '  <div class="request-actions">';
                            html += '    <button class="btn btn-success btn-sm" onclick="acceptManualRequest(' + request.manualSessionId + ')">接受</button>';
                            html += '    <button class="btn btn-danger btn-sm" onclick="rejectManualRequest(' + request.manualSessionId + ')">拒绝</button>';
                            html += '  </div>';
                            html += '</div>';
                        });
                    }
                    
                    $('#manualRequestContainer').html(html);
                    $('#manualRequestCount').text(requests.length);
                    console.log('转人工请求列表渲染完成，容器内容:', $('#manualRequestContainer').html());
                } else {
                    console.error('转人工请求API返回错误:', data.msg);
                    $('#manualRequestContainer').html('<div class="error-state">加载失败: ' + data.msg + '</div>');
                }
            })
            .fail(function(xhr, status, error) {
                console.error('转人工请求API调用失败:', {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    error: error,
                    response: xhr.responseText
                });
                $('#manualRequestContainer').html('<div class="error-state">网络错误，请稍后重试</div>');
            });
    }
    
    // 接受转人工请求
    function acceptManualRequest(requestId) {
        // 停止闪烁动画
        stopManualRequestBlink();
        
        $.post('/customer/service/manual-requests/' + requestId + '/accept', function(data) {
            if (data.code === 0) {
                layer.msg('已接受转人工请求');
                
                // 获取转人工请求的详细信息，包含sessionId
                console.log('[DEBUG] 开始获取转人工请求详情 - requestId:', requestId);
                $.get('/customer/service/manual-requests/' + requestId)
                    .done(function(requestData) {
                        console.log('[DEBUG] 获取转人工请求详情成功:', requestData);
                        
                        if (requestData.code === 0 && requestData.data) {
                            var sessionId = requestData.data.sessionId;
                            if (sessionId) {
                                console.log('[DEBUG] 获取到sessionId:', sessionId);
                                
                                // 直接切换到对应的会话，不重新建立WebSocket连接
                                console.log('[DEBUG] 接受转人工请求，切换到会话:', sessionId);
                                selectSession(sessionId);
                            } else {
                                console.error('[ERROR] 转人工请求数据中缺少sessionId:', requestData.data);
                                layer.msg('转人工请求数据异常：缺少会话ID');
                            }
                        } else {
                            console.error('[ERROR] 转人工请求数据格式错误:', requestData);
                            layer.msg('获取转人工请求详情失败：' + (requestData.msg || '数据格式错误'));
                        }
                    })
                    .fail(function(xhr, status, error) {
                        console.error('[ERROR] 获取转人工请求详情失败:', {
                            requestId: requestId,
                            status: xhr.status,
                            statusText: xhr.statusText,
                            error: error,
                            response: xhr.responseText
                        });
                        layer.msg('获取转人工请求详情失败，请检查网络连接或联系管理员');
                    });
                
                loadManualRequests();
                loadSessionList();
            } else {
                layer.msg('操作失败: ' + data.msg);
            }
        });
    }
    
    // 拒绝转人工请求
    function rejectManualRequest(requestId) {
        // 停止闪烁动画
        stopManualRequestBlink();
        
        $.post('/customer/service/manual-requests/' + requestId + '/reject', function(data) {
            if (data.code === 0) {
                layer.msg('已拒绝转人工请求');
                loadManualRequests();
            } else {
                layer.msg('操作失败: ' + data.msg);
            }
        });
    }
    
    // 更新当前会话信息
    function updateCurrentSessionInfo(sessionId) {
        $.get('/customer/service/sessions/' + sessionId, function(data) {
            if (data.code === 0 && data.data) {
                var session = data.data;
                var html = '<strong>' + (session.customerName || '访客' + session.userId) + '</strong>';
                html += ' <span class="text-muted">(' + getStatusText(session.status) + ')</span>';
                $('#currentSessionInfo').html(html);
            }
        });
    }
    
    // 获取状态样式类
    function getStatusClass(status) {
        switch(status) {
            case 'ONLINE': return 'status-online';
            case 'BUSY': return 'status-busy';
            default: return 'status-offline';
        }
    }
    
    // 获取状态文本
    function getStatusText(status) {
        switch(status) {
            case 'ONLINE': return '在线';
            case 'BUSY': return '忙碌';
            case 'OFFLINE': return '离线';
            default: return '未知';
        }
    }
    
    // 格式化时间
    function formatTime(timestamp) {
        if (!timestamp) return '';
        var date = new Date(timestamp);
        var now = new Date();
        var diff = now - date;
        
        if (diff < 60000) { // 1分钟内
            return '刚刚';
        } else if (diff < 3600000) { // 1小时内
            return Math.floor(diff / 60000) + '分钟前';
        } else if (diff < 86400000) { // 24小时内
            return Math.floor(diff / 3600000) + '小时前';
        } else {
            return date.getMonth() + 1 + '/' + date.getDate() + ' ' + 
                   String(date.getHours()).padStart(2, '0') + ':' + 
                   String(date.getMinutes()).padStart(2, '0');
        }
    }
    
    // 插入表情
    function insertEmoji(emoji) {
        var input = document.getElementById('messageInput');
        var start = input.selectionStart;
        var end = input.selectionEnd;
        var text = input.value;
        input.value = text.substring(0, start) + emoji + text.substring(end);
        input.focus();
        input.setSelectionRange(start + emoji.length, start + emoji.length);
    }
    
    // 触发转人工请求闪烁动画
    function triggerManualRequestBlink() {
        console.log('[DEBUG] 触发转人工请求闪烁动画');
        
        // 为转人工请求面板添加闪烁类
        $('.manual-service-panel').addClass('blink-notification');
        $('.panel-header').addClass('blink-notification');
        
        // 5秒后自动移除闪烁效果
        setTimeout(function() {
            $('.manual-service-panel').removeClass('blink-notification');
            $('.panel-header').removeClass('blink-notification');
            console.log('[DEBUG] 转人工请求闪烁动画已停止');
        }, 5000);
    }
    
    // 停止转人工请求闪烁动画
    function stopManualRequestBlink() {
        $('.manual-service-panel').removeClass('blink-notification');
        $('.panel-header').removeClass('blink-notification');
        console.log('[DEBUG] 手动停止转人工请求闪烁动画');
    }
    
    // 为转人工请求面板添加点击事件，点击时停止闪烁
     $(document).ready(function() {
         $('.manual-service-panel').on('click', function() {
             stopManualRequestBlink();
         });
         
         // 为转人工请求项添加点击事件，处理请求时停止闪烁
         $(document).on('click', '.manual-request-item', function() {
             stopManualRequestBlink();
         });
     });
    
    // 文件上传
    function uploadFile() {
        layer.msg('文件上传功能开发中...');
    }
</script>
</body>
</html>