<template>
	<div class="crew-log-panel">
		<div class="log-header">
			<el-radio-group v-model="activeTab" size="small">
				<el-radio-button value="all">全部</el-radio-button>
				<el-radio-button v-for="name in agentNames" :key="name" :value="name">{{ name }}</el-radio-button>
			</el-radio-group>
			<el-button size="small" text @click="$emit('clear')">清空</el-button>
		</div>
		<div ref="logContainer" class="log-list">
			<div v-for="(log, i) in filteredLogs" :key="i" class="log-item" :class="'level-' + log.level">
				<span class="log-time">{{ formatTime(log.timestamp) }}</span>
				<span class="log-agent">[{{ log.agentName }}]</span>
				<span class="log-msg">{{ log.message }}</span>
			</div>
			<div v-if="!filteredLogs.length" class="log-empty">暂无日志</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick } from 'vue';

const props = defineProps<{ logs: any[] }>();
defineEmits<{ (e: 'clear'): void }>();

const activeTab = ref('all');
const logContainer = ref<HTMLElement>();

const agentNames = computed(() => {
	const names = new Set<string>();
	props.logs.forEach(l => { if (l.agentName) names.add(l.agentName); });
	return [...names];
});

const filteredLogs = computed(() => {
	if (activeTab.value === 'all') return props.logs;
	return props.logs.filter(l => l.agentName === activeTab.value);
});

function formatTime(ts: string) {
	if (!ts) return '';
	return new Date(ts).toLocaleTimeString();
}

watch(() => props.logs.length, async () => {
	await nextTick();
	if (logContainer.value) logContainer.value.scrollTop = logContainer.value.scrollHeight;
});
</script>

<style scoped lang="scss">
.crew-log-panel { display: flex; flex-direction: column; height: 100%; }
.log-header { display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; border-bottom: 1px solid #ebeef5; }
.log-list { flex: 1; overflow-y: auto; padding: 8px 12px; font-family: monospace; font-size: 12px; }
.log-item { padding: 2px 0; line-height: 1.6; }
.log-time { color: #909399; margin-right: 8px; }
.log-agent { color: #409eff; margin-right: 4px; }
.log-msg { color: #303133; }
.level-error .log-msg { color: #f56c6c; }
.level-tool .log-msg { color: #e6a23c; }
.log-empty { color: #c0c4cc; text-align: center; padding: 20px; }
</style>
