<template>
  <div v-loading="loading">
    <PageHeader title="工作总览" description="汇总巡检运行、告警处置和系统健康状态">
      <el-button :icon="Refresh" :loading="loading" @click="load">刷新</el-button>
    </PageHeader>

    <section class="metric-strip">
      <div v-for="item in metrics" :key="item.key" class="metric-card" :class="{ clickable: item.path }" @click="item.path && router.push(item.path)">
        <strong>{{ item.value }}</strong><span>{{ item.label }}</span><small>{{ item.note }}</small>
      </div>
    </section>

    <section class="page-grid primary-aside">
      <div class="page-grid">
        <el-card class="workspace-card" shadow="never">
          <template #header><div class="card-heading"><strong>重点待办</strong><span>按优先级排序</span></div></template>
          <div class="overview-todos">
            <button v-for="todo in todos" :key="todo.label" type="button" @click="router.push(todo.path)">
              <el-icon><component :is="todo.icon" /></el-icon><span><strong>{{ todo.value }}</strong><small>{{ todo.label }}</small></span><el-icon><ArrowRight /></el-icon>
            </button>
          </div>
        </el-card>

        <el-card class="workspace-card" shadow="never">
          <template #header><div class="card-heading"><strong>最近巡检任务</strong><el-button link type="primary" @click="router.push('/tasks')">查看全部</el-button></div></template>
          <el-table :data="taskRows.slice(0, 6)" empty-text="暂无巡检任务">
            <el-table-column prop="task_id" label="任务编号" min-width="170"><template #default="scope"><span class="entity-id">{{ scope.row.task_id }}</span></template></el-table-column>
            <el-table-column prop="line_id" label="线路" width="120" />
            <el-table-column label="里程范围" min-width="180"><template #default="scope">{{ scope.row.mileage_start }} - {{ scope.row.mileage_end }}</template></el-table-column>
            <el-table-column label="状态" width="100"><template #default="scope"><el-tag :type="statusTag(scope.row.status)" effect="plain">{{ statusLabel(scope.row.status) }}</el-tag></template></el-table-column>
          </el-table>
        </el-card>

        <el-card class="workspace-card" shadow="never">
          <template #header><div class="card-heading"><strong>高等级告警</strong><el-button link type="primary" @click="router.push('/alarms')">进入研判</el-button></div></template>
          <el-table :data="priorityAlarms" empty-text="暂无高等级告警">
            <el-table-column prop="scene" label="场景" min-width="140" />
            <el-table-column prop="category" label="类别" min-width="120" />
            <el-table-column label="等级" width="90"><template #default="scope"><el-tag :type="scope.row.severity === 'critical' ? 'danger' : 'warning'" effect="dark">{{ severityLabel(scope.row.severity) }}</el-tag></template></el-table-column>
            <el-table-column label="状态" width="100"><template #default="scope">{{ statusLabel(scope.row.status) }}</template></el-table-column>
            <el-table-column label="操作" width="80"><template #default="scope"><el-button link type="primary" @click="router.push(`/alarms/${scope.row.alarm_id}`)">研判</el-button></template></el-table-column>
          </el-table>
        </el-card>
      </div>

      <aside class="page-grid">
        <el-card class="workspace-card" shadow="never">
          <template #header><div class="card-heading"><strong>快捷入口</strong><span>常用工作</span></div></template>
          <div class="quick-actions">
            <button v-for="action in quickActions" :key="action.path" class="quick-action" type="button" @click="router.push(action.path)">
              <el-icon><component :is="action.icon" /></el-icon><span><strong>{{ action.label }}</strong><small>{{ action.description }}</small></span>
            </button>
          </div>
        </el-card>

        <el-card class="workspace-card" shadow="never">
          <template #header><div class="card-heading"><strong>系统健康</strong><el-tag :type="healthStatus === 'UP' ? 'success' : 'danger'" effect="plain">{{ healthStatus === 'UP' ? '正常' : '异常' }}</el-tag></div></template>
          <div class="health-list">
            <div v-for="service in healthServices" :key="service.name" class="health-row"><div><strong>{{ service.name }}</strong><span>{{ service.description }}</span></div><i class="status-dot" :class="{ danger: healthStatus !== 'UP' }"></i></div>
          </div>
        </el-card>

        <el-card class="workspace-card" shadow="never">
          <template #header><div class="card-heading"><strong>工单闭环</strong><span>{{ closureRate }}%</span></div></template>
          <el-progress type="dashboard" :percentage="closureRate" :width="150" :stroke-width="12" />
          <div class="closure-breakdown"><span>待处置 <strong>{{ pendingWorkorders }}</strong></span><span>已闭环 <strong>{{ closedWorkorders }}</strong></span></div>
        </el-card>
      </aside>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ArrowRight, Bell, Checked, Files, MapLocation, Refresh, VideoPlay } from "@element-plus/icons-vue";
