<template>
	<div class="crew-monitor">
		<div class="monitor-header">
			<span class="title">运行监控</span>
			<el-button type="primary" size="small" @click="onManualTrigger">手动触发</el-button>
		</div>

		<div class="monitor-body">
			<div class="run-list-area">
				<crew-run-table
					ref="runTableRef"
					:crew-id="crewIdFilter"
					@select="onSelectRun"
					@control="onControl"
					@resume="onResume"
				/>
			</div>

			<div v-if="selectedRun" class="run-detail-area">
				<crew-run-detail
					:run="selectedRun"
					:tasks="runTasks"
					:logs="runLogs"
					@stop="onControl($event, 'stop')"
					@resume="onResumeWithMessage"
					@clear-logs="monitor.clearLogs()"
				/>
			</div>
			<div v-else class="run-detail-area empty">
				<el-empty description="选择一条运行记录查看详情" :image-size="80" />
			</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useCool } from '/@/cool';
import { useCrewMonitor } from '../hooks/crew-monitor';
import { useCrewStore } from '../store/crew';
import CrewRunTable from '../components/crew/crew-run-table.vue';
import CrewRunDetail from '../components/crew/crew-run-detail.vue';

const route = useRoute();
const { service } = useCool();
const monitor = useCrewMonitor();
const crewStore = useCrewStore();

const runTableRef = ref<InstanceType<typeof CrewRunTable>>();
const selectedRun = ref<any>(null);
const runTasks = ref<any[]>([]);
const crewIdFilter = ref<number | undefined>(undefined);
const autoRunTriggered = ref(false);

const runLogs = computed(() => {
	if (!selectedRun.value) return [];
	return monitor.logs.value.filter(l => l.runId === selectedRun.value.id);
});

onMounted(async () => {
	monitor.connect();
	await crewStore.loadCrewList();

	// URL 参数支持
	const qCrewId = route.query.crewId;
	if (qCrewId) crewIdFilter.value = Number(qCrewId);

	// 自动运行（防重复）
	if (route.query.autoRun && qCrewId && !autoRunTriggered.value) {
		autoRunTriggered.value = true;
		const triggerInput = route.query.triggerInput ? String(route.query.triggerInput) : '';
		const runId = await service.netaclaw.crew_trigger.start({ crewId: Number(qCrewId), triggerInput });
		if (runId?.data?.runId) {
			ElMessage.success(`已触发运行 #${runId.data.runId}`);
			setTimeout(() => runTableRef.value?.loadData(), 1000);
		}
	}
});

async function onSelectRun(row: any) {
	selectedRun.value = row;
	const detail = await service.netaclaw.crew_trigger.runDetail({ runId: row.id });
	runTasks.value = detail?.tasks || [];
}

function onControl(runId: number, action: string) {
	monitor.controlRun(runId, action);
	ElMessage.success(action === 'stop' ? '已终止' : '操作成功');
	setTimeout(() => runTableRef.value?.loadData(), 500);
}

async function onResume(runId: number) {
	const { value } = await ElMessageBox.prompt('请输入处理意见', '恢复运行', {
		confirmButtonText: '恢复', cancelButtonText: '取消',
	});
	monitor.controlRun(runId, 'resume', value || '继续执行');
	ElMessage.success('已恢复');
	setTimeout(() => runTableRef.value?.loadData(), 500);
}

function onResumeWithMessage(runId: number, message: string) {
	monitor.controlRun(runId, 'resume', message);
	ElMessage.success('已恢复');
	setTimeout(() => runTableRef.value?.loadData(), 500);
}

async function onManualTrigger() {
	await crewStore.loadCrewList();
	const crews = crewStore.crewList.filter(c => c.status === 1);
	if (!crews.length) return ElMessage.warning('没有已发布的集群');

	const { value: crewIdStr } = await ElMessageBox.prompt(
		`选择集群 ID（可用: ${crews.map(c => `${c.id}:${c.label}`).join(', ')}）`,
		'选择集群', { confirmButtonText: '下一步', cancelButtonText: '取消' }
	);
	if (!crewIdStr) return;
	const crewId = parseInt(crewIdStr);

	const { value: taskInput } = await ElMessageBox.prompt(
		'请输入任务指令（主 Agent 将根据此指令协调团队执行）',
		'任务描述', { confirmButtonText: '触发', cancelButtonText: '取消', inputPlaceholder: '例如：分析竞品数据并生成上架方案' }
	);
	if (!taskInput) return;

	const res = await service.netaclaw.crew_trigger.start({ crewId, triggerInput: taskInput });
	if (res?.data?.runId) ElMessage.success(`已触发运行 #${res.data.runId}`);
	setTimeout(() => runTableRef.value?.loadData(), 1000);
}
</script>

<style scoped lang="scss">
.crew-monitor { display: flex; flex-direction: column; height: 100%; }
.monitor-header {
	display: flex; justify-content: space-between; align-items: center;
	padding: 12px 16px; border-bottom: 1px solid #ebeef5;
	.title { font-weight: 600; font-size: 16px; }
}
.monitor-body { flex: 1; display: flex; flex-direction: column; overflow: hidden; }
.run-list-area { height: 40%; min-height: 200px; padding: 12px 16px; overflow-y: auto; border-bottom: 1px solid #ebeef5; }
.run-detail-area { flex: 1; overflow: hidden; &.empty { display: flex; align-items: center; justify-content: center; } }
</style>
