<template>
  <div v-loading="loading">
    <PageHeader title="巡检计划" description="管理周期计划、巡检对象、任务生成和执行准备">
      <el-button :icon="Refresh" @click="load">刷新</el-button>
      <el-button type="primary" :icon="Plus" @click="openPlanDialog()">新建计划</el-button>
    </PageHeader>

    <section class="metric-strip">
      <div class="metric-card"><strong>{{ plans.length }}</strong><span>巡检计划</span><small>{{ periodicPlans }} 个周期 · {{ manualPlans }} 个手动</small></div>
      <div class="metric-card"><strong>{{ objects.length }}</strong><span>巡检对象</span><small>线路、桥隧、防洪与电力</small></div>
      <div class="metric-card"><strong>{{ highRiskObjects }}</strong><span>重点对象</span><small>高及以上风险</small></div>
      <div class="metric-card"><strong>{{ generatedTasks }}</strong><span>已生成任务</span><small>由计划自动生成</small></div>
    </section>

    <el-tabs v-model="activeTab" class="secondary-tabs">
      <el-tab-pane label="计划日历与清单" name="plans">
        <el-card class="workspace-card" shadow="never">
          <el-table :data="plans" empty-text="暂无巡检计划" @row-click="inspectPlan">
            <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.plan_id }}</small></template></el-table-column>
            <el-table-column label="巡检方式" width="105"><template #default="scope"><el-tag :type="scope.row.trigger_type === 'MANUAL' ? 'warning' : 'primary'" effect="plain">{{ triggerTypeLabel(scope.row.trigger_type) }}</el-tag></template></el-table-column>
            <el-table-column label="业务类型" width="100"><template #default="scope">{{ planTypeLabel(scope.row.plan_type) }}</template></el-table-column>
            <el-table-column label="执行安排" min-width="190"><template #default="scope">{{ scheduleText(scope.row) }}</template></el-table-column>
            <el-table-column label="巡检对象" width="100"><template #default="scope">{{ parseArray(scope.row.object_ids).length }} 个</template></el-table-column>
            <el-table-column label="识别场景" width="100"><template #default="scope">{{ parseArray(scope.row.scene_set).length }} 项</template></el-table-column>
            <el-table-column prop="owner_org_name" label="责任单位" min-width="130" />
            <el-table-column label="下次/计划执行" min-width="165"><template #default="scope">{{ executionDateText(scope.row) }}</template></el-table-column>
            <el-table-column label="状态" width="105"><template #default="scope"><el-tag :type="planStatusTag(scope.row)" effect="plain">{{ planStatusLabel(scope.row) }}</el-tag></template></el-table-column>
            <el-table-column label="操作" width="230" fixed="right"><template #default="scope"><div class="list-actions" @click.stop><el-button v-if="scope.row.trigger_type !== 'MANUAL' && scope.row.status !== 'ACTIVE'" link type="primary" @click="activate(scope.row)">启用计划</el-button><el-button v-if="scope.row.trigger_type !== 'MANUAL' || !Number(scope.row.generated_task_count)" link type="primary" @click="generate(scope.row)">{{ scope.row.trigger_type === 'MANUAL' ? '创建任务' : '立即生成' }}</el-button><el-button link @click="inspectPlan(scope.row)">详情</el-button></div></template></el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="巡检对象台账" name="objects">
        <div class="filter-bar"><el-input v-model="keyword" clearable placeholder="对象、线路或里程" :prefix-icon="Search" /><el-select v-model="objectType"><el-option label="全部类型" value="" /><el-option v-for="item in objectTypes" :key="item.value" :label="item.label" :value="item.value" /></el-select><span class="filter-spacer"></span><el-button type="primary" plain :icon="Plus" @click="objectDialog = true">新增对象</el-button></div>
        <el-card class="workspace-card" shadow="never"><el-table :data="filteredObjects" empty-text="暂无巡检对象">
          <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.object_id }}</small></template></el-table-column>
          <el-table-column label="类型" width="100"><template #default="scope">{{ objectTypeLabel(scope.row.object_type) }}</template></el-table-column>
          <el-table-column prop="line_id" label="线路" width="110" />
          <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 prop="owner_org_name" label="责任单位" min-width="130" />
          <el-table-column label="风险" width="90"><template #default="scope"><el-tag :type="['CRITICAL','HIGH'].includes(scope.row.risk_level) ? 'danger' : 'info'" effect="plain">{{ scope.row.risk_level }}</el-tag></template></el-table-column>
          <el-table-column label="周期" width="90"><template #default="scope">{{ scope.row.inspection_cycle_days ? `${scope.row.inspection_cycle_days} 天` : '-' }}</template></el-table-column>
          <el-table-column prop="source_crs" label="坐标系" width="105" />
        </el-table></el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="planDialog" class="plan-create-dialog" :title="planTrigger === 'MANUAL' ? '发起手动巡检' : '新建周期巡检计划'" width="min(780px, 96vw)" destroy-on-close :close-on-click-modal="false">
      <InspectionPlanForm v-if="planDialog" :key="planFormKey" :objects="objects" :scenes="scenes" :saving="saving" :initial-trigger="planTrigger" @cancel="planDialog = false" @submit="savePlan" />
    </el-dialog>

    <el-dialog v-model="objectDialog" title="新增巡检对象" width="min(640px, 94vw)">
      <el-form label-position="top"><div class="form-grid">
        <el-form-item label="对象名称"><el-input v-model="objectForm.name" /></el-form-item><el-form-item label="对象类型"><el-select v-model="objectForm.object_type"><el-option v-for="item in objectTypes" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
        <el-form-item label="线路"><el-input v-model="objectForm.line_id" /></el-form-item><el-form-item label="风险等级"><el-select v-model="objectForm.risk_level"><el-option label="一般" value="NORMAL" /><el-option label="高" value="HIGH" /><el-option label="重大" value="CRITICAL" /></el-select></el-form-item>
        <el-form-item label="起始里程"><el-input v-model="objectForm.mileage_start" /></el-form-item><el-form-item label="结束里程"><el-input v-model="objectForm.mileage_end" /></el-form-item>
        <el-form-item label="经度"><el-input-number v-model="objectForm.longitude" :precision="6" :step="0.001" /></el-form-item><el-form-item label="纬度"><el-input-number v-model="objectForm.latitude" :precision="6" :step="0.001" /></el-form-item>
      </div></el-form>
      <template #footer><el-button @click="objectDialog = false">取消</el-button><el-button type="primary" :loading="saving" @click="saveObject">创建</el-button></template>
    </el-dialog>

    <el-drawer v-model="detailVisible" title="计划详情" size="560px"><template v-if="selectedPlan"><el-descriptions :column="1" border><el-descriptions-item label="计划编号"><span class="entity-id">{{ selectedPlan.plan_id }}</span></el-descriptions-item><el-descriptions-item label="巡检方式">{{ triggerTypeLabel(selectedPlan.trigger_type) }}</el-descriptions-item><el-descriptions-item label="业务类型">{{ planTypeLabel(selectedPlan.plan_type) }}</el-descriptions-item><el-descriptions-item label="执行安排">{{ scheduleText(selectedPlan) }}</el-descriptions-item><el-descriptions-item label="下次/计划执行">{{ executionDateText(selectedPlan) }}</el-descriptions-item><el-descriptions-item label="优先级">{{ priorityLabel(selectedPlan.priority) }}</el-descriptions-item><el-descriptions-item label="对象">{{ objectNames(selectedPlan.object_ids) }}</el-descriptions-item><el-descriptions-item label="场景">{{ parseArray(selectedPlan.scene_set).join('、') }}</el-descriptions-item><el-descriptions-item label="已生成任务">{{ selectedPlan.generated_task_count }}</el-descriptions-item></el-descriptions></template></el-drawer>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Plus, Refresh, Search } from "@element-plus/icons-vue";
