<template>
  <div v-loading="loading">
    <PageHeader title="航线中心" description="管理厂商无关航线、航点参数、校验结果和发布版本">
      <el-button :icon="Refresh" @click="load">刷新</el-button>
      <el-button type="primary" :icon="Plus" @click="createDialog = true">新建航线</el-button>
    </PageHeader>

    <section class="metric-strip">
      <div class="metric-card"><strong>{{ rows.length }}</strong><span>航线</span><small>统一航线台账</small></div>
      <div class="metric-card"><strong>{{ publishedCount }}</strong><span>已发布</span><small>允许任务下发</small></div>
      <div class="metric-card"><strong>{{ draftCount }}</strong><span>待发布</span><small>需要校验或审批</small></div>
      <div class="metric-card"><strong>{{ totalWaypoints }}</strong><span>航点</span><small>全部当前版本</small></div>
    </section>

    <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="PUBLISHED" /><el-option label="草稿" value="DRAFT" /></el-select><span class="filter-spacer"></span><span>{{ filteredRows.length }} 条航线</span></div>
    <el-card class="workspace-card" shadow="never"><el-table :data="filteredRows" empty-text="暂无航线" @row-click="inspect">
      <el-table-column prop="name" label="航线" min-width="180"><template #default="scope"><strong>{{ scope.row.name }}</strong><small class="cell-subtext entity-id">{{ scope.row.route_id }}</small></template></el-table-column>
      <el-table-column prop="object_name" label="巡检对象" min-width="150" />
      <el-table-column prop="template_name" label="模板" min-width="150" />
      <el-table-column label="版本" width="85"><template #default="scope">V{{ scope.row.version_no || '-' }}</template></el-table-column>
      <el-table-column label="航点" width="85"><template #default="scope">{{ parseWaypoints(scope.row.waypoints).length }}</template></el-table-column>
      <el-table-column label="校验" width="110"><template #default="scope"><el-tag :type="validation(scope.row).valid ? 'success' : 'danger'" effect="plain">{{ validation(scope.row).valid ? '通过' : '未通过' }}</el-tag></template></el-table-column>
      <el-table-column label="状态" width="105"><template #default="scope"><el-tag :type="scope.row.status === 'PUBLISHED' ? 'success' : 'info'" effect="plain">{{ scope.row.status === 'PUBLISHED' ? '已发布' : '草稿' }}</el-tag></template></el-table-column>
      <el-table-column label="操作" width="220" fixed="right"><template #default="scope"><div class="list-actions" @click.stop><el-button link type="primary" @click="validateRow(scope.row)">校验</el-button><el-button link type="success" :disabled="scope.row.status === 'PUBLISHED'" @click="publishRow(scope.row)">发布</el-button><el-button link @click="inspect(scope.row)">详情</el-button></div></template></el-table-column>
    </el-table></el-card>

    <el-dialog v-model="createDialog" title="新建航线" width="min(820px, 96vw)" destroy-on-close>
      <el-form label-position="top"><div class="form-grid"><el-form-item label="航线名称"><el-input v-model="form.name" /></el-form-item><el-form-item label="巡检对象"><el-select v-model="form.object_id" filterable><el-option v-for="item in objects" :key="item.object_id" :label="item.name" :value="item.object_id" /></el-select></el-form-item><el-form-item label="飞行速度"><el-input-number v-model="form.speed_mps" :min="1" :max="20" /><span class="unit-label">米/秒</span></el-form-item><el-form-item label="返航高度"><el-input-number v-model="form.rth_altitude_m" :min="20" :max="500" /><span class="unit-label">米</span></el-form-item></div></el-form>
      <div class="subsection-head"><div><strong>航点参数</strong><span>WGS84 坐标，高德底图仅在展示层转换</span></div><el-button :icon="Plus" @click="addWaypoint">增加航点</el-button></div>
      <el-table :data="form.waypoints" border size="small"><el-table-column type="index" label="#" width="52" /><el-table-column label="经度" min-width="145"><template #default="scope"><el-input-number v-model="scope.row.longitude" :precision="6" :step="0.001" controls-position="right" /></template></el-table-column><el-table-column label="纬度" min-width="145"><template #default="scope"><el-input-number v-model="scope.row.latitude" :precision="6" :step="0.001" controls-position="right" /></template></el-table-column><el-table-column label="高度" min-width="125"><template #default="scope"><el-input-number v-model="scope.row.altitude_m" :min="10" :max="600" controls-position="right" /></template></el-table-column><el-table-column label="云台俯仰" min-width="125"><template #default="scope"><el-input-number v-model="scope.row.gimbal_pitch_deg" :min="-90" :max="30" controls-position="right" /></template></el-table-column><el-table-column width="60"><template #default="scope"><el-button link type="danger" :disabled="form.waypoints.length <= 2" :icon="Delete" @click="form.waypoints.splice(scope.$index, 1)" /></template></el-table-column></el-table>
      <template #footer><el-button @click="createDialog = false">取消</el-button><el-button type="primary" :loading="saving" @click="save">创建并校验</el-button></template>
    </el-dialog>

    <el-drawer v-model="detailVisible" title="航线版本详情" size="580px"><template v-if="selected"><div class="route-visual"><div v-for="(point, index) in parseWaypoints(selected.waypoints)" :key="index" class="route-point" :style="pointStyle(point, index)"><span>{{ index + 1 }}</span></div><div class="route-axis"></div></div><el-descriptions :column="1" border><el-descriptions-item label="航线编号"><span class="entity-id">{{ selected.route_id }}</span></el-descriptions-item><el-descriptions-item label="当前版本">V{{ selected.version_no }}</el-descriptions-item><el-descriptions-item label="巡检对象">{{ selected.object_name || '-' }}</el-descriptions-item><el-descriptions-item label="飞行参数">{{ jsonText(selected.flight_parameters) }}</el-descriptions-item><el-descriptions-item label="载荷动作">{{ jsonText(selected.payload_actions) }}</el-descriptions-item></el-descriptions><div class="validation-panel" :class="{ invalid: !validation(selected).valid }"><strong>{{ validation(selected).valid ? '航线校验通过' : '航线校验未通过' }}</strong><p v-for="message in [...(validation(selected).errors || []), ...(validation(selected).warnings || [])]" :key="message">{{ message }}</p><small v-if="!(validation(selected).errors?.length || validation(selected).warnings?.length)">航点数量、高度和速度均符合平台校验规则</small></div></template></el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { Delete, Plus, Refresh, Search } from "@element-plus/icons-vue";
