<template>
  <el-form class="inspection-plan-form" label-position="top" @submit.prevent>
    <section class="form-section">
      <header><strong>选择巡检方式</strong><span>周期巡检按固定规则重复执行，手动巡检用于一次性或临时任务</span></header>
      <div class="trigger-selector">
        <button type="button" :class="{ active: form.trigger_type === 'PERIODIC' }" @click="selectTrigger('PERIODIC')">
          <i>周期</i><span><strong>周期巡检</strong><small>每天、每周或每月定时执行</small></span><em>{{ form.trigger_type === "PERIODIC" ? "已选择" : "选择" }}</em>
        </button>
        <button type="button" :class="{ active: form.trigger_type === 'MANUAL' }" @click="selectTrigger('MANUAL')">
          <i>手动</i><span><strong>手动巡检</strong><small>立即创建或预约一次巡检任务</small></span><em>{{ form.trigger_type === "MANUAL" ? "已选择" : "选择" }}</em>
        </button>
      </div>
    </section>

    <el-alert
      :title="form.trigger_type === 'PERIODIC' ? '创建后先保存为草稿，确认无误后在计划列表启用。' : '创建手动巡检后会同步生成一次性巡检任务。'"
      type="info"
      :closable="false"
      show-icon
    />

    <section class="form-section">
      <header><strong>基本信息</strong><span>用于识别计划用途并确定处置优先级</span></header>
      <div class="form-grid">
        <el-form-item label="计划名称" required>
          <el-input v-model="form.name" maxlength="80" show-word-limit :placeholder="namePlaceholder" />
        </el-form-item>
        <el-form-item label="业务类型" required>
          <el-select v-model="form.plan_type">
            <el-option label="日常巡检" value="DAILY"><span>日常巡检</span><small class="option-note">常规线路与设施检查</small></el-option>
            <el-option label="专项巡检" value="SPECIAL"><span>专项巡检</span><small class="option-note">特定隐患或专业检查</small></el-option>
            <el-option label="应急巡检" value="EMERGENCY"><span>应急巡检</span><small class="option-note">突发事件快速响应</small></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="任务优先级" required>
        <el-radio-group v-model="form.priority">
          <el-radio-button value="normal">普通</el-radio-button>
          <el-radio-button value="high">优先</el-radio-button>
          <el-radio-button value="urgent">紧急</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </section>

    <section v-if="form.trigger_type === 'PERIODIC'" class="form-section schedule-section">
      <header><strong>周期安排</strong><span>无需填写 Cron 表达式，系统会根据选项自动生成规则</span></header>
      <el-form-item label="重复频率" required>
        <el-radio-group v-model="form.frequency" @change="normalizeFrequency">
          <el-radio-button value="DAILY">每天</el-radio-button>
          <el-radio-button value="WEEKLY">每周</el-radio-button>
          <el-radio-button value="MONTHLY">每月</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <div v-if="form.frequency === 'DAILY'" class="schedule-choice">
        <span>每</span><el-input-number v-model="form.interval_days" :min="1" :max="30" controls-position="right" /><span>天执行一次</span>
      </div>
      <el-form-item v-else-if="form.frequency === 'WEEKLY'" label="执行星期" required>
        <el-checkbox-group v-model="form.weekdays" class="weekday-selector">
          <el-checkbox-button v-for="item in weekdayOptions" :key="item.value" :value="item.value">{{ item.label }}</el-checkbox-button>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item v-else label="每月执行日期" required>
        <el-select v-model="form.month_days" multiple collapse-tags :max-collapse-tags="5" placeholder="选择每月日期">
          <el-option v-for="day in monthDayOptions" :key="day" :label="`${day} 日`" :value="day" />
        </el-select>
        <small class="field-help">仅提供 1—28 日，避免短月份没有对应日期。</small>
      </el-form-item>

      <div class="form-grid">
        <el-form-item label="开始日期" required>
          <el-date-picker v-model="form.start_date" type="date" :disabled-date="disablePastDate" placeholder="选择生效日期" />
        </el-form-item>
        <el-form-item label="执行时间" required>
          <el-time-select v-model="form.execution_time" start="00:00" step="00:30" end="23:30" placeholder="选择执行时间" />
        </el-form-item>
      </div>
    </section>

    <section v-else class="form-section schedule-section">
      <header><strong>执行安排</strong><span>手动巡检只生成一次任务，不会按周期重复</span></header>
      <el-form-item label="任务时间" required>
        <div class="manual-timing-selector">
          <button type="button" :class="{ active: form.manual_timing === 'NOW' }" @click="form.manual_timing = 'NOW'">
            <strong>立即创建</strong><span>任务创建后进入待执行队列</span>
          </button>
          <button type="button" :class="{ active: form.manual_timing === 'SCHEDULED' }" @click="form.manual_timing = 'SCHEDULED'">
            <strong>预约执行</strong><span>指定未来的计划开始时间</span>
          </button>
        </div>
      </el-form-item>
      <el-form-item v-if="form.manual_timing === 'SCHEDULED'" label="计划执行时间" required>
        <el-date-picker v-model="form.manual_start_at" type="datetime" :disabled-date="disablePastDate" placeholder="选择未来时间" />
      </el-form-item>
    </section>

    <section class="form-section">
      <header><strong>巡检范围</strong><span>选择本次需要覆盖的业务对象和识别场景</span></header>
      <el-form-item label="巡检对象" required>
        <el-select v-model="form.object_ids" multiple filterable collapse-tags :max-collapse-tags="3" placeholder="搜索并选择线路、桥隧或设施">
          <el-option v-for="item in objects" :key="item.object_id" :label="objectOptionLabel(item)" :value="item.object_id">
            <div class="object-option"><span><strong>{{ item.name }}</strong><small>{{ objectTypeLabel(item.object_type) }} · {{ item.line_id }}</small></span><em>{{ mileageText(item) }}</em></div>
          </el-option>
        </el-select>
        <small class="field-help">每个巡检对象会生成一条独立任务，便于调度和追踪。</small>
      </el-form-item>
      <el-form-item label="识别场景" required>
        <el-checkbox-group v-model="form.scene_set" class="scene-selector">
          <el-checkbox v-for="scene in scenes" :key="scene" :value="scene" border>{{ scene }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </section>

    <section class="plan-summary">
      <div><span>巡检方式</span><strong>{{ triggerLabel }}</strong></div>
      <div><span>执行安排</span><strong>{{ scheduleSummary }}</strong></div>
      <div><span>任务规模</span><strong>{{ form.object_ids.length }} 个对象 · {{ form.scene_set.length }} 个场景</strong></div>
    </section>

    <footer class="form-actions">
      <el-button @click="emit('cancel')">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submit">{{ submitLabel }}</el-button>
    </footer>
  </el-form>
</template>

<script setup lang="ts">
import { computed, reactive, watch } from "vue";
import { ElMessage } from "element-plus";
import type { Row } from "../../types/demo-run";

const props = defineProps<{
  objects: Row[];
  scenes: string[];
  saving: boolean;
  initialTrigger?: "PERIODIC" | "MANUAL";
}>();
const emit = defineEmits<{
  cancel: [];
  submit: [request: { payload: Record<string, unknown>; generateTasks: boolean }];
}>();

const form = reactive({
  name: "",
  trigger_type: (props.initialTrigger || "PERIODIC") as "PERIODIC" | "MANUAL",
  plan_type: props.initialTrigger === "MANUAL" ? "SPECIAL" : "DAILY",
  priority: "normal",
  frequency: "WEEKLY" as "DAILY" | "WEEKLY" | "MONTHLY",
  interval_days: 1,
  weekdays: ["MON"] as string[],
  month_days: [1] as number[],
  start_date: tomorrow(),
  execution_time: "09:00",
  manual_timing: "NOW" as "NOW" | "SCHEDULED",
  manual_start_at: tomorrowAt(9),
  object_ids: [] as string[],
  scene_set: [] as string[]
});

const weekdayOptions = [
  { value: "MON", label: "周一" }, { value: "TUE", label: "周二" }, { value: "WED", label: "周三" },
  { value: "THU", label: "周四" }, { value: "FRI", label: "周五" }, { value: "SAT", label: "周六" },
  { value: "SUN", label: "周日" }
];
const monthDayOptions = Array.from({ length: 28 }, (_, index) => index + 1);
const triggerLabel = computed(() => form.trigger_type === "PERIODIC" ? "周期巡检" : "手动巡检");
const submitLabel = computed(() => form.trigger_type === "PERIODIC" ? "创建周期计划" : "创建手动任务");
const namePlaceholder = computed(() => form.trigger_type === "PERIODIC" ? "例如：京广线接触网每周巡检" : "例如：K123 区段雨后专项巡检");
const scheduleSummary = computed(() => {
  if (form.trigger_type === "MANUAL") {
    return form.manual_timing === "NOW" ? "立即创建，人工下发" : formatDateTime(form.manual_start_at);
  }
  if (form.frequency === "DAILY") return `每 ${form.interval_days} 天 ${form.execution_time}`;
  if (form.frequency === "WEEKLY") {
    const labels = form.weekdays.map((day) => weekdayOptions.find((item) => item.value === day)?.label || day);
    return `每周 ${labels.join("、")} ${form.execution_time}`;
  }
  return `每月 ${form.month_days.slice().sort((a, b) => a - b).join("、")} 日 ${form.execution_time}`;
});

watch(() => form.trigger_type, (value) => {
  form.plan_type = value === "PERIODIC" ? "DAILY" : "SPECIAL";
});

function selectTrigger(value: "PERIODIC" | "MANUAL") {
  form.trigger_type = value;
}

function normalizeFrequency() {
  if (form.frequency === "WEEKLY" && !form.weekdays.length) form.weekdays = ["MON"];
  if (form.frequency === "MONTHLY" && !form.month_days.length) form.month_days = [1];
}

function submit() {
  if (!form.name.trim()) return ElMessage.warning("请填写便于识别的计划名称");
  if (!form.object_ids.length) return ElMessage.warning("请至少选择一个巡检对象");
  if (!form.scene_set.length) return ElMessage.warning("请至少选择一个识别场景");

  let nextRunAt: string | null = null;
  let scheduleRule: string | null = null;
  let scheduleConfig: Record<string, unknown>;

  if (form.trigger_type === "PERIODIC") {
    if (!form.start_date || !form.execution_time) return ElMessage.warning("请选择周期计划的开始日期和执行时间");
    if (form.frequency === "WEEKLY" && !form.weekdays.length) return ElMessage.warning("请至少选择一个执行星期");
    if (form.frequency === "MONTHLY" && !form.month_days.length) return ElMessage.warning("请至少选择一个每月执行日期");
    const firstRun = combineDateAndTime(form.start_date, form.execution_time);
    if (firstRun.getTime() <= Date.now()) return ElMessage.warning("首次执行时间必须晚于当前时间");
    nextRunAt = firstRun.toISOString();
    scheduleRule = buildCronRule();
    scheduleConfig = {
      frequency: form.frequency,
      interval_days: form.frequency === "DAILY" ? form.interval_days : undefined,
      weekdays: form.frequency === "WEEKLY" ? form.weekdays : undefined,
      month_days: form.frequency === "MONTHLY" ? form.month_days : undefined,
      start_date: toDateKey(form.start_date),
      execution_time: form.execution_time,
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || "Asia/Shanghai"
    };
  } else {
    if (form.manual_timing === "SCHEDULED") {
      if (!form.manual_start_at || form.manual_start_at.getTime() <= Date.now()) return ElMessage.warning("请选择晚于当前时间的预约执行时间");
      nextRunAt = form.manual_start_at.toISOString();
    }
    scheduleConfig = { timing: form.manual_timing };
  }

  emit("submit", {
    payload: {
      name: form.name.trim(),
      trigger_type: form.trigger_type,
      plan_type: form.plan_type,
      schedule_rule: scheduleRule,
      schedule_config: scheduleConfig,
      object_ids: form.object_ids,
      scene_set: form.scene_set,
      priority: form.priority,
      next_run_at: nextRunAt,
      owner_org_id: "org-railway",
      created_by: "user-dispatcher"
    },
    generateTasks: form.trigger_type === "MANUAL"
  });
}

function buildCronRule() {
  const [hour, minute] = form.execution_time.split(":").map(Number);
  if (form.frequency === "DAILY") return `0 ${minute} ${hour} */${form.interval_days} * *`;
  if (form.frequency === "WEEKLY") return `0 ${minute} ${hour} * * ${form.weekdays.join(",")}`;
  return `0 ${minute} ${hour} ${form.month_days.slice().sort((a, b) => a - b).join(",")} * *`;
}

function objectOptionLabel(item: Row) {
  return `${item.name} / ${item.line_id} / ${mileageText(item)}`;
}

function objectTypeLabel(value: unknown) {
  return ({ RAILWAY: "铁路线路", BRIDGE: "桥梁", TUNNEL: "隧道", FLOOD: "防洪设施", POWER: "电力设施" } as Record<string, string>)[String(value)] || String(value || "巡检对象");
}

function mileageText(item: Row) {
  return [item.mileage_start, item.mileage_end].filter(Boolean).join(" - ") || "里程待补充";
}

function disablePastDate(date: Date) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date.getTime() < today.getTime();
}