import PageHeader from "../../components/common/PageHeader.vue";
import InspectionPlanForm from "../../components/planning/InspectionPlanForm.vue";
import { activateInspectionPlan, createInspectionObject, createInspectionPlan, generatePlanTasks, inspectionObjects, inspectionPlans } from "../../services/api";
import { safeObject, type Row } from "../../types/demo-run";

const route = useRoute(); const router = useRouter();
const plans = ref<Row[]>([]); const objects = ref<Row[]>([]); const loading = ref(false); const saving = ref(false); const activeTab = ref("plans"); const keyword = ref(""); const objectType = ref("");
const planDialog = ref(false); const planFormKey = ref(0); const planTrigger = ref<"PERIODIC" | "MANUAL">("PERIODIC"); const objectDialog = ref(false); const detailVisible = ref(false); const selectedPlan = ref<Row | null>(null);
const objectTypes = [{ value: "RAILWAY", label: "铁路线路" }, { value: "BRIDGE", label: "桥梁" }, { value: "TUNNEL", label: "隧道" }, { value: "FLOOD", label: "防洪设施" }, { value: "POWER", label: "电力设施" }];
const scenes = ["异物侵限", "护网破损", "桥梁裂缝", "隧道渗漏", "防洪体积变化", "接触网异物", "设备发热"];
const objectForm = reactive({ name: "", object_type: "RAILWAY", line_id: "line-demo", mileage_start: "", mileage_end: "", risk_level: "NORMAL", longitude: 116.1, latitude: 39.1 });
const periodicPlans = computed(() => plans.value.filter((item) => item.trigger_type !== "MANUAL").length); const manualPlans = computed(() => plans.value.filter((item) => item.trigger_type === "MANUAL").length); const highRiskObjects = computed(() => objects.value.filter((item) => ["HIGH", "CRITICAL"].includes(item.risk_level)).length); const generatedTasks = computed(() => plans.value.reduce((sum, item) => sum + Number(item.generated_task_count || 0), 0));
const filteredObjects = computed(() => objects.value.filter((item) => (!objectType.value || item.object_type === objectType.value) && (!keyword.value || `${item.name} ${item.line_id} ${item.mileage_start}`.toLowerCase().includes(keyword.value.toLowerCase()))));
function parseArray(value: unknown): string[] { try { return Array.isArray(value) ? value.map(String) : JSON.parse(String(value || "[]")); } catch { return []; } }
function planTypeLabel(value: unknown) { return ({ DAILY: "日常", SPECIAL: "专项", EMERGENCY: "应急" } as Record<string, string>)[String(value)] || String(value); }
function triggerTypeLabel(value: unknown) { return String(value || "PERIODIC") === "MANUAL" ? "手动巡检" : "周期巡检"; }
function priorityLabel(value: unknown) { return ({ normal: "普通", high: "优先", urgent: "紧急" } as Record<string, string>)[String(value)] || String(value || "普通"); }
function objectTypeLabel(value: unknown) { return objectTypes.find((item) => item.value === value)?.label || String(value); }
function formatDate(value: unknown) { return value ? new Date(String(value)).toLocaleString("zh-CN", { hour12: false }) : "-"; }
function executionDateText(row: Row) { return row.next_run_at ? formatDate(row.next_run_at) : row.trigger_type === "MANUAL" ? "立即创建" : "启用后计算"; }
function scheduleText(row: Row) {
  const triggerType = String(row.trigger_type || (row.schedule_rule ? "PERIODIC" : "MANUAL"));
  const config = safeObject(row.schedule_config);
  if (triggerType === "MANUAL") return String(config.timing) === "SCHEDULED" ? "预约一次执行" : "人工触发，执行一次";
  const time = String(config.execution_time || "").trim();
  if (config.frequency === "DAILY") return `每 ${Number(config.interval_days || 1)} 天${time ? ` ${time}` : ""}`;
  if (config.frequency === "WEEKLY") return `每周 ${parseArray(config.weekdays).map(weekdayLabel).join("、")}${time ? ` ${time}` : ""}`;
  if (config.frequency === "MONTHLY") return `每月 ${parseNumberArray(config.month_days).join("、")} 日${time ? ` ${time}` : ""}`;
  return row.schedule_rule || "周期规则待配置";
}
function weekdayLabel(value: string) { return ({ MON: "周一", TUE: "周二", WED: "周三", THU: "周四", FRI: "周五", SAT: "周六", SUN: "周日" } as Record<string, string>)[value] || value; }
function parseNumberArray(value: unknown): number[] { return Array.isArray(value) ? value.map(Number) : []; }
function planStatusLabel(row: Row) { if (row.trigger_type === "MANUAL") return Number(row.generated_task_count) ? "任务已生成" : "待创建任务"; return row.status === "ACTIVE" ? "已启用" : "草稿"; }
function planStatusTag(row: Row): "success" | "warning" | "info" { if (row.trigger_type === "MANUAL") return Number(row.generated_task_count) ? "success" : "warning"; return row.status === "ACTIVE" ? "success" : "info"; }
function objectNames(value: unknown) { const ids = parseArray(value); return ids.map((id) => objects.value.find((item) => item.object_id === id)?.name || id).join("、"); }
async function load() { loading.value = true; try { [plans.value, objects.value] = await Promise.all([inspectionPlans(), inspectionObjects()]); } finally { loading.value = false; } }
function openPlanDialog(trigger: "PERIODIC" | "MANUAL" = "PERIODIC") { planTrigger.value = trigger; planFormKey.value += 1; planDialog.value = true; }
async function savePlan(request: { payload: Record<string, unknown>; generateTasks: boolean }) { saving.value = true; try { const created = await createInspectionPlan(request.payload); if (request.generateTasks) { const result = await generatePlanTasks(String(created.plan_id)); ElMessage.success(`手动巡检已创建 ${result.generated} 条任务`); } else { ElMessage.success("周期巡检计划已创建，请确认后启用"); } planDialog.value = false; await load(); } finally { saving.value = false; } }
async function saveObject() { if (!objectForm.name || !objectForm.line_id) return ElMessage.warning("请填写对象名称和线路"); saving.value = true; try { await createInspectionObject({ ...objectForm, geometry: { type: "Point", coordinates: [objectForm.longitude, objectForm.latitude] }, owner_org_id: objectForm.object_type === "FLOOD" ? "org-flood" : "org-works", inspection_cycle_days: 7, source_crs: "EPSG:4326" }); objectDialog.value = false; ElMessage.success("巡检对象已创建"); await load(); } finally { saving.value = false; } }
async function activate(row: Row) { await activateInspectionPlan(String(row.plan_id)); ElMessage.success("计划已启用"); await load(); }
async function generate(row: Row) { const result = await generatePlanTasks(String(row.plan_id)); ElMessage.success(`已生成 ${result.generated} 个巡检任务`); await load(); }
function inspectPlan(row: Row) { selectedPlan.value = row; detailVisible.value = true; }
onMounted(async () => {
  await load();
  if (route.query.create === "manual") {
    openPlanDialog("MANUAL");
    const query = { ...route.query };
    delete query.create;
    router.replace({ path: "/planning", query });
  }
});
</script>

<style scoped>
:global(.plan-create-dialog) { margin-top: 4vh; }
:global(.plan-create-dialog .el-dialog__body) { max-height: calc(92vh - 118px); overflow-y: auto; }
</style>
