<template>
  <div>
    <PageHeader title="全链路运行" description="创建、观察、回放和恢复完整巡检处理运行">
      <el-button :icon="Refresh" :loading="loading" @click="loadRuns">刷新记录</el-button>
      <el-button v-if="activeTab !== 'workspace'" type="primary" :icon="VideoPlay" @click="openWorkspace('')">新建运行</el-button>
    </PageHeader>

    <el-tabs v-model="activeTab" class="secondary-tabs" @tab-change="syncTab">
      <el-tab-pane label="运行工作台" name="workspace">
        <FullChainRunConsole :key="selectedRunId || 'new-run'" :initial-run-id="selectedRunId" @refresh="loadRuns" />
      </el-tab-pane>
      <el-tab-pane :label="`运行记录 ${runRows.length}`" name="records">
        <div class="filter-bar"><el-input v-model="keyword" clearable placeholder="搜索运行编号或任务编号" :prefix-icon="Search" /><el-select v-model="statusFilter"><el-option label="全部状态" value="" /><el-option label="运行中" value="running" /><el-option label="已完成" value="completed" /><el-option label="失败" value="failed" /><el-option label="已取消" value="cancelled" /></el-select><span class="filter-spacer"></span><span>{{ filteredRuns.length }} 条记录</span></div>
        <el-card class="workspace-card" shadow="never" v-loading="loading">
          <el-table :data="filteredRuns" empty-text="暂无运行记录">
            <el-table-column prop="run_id" label="运行编号" min-width="175"><template #default="scope"><span class="entity-id">{{ scope.row.run_id }}</span></template></el-table-column>
            <el-table-column prop="task_id" label="任务编号" min-width="170" show-overflow-tooltip />
            <el-table-column label="状态" width="105"><template #default="scope"><el-tag :type="statusTag(scope.row.status)" effect="plain">{{ statusLabel(scope.row.status) }}</el-tag></template></el-table-column>
            <el-table-column label="进度" min-width="150"><template #default="scope"><el-progress :percentage="Number(scope.row.progress || 0)" :stroke-width="7" /></template></el-table-column>
            <el-table-column prop="event_count" label="事件" width="80" />
            <el-table-column label="启动时间" min-width="165"><template #default="scope">{{ formatDateTime(scope.row.started_at) }}</template></el-table-column>
            <el-table-column label="操作" width="100" fixed="right"><template #default="scope"><el-button link type="primary" @click="openWorkspace(scope.row.run_id)">{{ scope.row.status === 'running' ? '查看运行' : '回放' }}</el-button></template></el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
      <el-tab-pane :label="`异常运行 ${abnormalRuns.length}`" name="abnormal">
        <el-alert title="异常运行保留全部已完成节点和业务实体，可从失败或取消节点继续执行。" type="warning" show-icon :closable="false" />
        <el-card class="workspace-card run-exception-list" shadow="never" v-loading="loading">
          <el-table :data="abnormalRuns" empty-text="暂无异常运行">
            <el-table-column prop="run_id" label="运行编号" min-width="175"><template #default="scope"><span class="entity-id">{{ scope.row.run_id }}</span></template></el-table-column>
            <el-table-column label="状态" width="105"><template #default="scope"><el-tag :type="statusTag(scope.row.status)">{{ statusLabel(scope.row.status) }}</el-tag></template></el-table-column>
            <el-table-column prop="current_step" label="停止节点" min-width="160" />
            <el-table-column prop="error_message" label="异常信息" min-width="220" show-overflow-tooltip />
            <el-table-column label="操作" width="100"><template #default="scope"><el-button link type="primary" @click="openWorkspace(scope.row.run_id)">进入恢复</el-button></template></el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Refresh, Search, VideoPlay } from "@element-plus/icons-vue";
import PageHeader from "../../components/common/PageHeader.vue";
import FullChainRunConsole from "../../components/full-chain-run/FullChainRunConsole.vue";
import { demoRuns } from "../../services/api";
import { statusLabel, statusTag, type Row } from "../../types/demo-run";

const route = useRoute(); const router = useRouter();
const loading = ref(false); const runRows = ref<Row[]>([]); const keyword = ref(""); const statusFilter = ref("");
const activeTab = ref(String(route.query.tab || (route.params.runId ? "workspace" : "workspace")));
const selectedRunId = computed(() => String(route.params.runId || ""));
const filteredRuns = computed(() => runRows.value.filter((row) => (!statusFilter.value || row.status === statusFilter.value) && (!keyword.value || `${row.run_id} ${row.task_id}`.toLowerCase().includes(keyword.value.toLowerCase()))));
const abnormalRuns = computed(() => runRows.value.filter((row) => ["failed", "cancelled"].includes(String(row.status))));
function formatDateTime(value: unknown) { return value ? new Date(String(value)).toLocaleString("zh-CN", { hour12: false }) : "-"; }
async function loadRuns() { loading.value = true; try { runRows.value = await demoRuns(); } finally { loading.value = false; } }
function syncTab(value: string | number) { router.replace({ query: { ...route.query, tab: String(value) } }); }
function openWorkspace(runId: string) { activeTab.value = "workspace"; router.push(runId ? `/runs/${runId}?tab=workspace` : "/runs?tab=workspace"); }
watch(() => route.query.tab, (value) => { if (value) activeTab.value = String(value); });
onMounted(loadRuns);
</script>
