<template>
	<a-modal title="用户会话详情" :open="visible" :width="800" :destroy-on-close="true" :footer="null" @cancel="handleCancel">
		<div class="sessions-content">
			<!-- 用户信息 -->
			<div class="user-info">
				<a-descriptions :column="3" bordered size="small">
					<a-descriptions-item label="用户名">{{ userInfo.username }}</a-descriptions-item>
					<a-descriptions-item label="真实姓名">{{ userInfo.real_name }}</a-descriptions-item>
					<a-descriptions-item label="状态">
						<a-tag :color="userInfo.is_online ? 'success' : 'default'">
							{{ userInfo.is_online ? '在线' : '离线' }}
						</a-tag>
					</a-descriptions-item>
					<a-descriptions-item label="邮箱" :span="2">{{ userInfo.email }}</a-descriptions-item>
					<a-descriptions-item label="手机号">{{ userInfo.phone }}</a-descriptions-item>
				</a-descriptions>
			</div>

			<!-- 会话列表 -->
			<div class="sessions-list">
				<div class="list-header">
					<span>会话列表（{{ sessions.length }} 个）</span>
					<a-button type="link" size="small" danger @click="handleOfflineAll"> 全部下线 </a-button>
				</div>
				<a-list :data-source="sessions" :loading="loading" size="small">
					<template #renderItem="{ item }">
						<a-list-item>
							<a-list-item-meta>
								<template #avatar>
									<a-avatar shape="square" :icon="item.device_type === 'pc' ? 'DesktopOutlined' : 'MobileOutlined'" />
								</template>
								<template #title>
									<div class="session-title">
										<span>{{ getDeviceName(item.device_type) }}</span>
										<a-tag :color="item.is_online ? 'success' : 'default'" size="small">
											{{ item.is_online ? '活跃' : '过期' }}
										</a-tag>
									</div>
								</template>
								<template #description>
									<div class="session-info">
										<div><span class="label">IP地址：</span>{{ item.ip_address }}</div>
										<div><span class="label">登录时间：</span>{{ formatDate(item.created_at) }}</div>
										<div><span class="label">最后活跃：</span>{{ formatDate(item.last_active_at) }}</div>
										<div v-if="item.user_agent"><span class="label">浏览器：</span>{{ item.user_agent }}</div>
									</div>
								</template>
							</a-list-item-meta>
							<template #actions>
								<a-popconfirm v-if="item.is_online" title="确定强制该会话下线吗？" @confirm="handleOffline(item)">
									<a-button type="link" size="small" danger> 强制下线 </a-button>
								</a-popconfirm>
								<a-tag v-else color="default" size="small">已过期</a-tag>
							</template>
						</a-list-item>
					</template>
				</a-list>
				<a-empty v-if="!loading && sessions.length === 0" description="暂无会话数据" :image-size="80" />
			</div>
		</div>
		<template #footer>
			<a-button @click="handleCancel">关 闭</a-button>
		</template>
	</a-modal>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import authApi from '@/api/auth'

defineOptions({
	name: 'OnlineUserSessions',
})

const emit = defineEmits(['success', 'closed'])

const visible = ref(false)
const loading = ref(false)

// 用户信息
const userInfo = reactive({
	id: '',
	username: '',
	real_name: '',
	email: '',
	phone: '',
	is_online: false,
})

// 会话列表
const sessions = ref([])

// 打开对话框
const open = () => {
	visible.value = true
	return {
		open,
		setData,
		close,
	}
}

// 关闭对话框
const close = () => {
	visible.value = false
}

// 处理取消
const handleCancel = () => {
	emit('closed')
	visible.value = false
}

// 加载用户会话
const loadUserSessions = async (userId) => {
	try {
		loading.value = true
		const res = await authApi.onlineUser.sessions.get(userId)
		loading.value = false

		if (res.code === 200) {
			sessions.value = res.data || []
		}
	} catch (error) {
		console.error('加载用户会话失败:', error)
		loading.value = false
		message.error('加载会话失败')
	}
}

// 设置数据
const setData = (data) => {
	userInfo.id = data.id
	userInfo.username = data.username
	userInfo.real_name = data.real_name
	userInfo.email = data.email
	userInfo.phone = data.phone
	userInfo.is_online = data.is_online

	// 加载会话列表
	loadUserSessions(data.id)
}

// 强制会话下线
const handleOffline = async (session) => {
	try {
		const res = await authApi.onlineUser.offline.post(userInfo.id, {
			token: session.token,
		})
		if (res.code === 200) {
			message.success('强制下线成功')
			emit('success')
			// 重新加载会话列表
			loadUserSessions(userInfo.id)
		} else {
			message.error(res.message || '操作失败')
		}
	} catch (error) {
		console.error('强制下线失败:', error)
		message.error('操作失败')
	}
}

// 全部下线
const handleOfflineAll = async () => {
	try {
		const res = await authApi.onlineUser.offlineAll.post(userInfo.id)
		if (res.code === 200) {
			message.success('全部下线成功')
			emit('success')
			// 重新加载会话列表
			loadUserSessions(userInfo.id)
		} else {
			message.error(res.message || '操作失败')
		}
	} catch (error) {
		console.error('全部下线失败:', error)
		message.error('操作失败')
	}
}

// 获取设备名称
const getDeviceName = (deviceType) => {
	const deviceMap = {
		pc: '电脑端',
		mobile: '手机端',
		tablet: '平板端',
		unknown: '未知设备',
	}
	return deviceMap[deviceType] || deviceMap.unknown
}

// 格式化日期
const formatDate = (date) => {
	if (!date) return '-'
	const d = new Date(date)
	return d.toLocaleString('zh-CN', {
		year: 'numeric',
		month: '2-digit',
		day: '2-digit',
		hour: '2-digit',
		minute: '2-digit',
		second: '2-digit',
	})
}

// 暴露方法给父组件
defineExpose({
	open,
	setData,
	close,
})
</script>

<style scoped lang="scss">
.sessions-content {
	.user-info {
		margin-bottom: 20px;

		:deep(.ant-descriptions-item-label) {
			background-color: #fafafa;
			font-weight: 500;
		}
	}

	.sessions-list {
		.list-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 16px;
			padding-bottom: 12px;
			border-bottom: 1px solid #f0f0f0;

			span {
				font-size: 16px;
				font-weight: 500;
				color: #262626;
			}
		}

		:deep(.ant-list-item) {
			padding: 16px;
			border-bottom: 1px solid #f0f0f0;

			&:hover {
				background-color: #fafafa;
			}
		}

		.session-title {
			display: flex;
			align-items: center;
			gap: 8px;
			font-size: 16px;
			font-weight: 500;
		}

		.session-info {
			margin-top: 8px;
			color: #595959;

			div {
				margin-bottom: 4px;

				&:last-child {
					margin-bottom: 0;
				}
			}

			.label {
				color: #8c8c8c;
				margin-right: 4px;
			}
		}
	}
}
</style>
