<?php
// 包含API代理脚本
require_once 'api_proxy.php';

// 获取实例列表
function getInstances($page = 1, $pageSize = 10, $search = '') {
    $url = $_SERVER['PHP_SELF'] . '?action=instances&page=' . $page . '&page_size=' . $pageSize;
    if (!empty($search)) {
        $url .= '&instance_name=' . urlencode($search);
    }
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// 获取实例详情
function getInstanceDetail($uuid, $daemonId) {
    $url = $_SERVER['PHP_SELF'] . '?action=instanceDetail&instanceUuid=' . $uuid . '&daemonId=' . $daemonId;
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// 执行实例操作
function performInstanceAction($action, $uuid, $daemonId, $command = '') {
    $url = $_SERVER['PHP_SELF'] . '?action=' . $action . '&instanceUuid=' . $uuid . '&daemonId=' . $daemonId;
    
    if (!empty($command)) {
        $url .= '&command=' . urlencode($command);
    }
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}

// 获取输出日志
function getOutputLog($uuid, $daemonId, $size = 1024) {
    $url = $_SERVER['PHP_SELF'] . '?action=getOutput&instanceUuid=' . $uuid . '&daemonId=' . $daemonId . '&size=' . $size;
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    
    return json_decode($response, true);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCSManager服务器管理</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3b82f6',
                        secondary: '#10b981',
                        danger: '#ef4444',
                        warning: '#f59e0b',
                        info: '#06b6d4',
                        dark: '#1e293b',
                        light: '#f8fafc'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .server-card {
                @apply bg-white rounded-lg shadow-md p-4 mb-4 transition-all duration-300 hover:shadow-lg;
            }
            .server-status {
                @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
            }
            .btn {
                @apply inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2;
            }
            .btn-primary {
                @apply bg-primary text-white hover:bg-primary/90 focus:ring-primary/50;
            }
            .btn-secondary {
                @apply bg-secondary text-white hover:bg-secondary/90 focus:ring-secondary/50;
            }
            .btn-danger {
                @apply bg-danger text-white hover:bg-danger/90 focus:ring-danger/50;
            }
            .btn-warning {
                @apply bg-warning text-white hover:bg-warning/90 focus:ring-warning/50;
            }
            .btn-outline {
                @apply border-gray-300 text-gray-700 hover:bg-gray-50 focus:ring-primary/50;
            }
            .badge {
                @apply inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium;
            }
            .badge-online {
                @apply bg-green-100 text-green-800;
            }
            .badge-offline {
                @apply bg-gray-100 text-gray-800;
            }
            .badge-starting {
                @apply bg-blue-100 text-blue-800;
            }
            .badge-stopping {
                @apply bg-yellow-100 text-yellow-800;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-gray-800 min-h-screen flex flex-col">
    <!-- 导航栏 -->
    <header class="bg-dark text-white shadow-lg">
        <div class="container mx-auto px-4 py-3 flex items-center justify-between">
            <div class="flex items-center space-x-2">
                <i class="fa fa-server text-primary text-2xl"></i>
                <h1 class="text-xl font-bold">MCSManager 服务器管理</h1>
            </div>
            <nav>
                <ul class="flex space-x-6">
                    <li><a href="#" class="flex items-center hover:text-primary transition-colors duration-200"><i class="fa fa-home mr-1"></i> 首页</a></li>
                    <li><a href="#" class="flex items-center hover:text-primary transition-colors duration-200"><i class="fa fa-cog mr-1"></i> 设置</a></li>
                    <li><a href="#" class="flex items-center hover:text-primary transition-colors duration-200"><i class="fa fa-question-circle mr-1"></i> 帮助</a></li>
                </ul>
            </nav>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-grow container mx-auto px-4 py-6">
        <!-- 状态概览 -->
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-lg shadow p-4 flex items-center">
                <div class="rounded-full bg-blue-100 p-3 mr-4">
                    <i class="fa fa-server text-primary text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">总服务器</p>
                    <p class="text-2xl font-bold">12</p>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-4 flex items-center">
                <div class="rounded-full bg-green-100 p-3 mr-4">
                    <i class="fa fa-check-circle text-secondary text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">运行中</p>
                    <p class="text-2xl font-bold">8</p>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-4 flex items-center">
                <div class="rounded-full bg-red-100 p-3 mr-4">
                    <i class="fa fa-times-circle text-danger text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">已停止</p>
                    <p class="text-2xl font-bold">4</p>
                </div>
            </div>
            <div class="bg-white rounded-lg shadow p-4 flex items-center">
                <div class="rounded-full bg-yellow-100 p-3 mr-4">
                    <i class="fa fa-refresh text-warning text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-500">负载</p>
                    <p class="text-2xl font-bold">42%</p>
                </div>
            </div>
        </div>

        <!-- 服务器列表 -->
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold">服务器列表</h2>
                <div class="flex space-x-2">
                    <div class="relative">
                        <input type="text" id="search-instance" placeholder="搜索服务器..." class="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                        <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
                    </div>
                    <button id="refresh-instances" class="btn btn-outline">
                        <i class="fa fa-refresh mr-1"></i> 刷新
                    </button>
                </div>
            </div>

            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">IP/端口</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">运行时间</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                        </tr>
                    </thead>
                    <tbody id="server-list" class="bg-white divide-y divide-gray-200">
                        <!-- 服务器列表将通过JavaScript动态加载 -->
                        <tr class="animate-pulse">
                            <td colspan="5" class="px-6 py-4 text-center text-gray-500">
                                <i class="fa fa-spinner fa-spin mr-2"></i> 加载服务器列表中...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <!-- 分页 -->
            <div class="flex justify-between items-center mt-4">
                <div class="text-sm text-gray-500">
                    显示 <span id="showing-range">1-10</span> 条，共 <span id="total-count">0</span> 条
                </div>
                <div class="flex space-x-1">
                    <button class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" id="prev-page" disabled>
                        <i class="fa fa-chevron-left"></i>
                    </button>
                    <button class="px-3 py-1 bg-primary text-white rounded-md">1</button>
                    <button class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50">2</button>
                    <button class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50">3</button>
                    <button class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50">...</button>
                    <button class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50">12</button>
                    <button class="px-3 py-1 border border-gray-300 rounded-md hover:bg-gray-50" id="next-page">
                        <i class="fa fa-chevron-right"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 服务器详情模态框 -->
        <div id="server-detail-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg shadow-xl max-w-3xl w-full max-h-[90vh] flex flex-col">
                <div class="flex justify-between items-center p-4 border-b">
                    <h3 class="text-lg font-bold" id="modal-title">服务器详情</h3>
                    <button id="close-modal" class="text-gray-500 hover:text-gray-700">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                <div class="flex-grow overflow-y-auto p-4" id="modal-content">
                    <!-- 模态框内容将通过JavaScript动态加载 -->
                    <div class="text-center py-8">
                        <i class="fa fa-spinner fa-spin text-3xl text-primary mb-4"></i>
                        <p class="text-gray-500">加载服务器详情中...</p>
                    </div>
                </div>
                <div class="p-4 border-t flex justify-end space-x-3">
                    <button id="close-modal-btn" class="btn btn-outline">
                        关闭
                    </button>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="bg-dark text-white py-4">
        <div class="container mx-auto px-4 text-center">
            <p>&copy; 2025 MCSManager 服务器管理系统 | 版本 1.0.0</p>
        </div>
    </footer>

    <script>
        // 服务器列表数据
        let servers = [];
        let currentPage = 1;
        let totalPages = 1;
        let searchTerm = '';
        
        // DOM 元素
        const serverListEl = document.getElementById('server-list');
        const refreshBtn = document.getElementById('refresh-instances');
        const searchInput = document.getElementById('search-instance');
        const serverDetailModal = document.getElementById('server-detail-modal');
        const modalTitle = document.getElementById('modal-title');
        const modalContent = document.getElementById('modal-content');
        const closeModalBtn = document.getElementById('close-modal-btn');
        const closeModal = document.getElementById('close-modal');
        const prevPageBtn = document.getElementById('prev-page');
        const nextPageBtn = document.getElementById('next-page');
        const showingRangeEl = document.getElementById('showing-range');
        const totalCountEl = document.getElementById('total-count');
        
        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            fetchServers();
            
            // 事件监听器
            refreshBtn.addEventListener('click', fetchServers);
            searchInput.addEventListener('input', debounce(() => {
                searchTerm = searchInput.value.trim();
                currentPage = 1;
                fetchServers();
            }, 300));
            
            closeModalBtn.addEventListener('click', () => {
                serverDetailModal.classList.add('hidden');
            });
            
            closeModal.addEventListener('click', () => {
                serverDetailModal.classList.add('hidden');
            });
            
            serverDetailModal.addEventListener('click', (e) => {
                if (e.target === serverDetailModal) {
                    serverDetailModal.classList.add('hidden');
                }
            });
            
            prevPageBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    fetchServers();
                }
            });
            
            nextPageBtn.addEventListener('click', () => {
                if (currentPage < totalPages) {
                    currentPage++;
                    fetchServers();
                }
            });
        });
        
        // 获取服务器列表
        function fetchServers() {
            serverListEl.innerHTML = `
                <tr class="animate-pulse">
                    <td colspan="5" class="px-6 py-4 text-center text-gray-500">
                        <i class="fa fa-spinner fa-spin mr-2"></i> 加载服务器列表中...
                    </td>
                </tr>
            `;
            
            // 模拟API请求
            setTimeout(() => {
                // 这里应该调用后端API获取数据
                // 为了演示，使用模拟数据
                servers = generateMockServers(12);
                
                // 应用搜索过滤
                if (searchTerm) {
                    servers = servers.filter(server => 
                        server.name.toLowerCase().includes(searchTerm.toLowerCase())
                    );
                }
                
                // 计算分页
                const pageSize = 10;
                totalPages = Math.ceil(servers.length / pageSize);
                const startIdx = (currentPage - 1) * pageSize;
                const endIdx = Math.min(startIdx + pageSize, servers.length);
                const paginatedServers = servers.slice(startIdx, endIdx);
                
                // 更新UI
                renderServerList(paginatedServers);
                
                // 更新分页信息
                updatePagination(servers.length, startIdx, endIdx);
                
                // 更新分页按钮状态
                prevPageBtn.disabled = currentPage === 1;
                nextPageBtn.disabled = currentPage === totalPages;
            }, 800);
        }
        
        // 渲染服务器列表
        function renderServerList(servers) {
            serverListEl.innerHTML = '';
            
            if (servers.length === 0) {
                serverListEl.innerHTML = `
                    <tr>
                        <td colspan="5" class="px-6 py-4 text-center text-gray-500">
                            没有找到匹配的服务器
                        </td>
                    </tr>
                `;
                return;
            }
            
            servers.forEach(server => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors duration-150';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 h-10 w-10 bg-gray-200 rounded-full flex items-center justify-center">
                                <i class="fa fa-server text-primary"></i>
                            </div>
                            <div class="ml-4">
                                <div class="text-sm font-medium text-gray-900">${server.name}</div>
                                <div class="text-sm text-gray-500">${server.id}</div>
                            </div>
                        </div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="server-status ${getStatusClass(server.status)}">
                            ${getStatusText(server.status)}
                        </span>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <div class="text-sm text-gray-900">${server.ip}:${server.port}</div>
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                        ${server.status === 'online' ? server.uptime : '-'}
                    </td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                        <button class="text-primary hover:text-primary/80 mr-3 view-details" data-id="${server.id}">
                            <i class="fa fa-eye mr-1"></i> 详情
                        </button>
                        ${server.status === 'online' ? `
                            <button class="text-danger hover:text-danger/80 mr-3 stop-server" data-id="${server.id}">
                                <i class="fa fa-stop mr-1"></i> 停止
                            </button>
                            <button class="text-warning hover:text-warning/80 restart-server" data-id="${server.id}">
                                <i class="fa fa-refresh mr-1"></i> 重启
                            </button>
                        ` : `
                            <button class="text-secondary hover:text-secondary/80 start-server" data-id="${server.id}">
                                <i class="fa fa-play mr-1"></i> 启动
                            </button>
                        `}
                    </td>
                `;
                serverListEl.appendChild(row);
            });
            
            // 添加事件监听器
            document.querySelectorAll('.view-details').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    openServerDetails(serverId);
                });
            });
            
            document.querySelectorAll('.start-server').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    performServerAction(serverId, 'start');
                });
            });
            
            document.querySelectorAll('.stop-server').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    performServerAction(serverId, 'stop');
                });
            });
            
            document.querySelectorAll('.restart-server').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    performServerAction(serverId, 'restart');
                });
            });
        }
        
        // 更新分页信息
        function updatePagination(totalCount, startIdx, endIdx) {
            totalCountEl.textContent = totalCount;
            showingRangeEl.textContent = `${startIdx + 1}-${endIdx}`;
        }
        
        // 获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 'online': return '在线';
                case 'offline': return '离线';
                case 'starting': return '启动中';
                case 'stopping': return '停止中';
                default: return '未知';
            }
        }
        
        // 获取状态类
        function getStatusClass(status) {
            switch (status) {
                case 'online': return 'bg-green-100 text-green-800';
                case 'offline': return 'bg-gray-100 text-gray-800';
                case 'starting': return 'bg-blue-100 text-blue-800';
                case 'stopping': return 'bg-yellow-100 text-yellow-800';
                default: return 'bg-gray-100 text-gray-800';
            }
        }
        
        // 打开服务器详情
        function openServerDetails(serverId) {
            serverDetailModal.classList.remove('hidden');
            modalTitle.textContent = '服务器详情';
            
            // 显示加载状态
            modalContent.innerHTML = `
                <div class="text-center py-8">
                    <i class="fa fa-spinner fa-spin text-3xl text-primary mb-4"></i>
                    <p class="text-gray-500">加载服务器详情中...</p>
                </div>
            `;
            
            // 模拟API请求
            setTimeout(() => {
                // 找到对应的服务器
                const server = servers.find(s => s.id === serverId);
                
                if (!server) {
                    modalContent.innerHTML = `
                        <div class="text-center py-8">
                            <i class="fa fa-exclamation-circle text-3xl text-warning mb-4"></i>
                            <p class="text-gray-500">找不到该服务器</p>
                        </div>
                    `;
                    return;
                }
                
                // 构建详情内容
                modalContent.innerHTML = `
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h4 class="text-lg font-semibold mb-4">基本信息</h4>
                            <div class="space-y-3">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">名称:</span>
                                    <span class="font-medium">${server.name}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">ID:</span>
                                    <span class="font-medium">${server.id}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">状态:</span>
                                    <span class="font-medium">
                                        <span class="badge ${getStatusClass(server.status)}">
                                            ${getStatusText(server.status)}
                                        </span>
                                    </span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">IP/端口:</span>
                                    <span class="font-medium">${server.ip}:${server.port}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">版本:</span>
                                    <span class="font-medium">${server.version}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">内存限制:</span>
                                    <span class="font-medium">${server.memoryLimit} MB</span>
                                </div>
                                ${server.status === 'online' ? `
                                <div class="flex justify-between">
                                    <span class="text-gray-600">运行时间:</span>
                                    <span class="font-medium">${server.uptime}</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">在线玩家:</span>
                                    <span class="font-medium">${server.players.online}/${server.players.max}</span>
                                </div>
                                ` : ''}
                            </div>
                        </div>
                        
                        <div>
                            <h4 class="text-lg font-semibold mb-4">操作</h4>
                            <div class="space-y-3">
                                ${server.status === 'online' ? `
                                <button class="btn btn-danger w-full stop-server" data-id="${server.id}">
                                    <i class="fa fa-stop mr-1"></i> 停止服务器
                                </button>
                                <button class="btn btn-warning w-full restart-server" data-id="${server.id}">
                                    <i class="fa fa-refresh mr-1"></i> 重启服务器
                                </button>
                                ` : `
                                <button class="btn btn-secondary w-full start-server" data-id="${server.id}">
                                    <i class="fa fa-play mr-1"></i> 启动服务器
                                </button>
                                `}
                                <button class="btn btn-outline w-full delete-server" data-id="${server.id}">
                                    <i class="fa fa-trash mr-1"></i> 删除服务器
                                </button>
                            </div>
                            
                            <h4 class="text-lg font-semibold mt-6 mb-4">发送命令</h4>
                            <div class="space-y-2">
                                <input type="text" id="server-command" placeholder="输入命令..." class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                                <button class="btn btn-primary w-full send-command" data-id="${server.id}">
                                    <i class="fa fa-paper-plane mr-1"></i> 发送命令
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <h4 class="text-lg font-semibold mt-6 mb-4">控制台输出</h4>
                    <div class="bg-gray-900 text-gray-100 rounded-md p-3 h-64 overflow-y-auto" id="console-output">
                        <pre class="font-mono text-sm">${server.consoleOutput}</pre>
                    </div>
                    
                    <div class="mt-4 flex justify-end">
                        <button class="btn btn-outline refresh-output" data-id="${server.id}">
                            <i class="fa fa-refresh mr-1"></i> 刷新输出
                        </button>
                    </div>
                `;
                
                // 添加事件监听器
                modalContent.querySelector('.start-server')?.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    performServerAction(serverId, 'start');
                });
                
                modalContent.querySelector('.stop-server')?.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    performServerAction(serverId, 'stop');
                });
                
                modalContent.querySelector('.restart-server')?.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    performServerAction(serverId, 'restart');
                });
                
                modalContent.querySelector('.delete-server')?.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    if (confirm('确定要删除此服务器吗？此操作不可撤销！')) {
                        performServerAction(serverId, 'delete');
                    }
                });
                
                modalContent.querySelector('.send-command')?.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    const command = document.getElementById('server-command').value.trim();
                    
                    if (command) {
                        sendServerCommand(serverId, command);
                        document.getElementById('server-command').value = '';
                    }
                });
                
                modalContent.querySelector('.refresh-output')?.addEventListener('click', (e) => {
                    const serverId = e.currentTarget.getAttribute('data-id');
                    refreshServerOutput(serverId);
                });
                
            }, 800);
        }
        
        // 执行服务器操作
        function performServerAction(serverId, action) {
            // 找到对应的服务器
            const server = servers.find(s => s.id === serverId);
            if (!server) return;
            
            // 显示加载状态
            const loadingHtml = `
                <div class="text-center py-8">
                    <i class="fa fa-spinner fa-spin text-3xl text-primary mb-4"></i>
                    <p class="text-gray-500">执行${action === 'start' ? '启动' : action === 'stop' ? '停止' : action === 'restart' ? '重启' : '删除'}操作中...</p>
                </div>
            `;
            
            if (action === 'delete') {
                modalContent.innerHTML = loadingHtml;
            } else {
                // 更新状态
                if (action === 'start') {
                    server.status = 'starting';
                } else if (action === 'stop' || action === 'restart') {
                    server.status = 'stopping';
                }
                
                // 刷新列表
                renderServerList(servers.slice((currentPage - 1) * 10, currentPage * 10));
            }
            
            // 模拟API请求
            setTimeout(() => {
                if (action === 'delete') {
                    // 从列表中移除服务器
                    servers = servers.filter(s => s.id !== serverId);
                    
                    // 刷新列表
                    fetchServers();
                    
                    // 关闭模态框
                    serverDetailModal.classList.add('hidden');
                    
                    // 显示成功消息
                    showNotification('服务器删除成功', 'success');
                } else {
                    // 更新状态
                    if (action === 'start') {
                        server.status = 'online';
                        server.uptime = '刚刚启动';
                    } else if (action === 'stop') {
                        server.status = 'offline';
                    } else if (action === 'restart') {
                        server.status = 'online';
                    }
                    
                    // 刷新列表
                    renderServerList(servers.slice((currentPage - 1) * 10, currentPage * 10));
                    
                    // 如果模态框是打开的，刷新详情
                    if (!serverDetailModal.classList.contains('hidden') && modalTitle.textContent === `服务器详情 - ${server.name}`) {
                        openServerDetails(serverId);
                    }
                    
                    // 显示成功消息
                    showNotification(`服务器${action === 'start' ? '启动' : action === 'stop' ? '停止' : '重启'}成功`, 'success');
                }
            }, 1500);
        }
        
        // 发送服务器命令
        function sendServerCommand(serverId, command) {
            // 找到对应的服务器
            const server = servers.find(s => s.id === serverId);
            if (!server) return;
            
            // 显示加载状态
            const consoleOutputEl = document.getElementById('console-output');
            const originalContent = consoleOutputEl.innerHTML;
            
            consoleOutputEl.innerHTML = `
                <div class="animate-pulse">
                    <pre class="font-mono text-sm">${originalContent}</pre>
                    <pre class="font-mono text-sm mt-2">> ${command}</pre>
                    <pre class="font-mono text-sm text-yellow-300 mt-2">正在发送命令...</pre>
                </div>
            `;
            
            // 模拟API请求
            setTimeout(() => {
                // 更新控制台输出
                const newOutput = `${originalContent}\n> ${command}\n[${new Date().toLocaleTimeString()}] 命令已执行`;
                server.consoleOutput = newOutput;
                
                consoleOutputEl.innerHTML = `<pre class="font-mono text-sm">${newOutput}</pre>`;
                
                // 滚动到底部
                consoleOutputEl.scrollTop = consoleOutputEl.scrollHeight;
                
                // 显示成功消息
                showNotification('命令已发送', 'success');
            }, 800);
        }
        
        // 刷新服务器输出
        function refreshServerOutput(serverId) {
            // 找到对应的服务器
            const server = servers.find(s => s.id === serverId);
            if (!server) return;
            
            // 显示加载状态
            const consoleOutputEl = document.getElementById('console-output');
            const originalContent = consoleOutputEl.innerHTML;
            
            consoleOutputEl.innerHTML = `
                <div class="animate-pulse">
                    <pre class="font-mono text-sm">${originalContent}</pre>
                    <pre class="font-mono text-sm text-yellow-300 mt-2">正在刷新输出...</pre>
                </div>
            `;
            
            // 模拟API请求
            setTimeout(() => {
                // 更新控制台输出
                const newOutput = `${server.consoleOutput}\n[${new Date().toLocaleTimeString()}] 输出已刷新`;
                server.consoleOutput = newOutput;
                
                consoleOutputEl.innerHTML = `<pre class="font-mono text-sm">${newOutput}</pre>`;
                
                // 滚动到底部
                consoleOutputEl.scrollTop = consoleOutputEl.scrollHeight;
            }, 500);
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            // 创建通知元素
            const notification = document.createElement('div');
            notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg transform transition-all duration-500 translate-x-full opacity-0 z-50 ${
                type === 'success' ? 'bg-green-500 text-white' : 
                type === 'error' ? 'bg-red-500 text-white' : 
                type === 'warning' ? 'bg-yellow-500 text-white' : 
                'bg-blue-500 text-white'
            }`;
            notification.innerHTML = `
                <div class="flex items-center">
                    <i class="fa ${
                        type === 'success' ? 'fa-check-circle' : 
                        type === 'error' ? 'fa-exclamation-circle' : 
                        type === 'warning' ? 'fa-exclamation-triangle' : 
                        'fa-info-circle'
                    } mr-2"></i>
                    <span>${message}</span>
                </div>
            `;
            
            // 添加到页面
            document.body.appendChild(notification);
            
            // 显示通知
            setTimeout(() => {
                notification.classList.remove('translate-x-full', 'opacity-0');
            }, 100);
            
            // 自动关闭
            setTimeout(() => {
                notification.classList.add('translate-x-full', 'opacity-0');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 500);
            }, 3000);
        }
        
        // 生成模拟服务器数据
        function generateMockServers(count) {
            const servers = [];
            const statuses = ['online', 'offline', 'starting', 'stopping'];
            const names = ['生存服务器', '创造服务器', '冒险服务器', '空岛服务器', '小游戏服务器', 'RPG服务器', 'PVP服务器', '科技服务器', '建筑服务器', '模组服务器', '纯净服', '原版服务器'];
            
            for (let i = 0; i < count; i++) {
                const status = statuses[Math.floor(Math.random() * statuses.length)];
                const uptime = status === 'online' ? generateUptime() : '';
                const players = status === 'online' ? {
                    online: Math.floor(Math.random() * 20),
                    max: 20
                } : { online: 0, max: 20 };
                
                servers.push({
                    id: 'uuid-' + Math.random().toString(36).substr(2, 10),
                    name: names[i] || `服务器${i+1}`,
                    status,
                    ip: '127.0.0.1',
                    port: 25565 + i,
                    version: '1.19.2',
                    memoryLimit: 1024 + (Math.floor(Math.random() * 5) * 1024),
                    uptime,
                    players,
                    consoleOutput: generateConsoleOutput(status)
                });
            }
            
            return servers;
        }
        
        // 生成随机运行时间
        function generateUptime() {
            const hours = Math.floor(Math.random() * 24);
            const minutes = Math.floor(Math.random() * 60);
            
            if (hours > 0) {
                return `${hours}小时${minutes}分钟`;
            }
            
            return `${minutes}分钟`;
        }
        
        // 生成控制台输出
        function generateConsoleOutput(status) {
            if (status === 'offline') {
                return '[12:34:56] [Server thread/INFO]: Stopping server\n[12:34:56] [Server thread/INFO]: Saving players\n[12:34:57] [Server thread/INFO]: Saving worlds\n[12:34:57] [Server thread/INFO]: ThreadedAnvilChunkStorage (world): All chunks are saved\n[12:34:57] [Server thread/INFO]: ThreadedAnvilChunkStorage (world_nether): All chunks are saved\n[12:34:57] [Server thread/INFO]: ThreadedAnvilChunkStorage (world_the_end): All chunks are saved';
            }
            
            const messages = [
                '[12:34:56] [Server thread/INFO]: Starting minecraft server version 1.19.2',
                '[12:34:56] [Server thread/INFO]: Loading properties',
                '[12:34:56] [Server thread/INFO]: Default game type: SURVIVAL',
                '[12:34:56] [Server thread/INFO]: Generating keypair',
                '[12:34:56] [Server thread/INFO]: Starting Minecraft server on *:25565',
                '[12:34:56] [Server thread/INFO]: Using default channel type',
                '[12:34:57] [Server thread/INFO]: Preparing level "world"',
                '[12:34:57] [Server thread/INFO]: Preparing start region for dimension minecraft:overworld',
                '[12:34:58] [Server thread/INFO]: Preparing spawn area: 0%',
                '[12:34:59] [Server thread/INFO]: Preparing spawn area: 33%',
                '[12:35:00] [Server thread/INFO]: Preparing spawn area: 66%',
                '[12:35:01] [Server thread/INFO]: Done (4.500s)! For help, type "help"',
                '[12:35:10] [Server thread/INFO]: player1 joined the game',
                '[12:35:20] [Server thread/INFO]: player2 joined the game',
                '[12:35:30] [Server thread/INFO]: player1 moved to world_nether',
                '[12:35:40] [Server thread/INFO]: player1 issued server command: /tp player2',
                '[12:35:50] [Server thread/INFO]: player1 moved to world',
                '[12:36:00] [Server thread/INFO]: <player1> Hello, world!',
                '[12:36:10] [Server thread/INFO]: <player2> Hi there!',
                '[12:36:20] [Server thread/INFO]: player3 joined the game',
                '[12:36:30] [Server thread/INFO]: player3 issued server command: /gamemode creative',
                '[12:36:40] [Server thread/INFO]: Set player3's game mode to Creative Mode'
            ];
            
            const startIndex = status === 'starting' ? 0 : Math.floor(Math.random() * (messages.length - 10));
            return messages.slice(startIndex, startIndex + 10).join('\n');
        }
        
        // 防抖函数
        function debounce(func, wait) {
            let timeout;
            return function(...args) {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    func.apply(this, args);
                }, wait);
            };
        }
    </script>
</body>
</html>    