function combineDateAndTime(date: Date, time: string) {
  const result = new Date(date);
  const [hour, minute] = time.split(":").map(Number);
  result.setHours(hour, minute, 0, 0);
  return result;
}

function tomorrow() {
  const date = new Date();
  date.setDate(date.getDate() + 1);
  date.setHours(0, 0, 0, 0);
  return date;
}

function tomorrowAt(hour: number) {
  const date = tomorrow();
  date.setHours(hour, 0, 0, 0);
  return date;
}

function toDateKey(value: Date) {
  const year = value.getFullYear();
  const month = String(value.getMonth() + 1).padStart(2, "0");
  const day = String(value.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

function formatDateTime(value: Date) {
  return value.toLocaleString("zh-CN", { hour12: false, month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit" });
}
</script>

<style scoped>
.inspection-plan-form { display: grid; gap: 15px; }
.form-section { padding: 15px; border: 1px solid #dce4ed; border-radius: 7px; background: #fff; }
.form-section > header { margin-bottom: 14px; }
.form-section > header strong, .form-section > header span { display: block; }
.form-section > header strong { color: #17365d; font-size: 15px; }
.form-section > header span { margin-top: 4px; color: #64748b; font-size: 11px; }
.trigger-selector { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
.trigger-selector button { min-width: 0; min-height: 78px; padding: 12px; display: grid; grid-template-columns: 46px minmax(0, 1fr) auto; align-items: center; gap: 11px; border: 1px solid #dce4ed; border-radius: 7px; background: #fff; color: #334155; cursor: pointer; text-align: left; transition: .18s ease; }
.trigger-selector button:hover { border-color: #93abc5; background: #f8fafc; }
.trigger-selector button.active { border-color: #2563eb; background: #eff6ff; box-shadow: 0 0 0 1px rgba(37, 99, 235, .08); }
.trigger-selector i { width: 44px; height: 44px; display: grid; place-items: center; border-radius: 6px; background: #e2e8f0; color: #475569; font-size: 11px; font-style: normal; font-weight: 800; }
.trigger-selector button.active i { background: #2563eb; color: #fff; }
.trigger-selector strong, .trigger-selector small { display: block; }
.trigger-selector strong { color: #17365d; font-size: 14px; }
.trigger-selector small { margin-top: 4px; color: #64748b; font-size: 11px; line-height: 1.35; }
.trigger-selector em { color: #2563eb; font-size: 11px; font-style: normal; font-weight: 700; }
.form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0 14px; }
.inspection-plan-form :deep(.el-form-item) { margin-bottom: 14px; }
.inspection-plan-form :deep(.el-form-item:last-child) { margin-bottom: 0; }
.inspection-plan-form :deep(.el-select), .inspection-plan-form :deep(.el-date-editor), .inspection-plan-form :deep(.el-time-select) { width: 100%; }
.option-note { margin-left: 10px; color: #94a3b8; font-size: 11px; }
.field-help { display: block; margin-top: 6px; color: #94a3b8; font-size: 10px; line-height: 1.4; }
.schedule-section { background: #f8fafc; }
.schedule-choice { min-height: 48px; margin-bottom: 14px; display: flex; align-items: center; gap: 9px; color: #475569; font-size: 13px; }
.schedule-choice :deep(.el-input-number) { width: 128px; }
.weekday-selector { display: flex; flex-wrap: wrap; }
.manual-timing-selector { width: 100%; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
.manual-timing-selector button { min-height: 64px; padding: 11px 12px; border: 1px solid #dce4ed; border-radius: 6px; background: #fff; color: #334155; cursor: pointer; text-align: left; }
.manual-timing-selector button.active { border-color: #2563eb; background: #eff6ff; }
.manual-timing-selector strong, .manual-timing-selector span { display: block; }
.manual-timing-selector strong { color: #17365d; font-size: 13px; }
.manual-timing-selector span { margin-top: 4px; color: #64748b; font-size: 11px; }
.object-option { width: 100%; display: flex; align-items: center; justify-content: space-between; gap: 12px; }
.object-option strong, .object-option small { display: block; }
.object-option small { color: #94a3b8; font-size: 10px; }
.object-option em { color: #64748b; font-size: 11px; font-style: normal; }
.scene-selector { display: flex; flex-wrap: wrap; gap: 7px; }
.scene-selector :deep(.el-checkbox) { margin: 0; }
.plan-summary { padding: 13px 15px; display: grid; grid-template-columns: .8fr 1.5fr 1fr; gap: 14px; border-radius: 7px; background: #17365d; color: #fff; }
.plan-summary span, .plan-summary strong { display: block; }
.plan-summary span { color: #bfdbfe; font-size: 10px; }
.plan-summary strong { margin-top: 5px; font-size: 12px; line-height: 1.4; }
.form-actions { display: flex; justify-content: flex-end; gap: 8px; }
@media (max-width: 680px) {
  .trigger-selector, .form-grid, .manual-timing-selector, .plan-summary { grid-template-columns: 1fr; }
}
</style>