import PageHeader from "../../components/common/PageHeader.vue";
import { createInspectionRoute, inspectionObjects, inspectionRoutes, publishRouteVersion, validateRouteVersion } from "../../services/api";
import { safeObject, type Row } from "../../types/demo-run";

const rows = ref<Row[]>([]); const objects = ref<Row[]>([]); const loading = ref(false); const saving = ref(false); const createDialog = ref(false); const detailVisible = ref(false); const selected = ref<Row | null>(null); const keyword = ref(""); const statusFilter = ref("");
const form = reactive({ name: "铁路沿线巡检航线", object_id: "object-line-demo", speed_mps: 7, rth_altitude_m: 100, waypoints: [{ longitude: 116.09, latitude: 39.095, altitude_m: 80, gimbal_pitch_deg: -45 }, { longitude: 116.125, latitude: 39.115, altitude_m: 80, gimbal_pitch_deg: -45 }, { longitude: 116.165, latitude: 39.105, altitude_m: 80, gimbal_pitch_deg: -45 }] });
const filteredRows = computed(() => rows.value.filter((row) => (!statusFilter.value || row.status === statusFilter.value) && (!keyword.value || `${row.name} ${row.object_name} ${row.template_name}`.toLowerCase().includes(keyword.value.toLowerCase())))); const publishedCount = computed(() => rows.value.filter((row) => row.status === "PUBLISHED").length); const draftCount = computed(() => rows.value.filter((row) => row.status !== "PUBLISHED").length); const totalWaypoints = computed(() => rows.value.reduce((sum, row) => sum + parseWaypoints(row.waypoints).length, 0));
function parseWaypoints(value: unknown): Row[] { try { return Array.isArray(value) ? value as Row[] : JSON.parse(String(value || "[]")); } catch { return []; } }
function validation(row: Row): Row { return safeObject(row.validation_result); }
function jsonText(value: unknown) { const data = typeof value === "string" ? safeObject(value) : value; return Object.entries(data as Row || {}).map(([key, item]) => `${key}: ${Array.isArray(item) ? item.length + '项' : item}`).join("，") || "-"; }
function addWaypoint() { const previous = form.waypoints.at(-1) || { longitude: 116.1, latitude: 39.1, altitude_m: 80, gimbal_pitch_deg: -45 }; form.waypoints.push({ ...previous, longitude: previous.longitude + 0.005, latitude: previous.latitude + 0.003 }); }
function inspect(row: Row) { selected.value = row; detailVisible.value = true; }
function pointStyle(_point: Row, index: number) { const count = Math.max(2, parseWaypoints(selected.value?.waypoints).length); return { left: `${10 + index * 80 / (count - 1)}%`, top: `${60 - Math.sin(index * 1.4) * 25}%` }; }
async function load() { loading.value = true; try { [rows.value, objects.value] = await Promise.all([inspectionRoutes(), inspectionObjects()]); } finally { loading.value = false; } }
async function save() { if (!form.name || form.waypoints.length < 2) return ElMessage.warning("请填写航线名称并配置至少两个航点"); saving.value = true; try { await createInspectionRoute({ name: form.name, object_id: form.object_id, template_id: "template-railway", waypoints: form.waypoints.map((point, index) => ({ ...point, sequence: index + 1, speed_mps: form.speed_mps, actions: ["TAKE_PHOTO"] })), flight_parameters: { speed_mps: form.speed_mps, rth_altitude_m: form.rth_altitude_m }, payload_actions: [{ type: "TAKE_PHOTO", interval_s: 2 }], created_by: "user-dispatcher" }); createDialog.value = false; ElMessage.success("航线已创建并完成校验"); await load(); } finally { saving.value = false; } }
async function validateRow(row: Row) { const result = await validateRouteVersion(String(row.current_version_id)); ElMessage[result.valid ? "success" : "error"](result.valid ? "航线校验通过" : result.errors.join("；")); await load(); }
async function publishRow(row: Row) { try { await publishRouteVersion(String(row.current_version_id)); ElMessage.success("航线版本已发布"); await load(); } catch { /* global error */ } }
onMounted(load);
</script>