import PageHeader from "../../components/common/PageHeader.vue";
import { alarms, overview, serviceHealth, tasks, workorders } from "../../services/api";
import { severityLabel, statusLabel, statusTag, type Row } from "../../types/demo-run";

const router = useRouter();
const loading = ref(false);
const stats = ref<Record<string, number>>({});
const taskRows = ref<Row[]>([]);
const alarmRows = ref<Row[]>([]);
const workorderRows = ref<Row[]>([]);
const healthStatus = ref("UNKNOWN");
const metricDefinitions = [
  { key: "tasks", label: "巡检任务", note: "任务总量", path: "/tasks" },
  { key: "resources", label: "数据资源", note: "已接入资源", path: "/resources" },
  { key: "analysis_jobs", label: "分析任务", note: "处理批次", path: "/analysis" },
  { key: "ai_results", label: "AI 结果", note: "识别与分析", path: "/analysis?tab=results" },
  { key: "alarms", label: "有效告警", note: "待研判与处置", path: "/alarms" },
  { key: "workorders", label: "工单", note: "闭环处置", path: "/workorders" }
];
const metrics = computed(() => metricDefinitions.map((item) => ({ ...item, value: stats.value[item.key] ?? 0 })));
const priorityAlarms = computed(() => alarmRows.value.filter((row) => ["critical", "high"].includes(String(row.severity))).slice(0, 8));
const pendingWorkorders = computed(() => workorderRows.value.filter((row) => row.status !== "closed").length);
const closedWorkorders = computed(() => workorderRows.value.filter((row) => row.status === "closed").length);
const closureRate = computed(() => workorderRows.value.length ? Math.round(closedWorkorders.value / workorderRows.value.length * 100) : 0);
const todos = computed(() => [
  { label: "待执行巡检任务", value: taskRows.value.filter((row) => ["created", "pending", "dispatching", "dispatched"].includes(String(row.status))).length, path: "/tasks?tab=pending", icon: Files },
  { label: "待研判高等级告警", value: priorityAlarms.value.filter((row) => row.status !== "closed").length, path: "/alarms?tab=pending", icon: Bell },
  { label: "待处置与复核工单", value: pendingWorkorders.value, path: "/workorders?tab=pending", icon: Checked }
]);
const quickActions = [
  { label: "全链路运行", description: "查看运行记录与处理进度", path: "/runs", icon: VideoPlay },
  { label: "GIS 态势", description: "查看线路与隐患分布", path: "/gis", icon: MapLocation },
  { label: "巡检任务", description: "任务调度与执行跟踪", path: "/tasks", icon: Files },
  { label: "工单中心", description: "处理现场闭环事项", path: "/workorders", icon: Checked }
];
const healthServices = [
  { name: "业务平台", description: "Spring Boot API" }, { name: "视觉推理", description: "图像、视频与红外" },
  { name: "点云分析", description: "点云、TIF 与 DEM" }, { name: "数据基础设施", description: "PostGIS、Kafka、Redis、MinIO" }
];

async function load() {
  loading.value = true;
  try {
    const [statData, taskData, alarmData, workorderData, health] = await Promise.all([overview(), tasks(), alarms(), workorders(), serviceHealth()]);
    stats.value = statData; taskRows.value = taskData; alarmRows.value = alarmData; workorderRows.value = workorderData; healthStatus.value = health.status;
  } finally { loading.value = false; }
}
onMounted(load);
</script>
