<template>
  <div v-loading="loading">
    <PageHeader title="巡检任务" description="统一查看计划生成的任务，完成执行准备、飞行调度和结果跟踪">
      <el-button :icon="Refresh" @click="load">刷新</el-button>
      <el-button type="primary" :icon="Plus" @click="startManualInspection">发起手动巡检</el-button>
    </PageHeader>

    <el-alert
      class="task-entry-tip"
      type="info"
      :closable="false"
      show-icon
      title="任务统一由周期计划自动生成，或由“巡检计划 > 手动巡检”创建；本页不再提供第二套新建入口。"
    />

    <el-tabs v-model="activeTab" class="secondary-tabs">
      <el-tab-pane :label="`全部任务 ${rows.length}`" name="all" />
      <el-tab-pane :label="`待执行 ${statusCount('pending')}`" name="pending" />
      <el-tab-pane :label="`执行中 ${statusCount('running')}`" name="running" />
      <el-tab-pane :label="`已完成 ${statusCount('completed')}`" name="completed" />
      <el-tab-pane :label="`异常/取消 ${statusCount('abnormal')}`" name="abnormal" />
    </el-tabs>

    <div class="filter-bar">
      <el-input v-model="keyword" clearable placeholder="任务编号、计划、线路或航线" :prefix-icon="Search" />
      <el-select v-model="priorityFilter">
        <el-option label="全部优先级" value="" />
        <el-option label="紧急" value="urgent" />
        <el-option label="优先" value="high" />
        <el-option label="普通" value="normal" />
      </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="openDetail">
        <el-table-column prop="task_id" label="任务编号" min-width="190">
          <template #default="scope">
            <span class="entity-id">{{ scope.row.task_id }}</span>
            <small class="cell-subtext">{{ taskSource(scope.row) }}</small>
          </template>
        </el-table-column>
        <el-table-column prop="line_id" label="线路" width="110" />
        <el-table-column label="里程范围" min-width="175">
          <template #default="scope">{{ mileageText(scope.row) }}</template>
        </el-table-column>
        <el-table-column label="航线" min-width="150">
          <template #default="scope">
            <span>{{ scope.row.route_name || scope.row.route_id || "待配置" }}</span>
            <small v-if="scope.row.route_id && (scope.row.route_status !== 'PUBLISHED' || scope.row.route_version_status !== 'PUBLISHED')" class="cell-subtext warning-text">尚未发布</small>
          </template>
        </el-table-column>
        <el-table-column label="计划执行" min-width="165">
          <template #default="scope">{{ formatDate(scope.row.planned_start_at) }}</template>
        </el-table-column>
        <el-table-column label="优先级" width="90">
          <template #default="scope">{{ priorityLabel(scope.row.priority) }}</template>
        </el-table-column>
        <el-table-column label="状态" min-width="145">
          <template #default="scope">
            <div class="status-stack">
              <el-tag :type="phaseTag(taskPhase(scope.row))" effect="plain">{{ phaseLabel(taskPhase(scope.row)) }}</el-tag>
              <small v-if="scope.row.mission_id">{{ scope.row.vendor_code || "无人机" }} · {{ Number(scope.row.mission_progress || 0) }}%</small>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <div class="list-actions" @click.stop>
              <el-button v-if="canDispatch(scope.row)" link type="primary" @click="openDispatchWorkspace(scope.row)">航线下发</el-button>
              <el-button v-else-if="needsRoute(scope.row)" link type="warning" @click="configureRoute(scope.row)">配置航线</el-button>
              <el-tooltip v-else-if="awaitingApproval(scope.row)" :content="String(scope.row.dispatch_block_reason || '任务尚未审批通过')" placement="top">
                <span><el-button link disabled>待审批</el-button></span>
              </el-tooltip>
              <el-button v-if="scope.row.mission_id" link type="primary" @click="openMission(scope.row)">查看飞行</el-button>
              <el-button v-if="hasResults(scope.row)" link type="primary" @click="openResources(scope.row)">查看结果</el-button>
              <el-button v-else link @click="openMap(scope.row)">地图</el-button>
              <el-button v-if="canCancel(scope.row)" link type="danger" @click="cancel(scope.row)">取消</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-drawer v-model="detailVisible" title="巡检任务详情" size="600px">
      <template v-if="selectedTask">
        <el-alert
          class="detail-guidance"
          :type="guidanceType(selectedTask)"
          :closable="false"
          show-icon
          :title="nextActionText(selectedTask)"
        />
        <el-steps
          class="task-workflow"
          :active="workflowStep(selectedTask)"
          :process-status="taskPhase(selectedTask) === 'failed' ? 'error' : 'process'"
          finish-status="success"
          align-center
        >
          <el-step title="任务生成" />
          <el-step title="执行准备" />
          <el-step title="飞行执行" />
          <el-step title="数据处理" />
        </el-steps>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="任务编号"><span class="entity-id">{{ selectedTask.task_id }}</span></el-descriptions-item>
          <el-descriptions-item label="任务来源">{{ taskSource(selectedTask) }}</el-descriptions-item>
          <el-descriptions-item label="巡检计划">{{ selectedTask.plan_name || selectedTask.plan_id || "历史任务" }}</el-descriptions-item>
          <el-descriptions-item label="线路区段">{{ selectedTask.line_id }} / {{ mileageText(selectedTask) }}</el-descriptions-item>
          <el-descriptions-item label="计划执行">{{ formatDate(selectedTask.planned_start_at) }}</el-descriptions-item>
          <el-descriptions-item label="航线">{{ selectedTask.route_name || selectedTask.route_id || "待配置" }}</el-descriptions-item>
          <el-descriptions-item label="审批状态">{{ approvalLabel(selectedTask.approval_status) }}</el-descriptions-item>
          <el-descriptions-item label="业务状态">
            <el-tag :type="phaseTag(taskPhase(selectedTask))" effect="plain">{{ phaseLabel(taskPhase(selectedTask)) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedTask.mission_id" label="飞行任务">
            <span class="entity-id">{{ selectedTask.mission_id }}</span> · {{ missionLabel(selectedTask.mission_status) }} · {{ Number(selectedTask.mission_progress || 0) }}%
          </el-descriptions-item>
          <el-descriptions-item v-if="selectedTask.mission_error_message" label="异常原因">{{ selectedTask.mission_error_message }}</el-descriptions-item>
          <el-descriptions-item label="识别场景">{{ sceneText(selectedTask.scene_set) }}</el-descriptions-item>
        </el-descriptions>
        <div class="drawer-actions">
          <el-button v-if="canDispatch(selectedTask)" type="primary" @click="openDispatchWorkspace(selectedTask)">进入调度并下发</el-button>
          <el-button v-if="needsRoute(selectedTask)" type="warning" plain @click="configureRoute(selectedTask)">配置航线</el-button>
          <el-button v-if="selectedTask.mission_id" @click="openMission(selectedTask)">查看飞行任务</el-button>
          <el-button v-if="hasResults(selectedTask)" @click="openResources(selectedTask)">查看数据资源</el-button>
          <el-button v-if="canCancel(selectedTask)" type="danger" plain @click="cancel(selectedTask)">取消任务</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Refresh, Search } from "@element-plus/icons-vue";
import PageHeader from "../../components/common/PageHeader.vue";
import { cancelInspectionTask, tasks } from "../../services/api";
import type { Row } from "../../types/demo-run";

type TaskPhase =
  | "awaiting_approval" | "route_pending" | "ready" | "dispatching" | "dispatched" | "preparing"
  | "flying" | "paused" | "returning" | "uploading" | "processing" | "completed" | "failed" | "cancelled";

const route = useRoute();
const router = useRouter();
const rows = ref<Row[]>([]);
const loading = ref(false);
const detailVisible = ref(false);
const selectedTask = ref<Row | null>(null);
const keyword = ref("");
const priorityFilter = ref("");
const activeTab = ref(String(route.query.tab || "all"));

const filteredRows = computed(() => rows.value.filter((row) => {
  const searchText = `${row.task_id} ${row.plan_name || ""} ${row.line_id || ""} ${row.route_name || row.route_id || ""}`.toLowerCase();
  return matchTab(row)
    && (!priorityFilter.value || row.priority === priorityFilter.value)
    && (!keyword.value || searchText.includes(keyword.value.toLowerCase()));
}));

function taskPhase(row: Row): TaskPhase {
  const taskStatus = String(row.status || "").toLowerCase();
  if (taskStatus === "completed") return "completed";
  if (taskStatus === "cancelled") return "cancelled";
  if (taskStatus === "failed") return "failed";

  const missionStatus = String(row.mission_status || "").toUpperCase();
  const missionPhases: Record<string, TaskPhase> = {
    DISPATCHING: "dispatching",
    DISPATCHED: "dispatched",
    PREPARING: "preparing",
    FLYING: "flying",
    PAUSED: "paused",
    RETURNING: "returning",
    UPLOADING: "uploading",
    COMPLETED: "processing",
    DISPATCH_FAILED: "failed",
    FAILED: "failed",
    ABORTED: "failed",
    CANCELLED: "cancelled"
  };
  if (missionPhases[missionStatus]) return missionPhases[missionStatus];
  if (taskStatus === "data_uploading") return "processing";
  if (taskStatus === "flying" || taskStatus === "running") return "flying";
  if (taskStatus === "dispatched" || taskStatus === "dispatching") return "dispatched";
  if (String(row.approval_status || "") !== "APPROVED") return "awaiting_approval";
  if (!row.route_id || row.route_status !== "PUBLISHED") return "route_pending";
  return "ready";
}

function phaseLabel(phase: TaskPhase) {
  const labels: Record<TaskPhase, string> = {
    awaiting_approval: "待审批",
    route_pending: "待配置航线",
    ready: "待下发",
    dispatching: "下发中",
    dispatched: "已下发",
    preparing: "飞行准备",
    flying: "飞行中",
    paused: "已暂停",
    returning: "返航中",
    uploading: "数据回传",
    processing: "待数据处理",
    completed: "已完成",
    failed: "执行异常",
    cancelled: "已取消"
  };
  return labels[phase];
}

function phaseTag(phase: TaskPhase): "success" | "warning" | "info" | "danger" | "primary" {
  if (phase === "completed") return "success";
  if (phase === "failed") return "danger";
  if (["awaiting_approval", "route_pending", "paused"].includes(phase)) return "warning";
  if (["dispatching", "dispatched", "preparing", "flying", "returning", "uploading", "processing"].includes(phase)) return "primary";
  return "info";
}

function matchTab(row: Row) {
  if (activeTab.value === "all") return true;
  const phase = taskPhase(row);
  if (activeTab.value === "pending") return ["awaiting_approval", "route_pending", "ready", "dispatching", "dispatched", "preparing"].includes(phase);
  if (activeTab.value === "running") return ["flying", "paused", "returning", "uploading", "processing"].includes(phase);
  if (activeTab.value === "completed") return phase === "completed";
  return ["failed", "cancelled"].includes(phase);
}

function statusCount(kind: string) {
  return rows.value.filter((row) => {
    const phase = taskPhase(row);
    if (kind === "pending") return ["awaiting_approval", "route_pending", "ready", "dispatching", "dispatched", "preparing"].includes(phase);
    if (kind === "running") return ["flying", "paused", "returning", "uploading", "processing"].includes(phase);
    if (kind === "completed") return phase === "completed";
    return ["failed", "cancelled"].includes(phase);
  }).length;
}

function booleanFlag(value: unknown) {
  return value === true || value === 1 || String(value).toLowerCase() === "true";
}

function canDispatch(row: Row) { return booleanFlag(row.can_dispatch); }
function canCancel(row: Row) { return booleanFlag(row.can_cancel); }
function needsRoute(row: Row) { return ["created", "pending"].includes(String(row.status)) && String(row.approval_status) === "APPROVED" && (!row.route_id || row.route_status !== "PUBLISHED" || row.route_version_status !== "PUBLISHED"); }
function awaitingApproval(row: Row) { return ["created", "pending"].includes(String(row.status)) && String(row.approval_status) !== "APPROVED"; }
function hasResults(row: Row) { return ["data_uploading", "completed"].includes(String(row.status)); }
function parseScenes(value: unknown): string[] { try { return Array.isArray(value) ? value.map(String) : JSON.parse(String(value || "[]")); } catch { return []; } }
function parseIds(value: unknown): string[] { try { return Array.isArray(value) ? value.map(String) : JSON.parse(String(value || "[]")); } catch { return []; } }
function sceneText(value: unknown) { return parseScenes(value).join("、") || "-"; }
function mileageText(row: Row) { return [row.mileage_start, row.mileage_end].filter(Boolean).join(" - ") || "-"; }
function formatDate(value: unknown) { return value ? new Date(String(value)).toLocaleString("zh-CN", { hour12: false }) : "未指定"; }
function priorityLabel(value: unknown) { return ({ urgent: "紧急", high: "优先", normal: "普通" } as Record<string, string>)[String(value)] || String(value || "普通"); }
function approvalLabel(value: unknown) { return ({ APPROVED: "已审批", DRAFT: "待审批", PENDING: "审批中", REJECTED: "已驳回" } as Record<string, string>)[String(value)] || String(value || "待审批"); }
function missionLabel(value: unknown) { return ({ DISPATCHING: "下发中", DISPATCHED: "已下发", PREPARING: "准备中", FLYING: "飞行中", PAUSED: "已暂停", RETURNING: "返航中", UPLOADING: "数据回传", COMPLETED: "飞行完成", CANCELLED: "已取消", ABORTED: "已中止", FAILED: "失败", DISPATCH_FAILED: "下发失败" } as Record<string, string>)[String(value)] || String(value || "-"); }
function taskSource(row: Row) { if (row.plan_id) return row.trigger_type === "MANUAL" ? "手动巡检" : `周期计划 · ${row.plan_name || row.plan_id}`; return row.external_task_id || "历史任务"; }

function workflowStep(row: Row) {
  const phase = taskPhase(row);
  if (phase === "completed") return 4;
  if (["uploading", "processing"].includes(phase)) return 3;
  if (["flying", "paused", "returning", "failed"].includes(phase)) return 2;
  if (["dispatching", "dispatched", "preparing"].includes(phase)) return 2;
  return 1;
}

function guidanceType(row: Row): "success" | "warning" | "info" | "error" {
  const phase = taskPhase(row);
  if (phase === "completed") return "success";
  if (phase === "failed") return "error";
  if (["awaiting_approval", "route_pending", "paused"].includes(phase)) return "warning";
  return "info";
}

function nextActionText(row: Row) {
  const phase = taskPhase(row);
  const messages: Record<TaskPhase, string> = {
    awaiting_approval: "任务尚未审批通过，审批完成前不能下发航线。",
    route_pending: row.route_id ? "任务航线尚未发布，请完成校验和发布后再下发。" : "任务尚未关联航线，请先完成航线配置。",
    ready: "执行准备已完成，可进入无人机运行选择厂商连接和在线设备后下发。",
    dispatching: "航线正在下发，请等待厂商回执，勿重复操作。",
    dispatched: "航线已下发，等待在无人机运行工作台启动飞行。",
    preparing: "无人机正在执行起飞前准备，请在运行工作台关注设备状态。",
    flying: "任务飞行执行中，可进入无人机运行查看遥测和控制命令。",
    paused: "飞行任务已暂停，请在无人机运行工作台选择恢复或返航。",
    returning: "无人机正在返航，任务不可取消或重复下发。",
    uploading: "飞行结束，数据正在回传。",
    processing: "飞行已完成，等待资源接入和智能分析完成。",
    completed: "任务已完成，可查看数据资源和分析结果。",
    failed: row.mission_error_message ? `任务执行异常：${row.mission_error_message}` : "任务执行异常，请进入无人机运行查看飞行记录和错误信息。",
    cancelled: "任务已取消，不再允许下发航线。"
  };
  return messages[phase];
}

async function load() {
  loading.value = true;
  try {
    rows.value = await tasks();
    if (selectedTask.value) {
      selectedTask.value = rows.value.find((item) => item.task_id === selectedTask.value?.task_id) || null;
    }
    openRouteTask();
  } finally {
    loading.value = false;
  }
}

function startManualInspection() { router.push({ path: "/planning", query: { create: "manual" } }); }
function openDispatchWorkspace(row: Row) { router.push({ path: "/uav-operations", query: { tab: "missions", dispatchTaskId: String(row.task_id) } }); }
function openMission(row: Row) { router.push({ path: "/uav-operations", query: { tab: "missions", missionId: String(row.mission_id) } }); }
function openResources(row: Row) { router.push({ path: "/resources", query: { taskId: String(row.task_id) } }); }
function openMap(row: Row) { router.push({ path: "/gis", query: { taskId: String(row.task_id) } }); }
function configureRoute(row: Row) {
  const objectId = parseIds(row.object_scope)[0];
  router.push({ path: "/routes", query: objectId ? { objectId, taskId: String(row.task_id) } : { taskId: String(row.task_id) } });
}

async function cancel(row: Row) {
  try {
    await ElMessageBox.confirm("仅尚未下发的任务可以取消。确认取消该巡检任务？", "取消任务", { type: "warning" });
    await cancelInspectionTask(String(row.task_id));
    ElMessage.success("任务已取消");
    await load();
  } catch {
    // 用户取消确认或接口拒绝后保持当前列表。
  }
}

function openDetail(row: Row) {
  selectedTask.value = row;
  detailVisible.value = true;
  router.replace({ path: `/tasks/${row.task_id}`, query: route.query });
}

function openRouteTask() {
  const id = String(route.params.taskId || "");
  if (!id) return;
  const row = rows.value.find((item) => String(item.task_id) === id);
  if (row) {
    selectedTask.value = row;
    detailVisible.value = true;
  }
}

watch(detailVisible, (visible) => {
  if (!visible && route.params.taskId) router.replace({ path: "/tasks", query: route.query });
});
onMounted(load);
</script>

<style scoped>
.task-entry-tip { margin-bottom: 14px; }
.status-stack { display: flex; align-items: flex-start; flex-direction: column; gap: 4px; }
.status-stack small { color: var(--el-text-color-secondary); }
.warning-text { color: var(--el-color-warning); }
.detail-guidance { margin-bottom: 22px; }
.task-workflow { margin: 10px 0 28px; }
</style>
