<template>
  <div v-loading="loading">
    <PageHeader title="GIS 态势" description="统一查看线路、规则区域、航线、告警和工单空间分布">
      <el-button :icon="Refresh" :loading="loading" @click="load">刷新图层</el-button>
    </PageHeader>

    <div class="filter-bar">
      <el-select v-model="lineFilter" placeholder="全部线路"><el-option label="全部线路" value="" /><el-option v-for="line in lines" :key="line" :label="line" :value="line" /></el-select>
      <el-select v-model="severityFilter" placeholder="全部等级"><el-option label="全部等级" value="" /><el-option label="严重" value="critical" /><el-option label="高" value="high" /><el-option label="中" value="medium" /><el-option label="低" value="low" /></el-select>
      <el-checkbox v-model="layers.routes">航线</el-checkbox><el-checkbox v-model="layers.rules">规则区域</el-checkbox><el-checkbox v-model="layers.alarms">告警点位</el-checkbox>
      <span class="filter-spacer"></span><span class="gis-result-count">当前显示 {{ filteredAlarms.length }} 个告警点</span>
    </div>

    <section class="gis-page-layout">
      <OperationalGisMap :feature-collection="filteredFeatureCollection" :layers="layers" :selected-id="String(selected?.alarm_id || '')" @select="selectFeature" />
      <aside class="gis-detail-panel">
        <template v-if="selected">
          <div class="gis-detail-head"><div><el-tag :type="selected.severity === 'critical' ? 'danger' : 'warning'" effect="dark">{{ severityLabel(selected.severity) }}</el-tag><h2>{{ selected.scene }}</h2></div><el-button text :icon="Close" @click="selected = null" /></div>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="告警编号"><span class="entity-id">{{ selected.alarm_id }}</span></el-descriptions-item>
            <el-descriptions-item label="类别">{{ selected.category }}</el-descriptions-item>
            <el-descriptions-item label="线路">{{ taskLine(selected.task_id) }}</el-descriptions-item>
            <el-descriptions-item label="空间位置">{{ locationText(selected) }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ statusLabel(selected.status) }}</el-descriptions-item>
            <el-descriptions-item label="关联工单">{{ relatedWorkorder(selected.alarm_id)?.workorder_id || "尚未生成" }}</el-descriptions-item>
          </el-descriptions>
          <div class="gis-detail-actions"><el-button type="primary" @click="router.push(`/alarms/${selected.alarm_id}`)">进入告警研判</el-button><el-button v-if="relatedWorkorder(selected.alarm_id)" @click="router.push(`/workorders/${relatedWorkorder(selected.alarm_id)?.workorder_id}`)">查看工单</el-button></div>
        </template>
        <el-empty v-else description="点击地图告警点查看详情" :image-size="96" />
      </aside>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Close, Refresh } from "@element-plus/icons-vue";
import PageHeader from "../../components/common/PageHeader.vue";
import OperationalGisMap from "../../components/gis/OperationalGisMap.vue";
import { alarms, gisFeatures, tasks, workorders } from "../../services/api";
import { safeObject, severityLabel, statusLabel, type Row } from "../../types/demo-run";

const router = useRouter();
const loading = ref(false);
const alarmRows = ref<Row[]>([]); const taskRows = ref<Row[]>([]); const workorderRows = ref<Row[]>([]);
const featureCollection = ref<Row>({ type: "FeatureCollection", features: [] });
const selected = ref<Row | null>(null); const lineFilter = ref(""); const severityFilter = ref("");
const layers = reactive({ routes: true, rules: true, alarms: true });
const lines = computed(() => [...new Set(taskRows.value.map((row) => String(row.line_id)).filter(Boolean))]);
const filteredAlarms = computed(() => alarmRows.value.filter((row) => (!severityFilter.value || row.severity === severityFilter.value) && (!lineFilter.value || taskLine(row.task_id) === lineFilter.value)));
const filteredFeatureCollection = computed(() => { const ids = new Set(filteredAlarms.value.map((row) => String(row.alarm_id))); return { ...featureCollection.value, features: (featureCollection.value.features || []).filter((feature: Row) => feature.properties?.domain_type !== "alarm" || ids.has(String(feature.properties?.alarm_id))) }; });
function taskLine(taskId: unknown) { return String(taskRows.value.find((row) => String(row.task_id) === String(taskId))?.line_id || "line-demo"); }
function relatedWorkorder(alarmId: unknown) { return workorderRows.value.find((row) => String(row.alarm_id) === String(alarmId)); }
function locationText(row: Row) { const location = safeObject(row.location); return [location.mileage, location.distance_to_track_m ? `距线路 ${location.distance_to_track_m}m` : ""].filter(Boolean).join(" / ") || "线路邻近"; }
function selectFeature(properties: Row) { selected.value = alarmRows.value.find((row) => String(row.alarm_id) === String(properties.alarm_id)) || properties; }
async function load() { loading.value = true; try { [alarmRows.value, taskRows.value, workorderRows.value, featureCollection.value] = await Promise.all([alarms(), tasks(), workorders(), gisFeatures()]); selected.value = filteredAlarms.value[0] || null; } finally { loading.value = false; } }
onMounted(load);
</script>
