<template>
    <div class="vpn-server-online-user">
        <el-row :gutter="20">
            <!-- 左侧服务器列表 -->
            <el-col :span="8">
                <el-card shadow="hover">
                    <template #header>
                        <div class="card-header">
                            <span>服务器列表</span>
                        </div>
                    </template>
                    <div class="server-list">
                        <div 
                            v-for="server in serverList" 
                            :key="server.server_id"
                            class="server-item"
                            :class="{ active: selectedServer?.server_id === server.server_id }"
                            @click="selectServer(server)"
                        >
                            <div class="server-info">
                                <div class="server-name">
                                    <span class="status-indicator" :class="{ 'online': onlineServers.includes(server.server_id) }"></span>
                                    {{ server.name }}
                                </div>
                                <div class="server-ip">{{ server.server_ip }}</div>
                            </div>
                        </div>
                        <el-empty v-if="serverList.length === 0" description="暂无服务器配置" />
                    </div>
                </el-card>
            </el-col>

            <!-- 右侧在线用户列表 -->
            <el-col :span="16">
                <el-card shadow="hover" v-if="selectedServer">
                    <template #header>
                        <div class="card-header">
                            <span>{{ selectedServer.name }} - 在线用户 ({{ onlineUsers.length }})</span>
                            <el-button type="primary" @click="KickOutAllOnlineUser" :loading="loading">
                                踢出所有用户
                            </el-button>
                            <el-button type="primary" @click="refreshOnlineUsers" :loading="loading">
                                刷新
                            </el-button>
                        </div>
                    </template>
                    
                    <el-table 
                        :data="onlineUsers" 
                        style="width: 100%" 
                        v-loading="loading"
                        stripe
                    >
                        <el-table-column prop="id" label="密钥ID" width="120" />
                        <el-table-column prop="user_name" label="用户名" width="120" />
                        <el-table-column prop="private_ipv4" label="内网IPv4" width="140" />
                        <el-table-column prop="uuid" label="会话ID" min-width="200" show-overflow-tooltip />
                        <el-table-column prop="host_info.hostname" label="主机名" min-width="200" show-overflow-tooltip />
                        <el-table-column prop="host_info.os" label="操作系统" min-width="200" show-overflow-tooltip>
                            <!-- tags 操作系统, windows 蓝色； linux 绿色；macos 黄色; android 红色; ios 紫色; 其他 橙色 -->
                            <template #default="scope">
                                <el-tag v-if="scope.row.host_info.os === 'windows'" type="primary" size="small">Windows</el-tag>
                                <el-tag v-else-if="scope.row.host_info.os === 'linux'" type="success" size="small">Linux</el-tag>
                                <el-tag v-else-if="scope.row.host_info.os === 'macos'" type="warning" size="small">macOS</el-tag>
                                <el-tag v-else-if="scope.row.host_info.os === 'android'" type="danger" size="small">Android</el-tag>
                                <el-tag v-else-if="scope.row.host_info.os === 'ios'" type="info" size="small">iOS</el-tag>
                                <el-tag v-else type="danger" size="small">未知</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="last_update_time" label="最后更新时间" width="180">
                            <template #default="scope">
                                {{ formatTime(scope.row.last_update_time) }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="last_update_time" label="操作" width="240" #default="scope">
                            <el-button type="primary" @click="KickOutSomeUser(scope.row)">踢出</el-button>
                            <el-button type="primary" @click="showHostInfo(scope.row)">主机信息</el-button>
                        </el-table-column>
                    </el-table>

                    <el-empty v-if="!loading && onlineUsers.length === 0" description="该服务器暂无在线用户" />
                </el-card>

                <el-card shadow="hover" v-else>
                    <el-empty description="请选择要查看的服务器" />
                </el-card>
            </el-col>
        </el-row>
    </div>
    <!-- 主机信息弹窗 -->
    <el-dialog title="主机信息" width="65%" v-model="show_host_info" class="host-info-dialog">
        <div class="host-info-header">
            <el-icon class="host-info-icon"><Monitor /></el-icon>
            <span class="host-info-title">{{ hostInfo.hostname || '未知主机' }}</span>
            <el-tag v-if="hostInfo.virtualizationRole" :type="hostInfo.virtualizationRole === 'host' ? 'warning' : 'info'" size="small">
                {{ hostInfo.virtualizationRole === 'host' ? '宿主机' : '虚拟机' }}
            </el-tag>
        </div>
        
        <el-tabs v-model="activeHostInfoTab" type="card" class="host-info-tabs">
            <!-- 基本信息标签页 -->
            <el-tab-pane label="基本信息" name="basic">
                <el-descriptions :column="2" border class="host-info-descriptions">
                    <el-descriptions-item label="主机名">
                        <div class="info-item-with-icon">
                            <el-icon><Computer /></el-icon>
                            <span>{{ hostInfo.hostname || '-' }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="主机ID">
                        <div class="info-item-with-icon">
                            <el-icon><Tag /></el-icon>
                            <span>{{ hostInfo.hostId || '-' }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="运行时间">
                        <div class="info-item-with-icon">
                            <el-icon><Timer /></el-icon>
                            <span>{{ formatUptime(hostInfo.uptime) }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="启动时间">
                        <div class="info-item-with-icon">
                            <el-icon><Calendar /></el-icon>
                            <span>{{ formatBootTime(hostInfo.bootTime) }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="进程数">
                        <div class="info-item-with-icon">
                            <el-icon><Cpu /></el-icon>
                            <span>{{ hostInfo.procs || 0 }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="客户端版本">
                        <div class="info-item-with-icon">
                            <el-icon><Box /></el-icon>
                            <el-tag type="success" size="small">{{ hostInfo.client_version || '-' }}</el-tag>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </el-tab-pane>
            
            <!-- 系统信息标签页 -->
            <el-tab-pane label="系统信息" name="system">
                <el-descriptions :column="2" border class="host-info-descriptions">
                    <el-descriptions-item label="操作系统">
                        <el-tag type="primary" size="small">{{ hostInfo.os || '-' }}</el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="平台">
                        {{ hostInfo.platform || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="平台家族">
                        {{ hostInfo.platformFamily || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="平台版本">
                        {{ hostInfo.platformVersion || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="内核版本">
                        {{ hostInfo.kernelVersion || '-' }}
                    </el-descriptions-item>
                    <el-descriptions-item label="内核架构">
                        <el-tag type="warning" size="small">{{ hostInfo.kernelArch || '-' }}</el-tag>
                    </el-descriptions-item>
                </el-descriptions>
            </el-tab-pane>
            
            <!-- 虚拟化信息标签页 -->
            <el-tab-pane label="虚拟化信息" name="virtualization">
                <el-descriptions :column="2" border class="host-info-descriptions">
                    <el-descriptions-item label="虚拟化系统">
                        <div class="info-item-with-icon">
                            <el-icon><Cloud /></el-icon>
                            <span>{{ hostInfo.virtualizationSystem || '无' }}</span>
                        </div>
                    </el-descriptions-item>
                    <el-descriptions-item label="虚拟化角色">
                        <div class="info-item-with-icon">
                            <el-icon><InfoFilled /></el-icon>
                            <span>{{ hostInfo.virtualizationRole || '物理机' }}</span>
                        </div>
                    </el-descriptions-item>
                </el-descriptions>
            </el-tab-pane>
        </el-tabs>
        
        <template #footer>
            <el-button type="primary" @click="show_host_info = false">关闭</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { GetVPNServerConfigHandler, GetVPNServerOnlineListHandler,GetServerOnlineUsers,KickOutOnlineUser } from '@/api/vpn';
import { on } from 'events';
import { VPNStatus, OnlineUserInfo, OnlineUserInfoList, ServerConfig, HostInfo } from '@/types/vpn';
import { Monitor, Cpu, Timer, Calendar, Box, InfoFilled } from '@element-plus/icons-vue';

const serverList = ref<ServerConfig[]>([]);
const selectedServer = ref<ServerConfig | null>(null);
const onlineUsers = ref<OnlineUserInfoList[]>([]);
const onlineServers = ref<string[]>([]);
const loading = ref(false);
const show_host_info = ref(false);
const hostInfo = ref<HostInfo>({} as HostInfo);
const activeHostInfoTab = ref('basic');
const rules = ref({});
let timer: number | null = null;
let timer2: number | null = null;

// 获取服务器配置列表
const getServerConfigs = async () => {
    try {
        const response = await GetVPNServerConfigHandler();
        serverList.value = response.data;
    } catch (error) {
        ElMessage.error('获取服务器配置失败');
        console.error(error);
    }
};

const showHostInfo = (user:OnlineUserInfoList) =>{
    show_host_info.value = true;
    hostInfo.value = user.host_info || createEmptyHostInfo();
    activeHostInfoTab.value = 'basic';
    console.log(user);
}

// 创建空的 HostInfo 对象
const createEmptyHostInfo = (): HostInfo => {
    return {
        hostname: '',
        uptime: 0,
        bootTime: 0,
        procs: 0,
        os: '',
        platform: '',
        platformFamily: '',
        platformVersion: '',
        kernelVersion: '',
        kernelArch: '',
        virtualizationSystem: '',
        virtualizationRole: '',
        hostId: '',
        client_version: ''
    };
}

// 格式化运行时间
const formatUptime = (uptime: number): string => {
    if (!uptime || uptime <= 0) return '-';
    
    const days = Math.floor(uptime / (24 * 60 * 60));
    const hours = Math.floor((uptime % (24 * 60 * 60)) / (60 * 60));
    const minutes = Math.floor((uptime % (60 * 60)) / 60);
    const seconds = Math.floor(uptime % 60);
    
    const parts = [];
    if (days > 0) parts.push(`${days}天`);
    if (hours > 0) parts.push(`${hours}小时`);
    if (minutes > 0) parts.push(`${minutes}分钟`);
    if (seconds > 0 || parts.length === 0) parts.push(`${seconds}秒`);
    
    return parts.join(' ');
}

// 格式化启动时间
const formatBootTime = (bootTime: number): string => {
    if (!bootTime || bootTime <= 0) return '-';
    
    const date = new Date(bootTime * 1000);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

const KickOutAllOnlineUser = async() =>{
    try{
        // 询问用户是否确认踢出所有用户
        const result = await ElMessageBox.confirm(
            `确定要踢出所有在线用户吗？此操作将强制断开所有用户的连接。`,
            '确认踢出所有用户',
            {
                confirmButtonText: '确认踢出',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        if (result === 'confirm') {
            let req = {
                server_id: selectedServer.value.server_id,
                type: 1, //all
                session: [{
                    "user_id": 1,
                    "session": "kickout all"
                }]
            }
            let resp = await KickOutOnlineUser(req);
            if (resp && resp["code"] == 0){
                ElMessage.success("踢出成功");
            }else{
                ElMessage.error(resp["message"] || "踢出失败");
            }
        }
    }catch(error){
        // 如果用户点击取消，则不显示错误信息
        if (error !== 'cancel') {
            ElMessage.error("踢出失败");
            console.error(error);
        }
    }
}

const KickOutSomeUser = async(user:OnlineUserInfoList) =>{
    try{
        // 询问用户是否确认踢出该用户
        const result = await ElMessageBox.confirm(
            `确定要踢出用户 "${user.user_name}" 吗？此操作将强制断开该用户的连接。`,
            '确认踢出用户',
            {
                confirmButtonText: '确认踢出',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        if (result === 'confirm') {
            let req = {
                server_id: selectedServer.value.server_id,
                sessions: [{
                    "user_id": user.user_id,
                    "session": user.uuid
                }]
            }
            let resp = await KickOutOnlineUser(req);
            if (resp && resp["code"] == 0){
                ElMessage.success("踢出成功");
            }else{
                ElMessage.error(resp["message"] || "踢出失败");
            }
        }
    }catch(error){
        // 如果用户点击取消，则不显示错误信息
        if (error !== 'cancel') {
            ElMessage.error("踢出失败");
            console.error(error);
        }
    }
}

// 获取在线服务器列表
const getOnlineServers = async () => {
    try {
        const response = await GetVPNServerOnlineListHandler();
        if (response.data && Array.isArray(response.data)) {
            onlineServers.value = response.data.map((server: any) => server.server_id);
        }
    } catch (error) {
        console.error('获取在线服务器状态失败:', error);
    }
};

// 获取指定服务器的在线用户
const getOnlineUsers = async (serverId: string) => {
    if (!serverId) return;
    
    loading.value = true;
    try {
        const response = await GetServerOnlineUsers(serverId);
        if (response["code"] === 0) {
            if(response.data){
                // 处理每个用户对象，确保 host_info 字段有有效的值
                onlineUsers.value = response.data.map((user: any) => ({
                    ...user,
                    host_info: user.host_info || createEmptyHostInfo()
                }));
            }else{
                onlineUsers.value = [];
            }
        } else {
            ElMessage.error(response["message"]);
        }
    } catch (error) {
        console.error('获取在线用户失败:', error);
        ElMessage.error('获取在线用户失败');
        onlineUsers.value = [];
    } finally {
        loading.value = false;
    }
};

const getOnlineUsers2 = async (serverId: string) => {
    if (!serverId) return;
    
    //loading.value = true;
    try {
        const response = await GetServerOnlineUsers(serverId);
        if (response["code"] === 0) {
            if(response.data){
                // 处理每个用户对象，确保 host_info 字段有有效的值
                onlineUsers.value = response.data.map((user: any) => ({
                    ...user,
                    host_info: user.host_info || createEmptyHostInfo()
                }));
            }else{
                onlineUsers.value = [];
            }
        } else {
            ElMessage.error(response["message"]);
        }
    } catch (error) {
        console.error('获取在线用户失败:', error);
        ElMessage.error('获取在线用户失败');
        onlineUsers.value = [];
    } finally {
        loading.value = false;
    }
};

// 刷新在线用户
const refreshOnlineUsers = () => {
    if (selectedServer.value) {
        getOnlineUsers(selectedServer.value.server_id);
    }
};

// 选择服务器
const selectServer = (server: ServerConfig) => {
    selectedServer.value = server;
    getOnlineUsers(server.server_id);
};

// 格式化时间戳
const formatTime = (timestamp: number) => {
    if (!timestamp) return '-';
    const date = new Date(timestamp * 1000);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
};

// 启动定时查询
const startOnlineStatusTimer = () => {
    // 立即查询一次
    getOnlineServers();
    // 设置定时器，每2秒查询一次
    timer = window.setInterval(() => {
        getOnlineServers();
    }, 10000);
    timer2 = window.setInterval(() => {
        if (selectedServer.value){
            getOnlineUsers2(selectedServer.value.server_id);
        }
    }, 5000);
};

// 停止定时查询
const stopOnlineStatusTimer = () => {
    if (timer !== null) {
        clearInterval(timer);
        timer = null;
    }
    if (timer2 !== null){
        clearInterval(timer2);
        timer2 = null;
    }
};

// 组件挂载时获取数据
onMounted(() => {
    getServerConfigs();
    startOnlineStatusTimer();
});

// 组件卸载时清理定时器
onUnmounted(() => {
    stopOnlineStatusTimer();
});
</script>

<style scoped>
.vpn-server-online-user {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
}

.server-list {
    max-height: 400px;
    overflow-y: auto;
}

.server-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    margin-bottom: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.server-item:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
}

.server-item.active {
    background-color: #ecf5ff;
    border-color: #409eff;
}

.server-info {
    flex: 1;
}

.server-name {
    font-weight: bold;
    margin-bottom: 4px;
    display: flex;
    align-items: center;
}

.status-indicator {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #909399;
    margin-right: 8px;
    transition: background-color 0.3s;
}

.status-indicator.online {
    background-color: #67c23a;
    box-shadow: 0 0 4px rgba(103, 194, 58, 0.5);
}

.server-ip {
    font-size: 12px;
    color: #909399;
}

.el-table {
    margin-top: 10px;
}

/* 主机信息对话框样式 */
.host-info-dialog :deep(.el-dialog__body) {
    padding-top: 16px;
}

.host-info-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
}

.host-info-icon {
    font-size: 24px;
    color: #409eff;
    margin-right: 12px;
}

.host-info-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-right: 12px;
}

.host-info-tabs {
    margin-top: 8px;
}

.host-info-descriptions {
    margin-top: 16px;
}

.host-info-descriptions :deep(.el-descriptions__label) {
    font-weight: 500;
    color: #606266;
    width: 120px;
}

.host-info-descriptions :deep(.el-descriptions__content) {
    color: #303133;
    font-weight: 400;
}

.info-item-with-icon {
    display: flex;
    align-items: center;
    gap: 8px;
}

.info-item-with-icon .el-icon {
    color: #909399;
    font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .host-info-dialog :deep(.el-dialog) {
        width: 90% !important;
        max-width: 90%;
    }
    
    .host-info-descriptions :deep(.el-descriptions) {
        --el-descriptions-table-border: none;
    }
    
    .host-info-descriptions :deep(.el-descriptions__table) {
        display: block;
    }
    
    .host-info-descriptions :deep(.el-descriptions__row) {
        display: block;
        margin-bottom: 12px;
        border-bottom: 1px solid #f0f0f0;
        padding-bottom: 12px;
    }
    
    .host-info-descriptions :deep(.el-descriptions__cell) {
        display: block;
        padding: 8px 0;
        border: none;
    }
    
    .host-info-descriptions :deep(.el-descriptions__label) {
        display: block;
        width: 100%;
        margin-bottom: 4px;
        font-weight: 600;
        color: #409eff;
    }
    
    .host-info-descriptions :deep(.el-descriptions__content) {
        display: block;
        width: 100%;
    }
}

/* 动画效果 */
.host-info-dialog :deep(.el-dialog) {
    transition: all 0.3s ease;
}

.host-info-tabs :deep(.el-tabs__item) {
    transition: all 0.2s ease;
}

.host-info-tabs :deep(.el-tabs__item:hover) {
    color: #409eff;
}

.host-info-tabs :deep(.el-tabs__item.is-active) {
    color: #409eff;
    font-weight: 500;
}
</style>