<template>
  <div class="p-2">
    <el-card shadow="never" class="hero-card">
      <div class="hero-grid">
        <div class="hero-main">
          <div class="hero-kicker">ALARM CENTER</div>
          <div class="hero-title">报警中心工作台</div>
          <div class="hero-desc">把告警主记录与确认处理动作收敛到一个入口里，值班人员只需要围绕记录列表、详情和处置闭环工作。</div>
          <div class="hero-tags">
            <el-tag effect="dark" round class="hero-tag">实时告警闭环</el-tag>
            <el-tag effect="plain" round class="hero-tag">{{ currentAlarmStatusLabel }}</el-tag>
          </div>
        </div>
        <div class="hero-side">
          <div class="hero-panel">
            <div class="hero-panel-label">当前详情对象</div>
            <div class="hero-panel-value">{{ selectedAlarm ? resolveMonitorName(selectedAlarm) : '未选中告警' }}</div>
            <div class="hero-panel-foot">支持在左侧记录列表点选后联动查看告警详情与确认备注。</div>
          </div>
        </div>
      </div>
    </el-card>

    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover" class="query-card">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="点位名称" prop="monitorName">
              <el-input v-model="queryParams.monitorName" placeholder="请输入点位名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="记录时间" prop="collectTime">
              <el-date-picker clearable v-model="queryParams.collectTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择记录时间" />
            </el-form-item>
            <el-form-item label="异常类型" prop="alarmType">
              <el-select v-model="queryParams.alarmType" placeholder="请选择异常类型" clearable style="width: 160px">
                <el-option v-for="item in dict.type.alarm_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="异常状态" prop="alarmStatus">
              <el-select v-model="queryParams.alarmStatus" placeholder="请选择异常状态" clearable style="width: 160px">
                <el-option v-for="item in dict.type.alarm_status" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="告警标题" prop="alarmTitle">
              <el-input v-model="queryParams.alarmTitle" placeholder="请输入告警标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <div class="summary-grid">
      <el-card shadow="never" class="summary-card">
        <div class="summary-label">匹配告警总数</div>
        <div class="summary-value">{{ overviewSummary.totalCount ?? 0 }}</div>
        <div class="summary-foot">{{ overviewLoading ? '正在按筛选条件汇总全量统计…' : '按当前筛选条件统计，不受分页结果影响' }}</div>
      </el-card>
      <el-card shadow="never" class="summary-card">
        <div class="summary-label">待处理总数</div>
        <div class="summary-value">{{ overviewSummary.unhandledCount ?? 0 }}</div>
        <div class="summary-foot">用于快速判断当前筛选范围内仍待闭环的风险规模</div>
      </el-card>
      <el-card shadow="never" class="summary-card">
        <div class="summary-label">已处理总数</div>
        <div class="summary-value">{{ overviewSummary.handledCount ?? 0 }}</div>
        <div class="summary-foot">用于判断当前筛选范围内已经完成闭环的处理量</div>
      </el-card>
    </div>

    <el-row :gutter="12">
      <el-col :xs="24" :lg="15">
        <el-card shadow="never" class="table-card">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/record:recordAlarmData:export']"
                  >导出</el-button
                >
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="CircleCheck"
                  :disabled="!selectedAlarm || selectedAlarm.alarmStatus === 0"
                  @click="handleConfirmCurrentAlarm"
                >
                  确认处理
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="info" plain icon="Refresh" @click="refreshCurrentAlarm">刷新当前详情</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
            </el-row>
          </template>

          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="recordAlarmDataList"
            highlight-current-row
            row-key="objId"
            @selection-change="handleSelectionChange"
            @row-click="handleRowClick"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="点位名称" align="center" min-width="180" show-overflow-tooltip>
              <template #default="scope">
                <div class="main-cell">{{ resolveMonitorName(scope.row) }}</div>
                <div class="sub-cell">{{ scope.row.monitorId || scope.row.collectDeviceName || '-' }}</div>
              </template>
            </el-table-column>
            <el-table-column label="记录时间" align="center" prop="collectTime" width="180">
              <template #default="scope">
                <span>{{ formatDateTime(scope.row.collectTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="异常类型" align="center" prop="alarmType" width="110">
              <template #default="scope">
                <dict-tag :options="dict.type.alarm_type" :value="scope.row.alarmType" />
              </template>
            </el-table-column>
            <el-table-column label="异常状态" align="center" prop="alarmStatus" width="110">
              <template #default="scope">
                <dict-tag :options="dict.type.alarm_status" :value="scope.row.alarmStatus" />
              </template>
            </el-table-column>
            <el-table-column label="告警级别" align="center" prop="alarmLevel" width="100" />
            <el-table-column label="告警标题" align="center" prop="alarmTitle" min-width="180" show-overflow-tooltip />
            <el-table-column label="确认备注" align="center" prop="confirmRemark" min-width="180" show-overflow-tooltip />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
              <template #default="scope">
                <el-button size="small" type="text" @click.stop="handleRowClick(scope.row)">查看</el-button>
                <el-button
                  size="small"
                  type="text"
                  icon="Edit"
                  @click.stop="handleUpdate(scope.row)"
                  v-hasPermi="['ems/record:recordAlarmData:edit']"
                >
                  修改
                </el-button>
                <el-button
                  size="small"
                  type="text"
                  icon="Delete"
                  @click.stop="handleDelete(scope.row)"
                  v-hasPermi="['ems/record:recordAlarmData:remove']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="9">
        <el-card shadow="never" class="detail-card" v-loading="detailLoading">
          <template #header>
            <div class="detail-header">
              <span>告警中心详情</span>
              <el-button link type="primary" :disabled="!selectedAlarm" @click="refreshCurrentAlarm">刷新</el-button>
            </div>
          </template>

          <el-empty v-if="!selectedAlarm" description="请选择左侧一条告警记录查看详情" />

          <template v-else>
            <el-descriptions :column="1" border size="small" class="mb-3">
              <el-descriptions-item label="告警标题">{{ selectedAlarm.alarmTitle || '-' }}</el-descriptions-item>
              <el-descriptions-item label="点位名称">{{ resolveMonitorName(selectedAlarm) }}</el-descriptions-item>
              <el-descriptions-item label="记录时间">{{ formatDateTime(selectedAlarm.collectTime) }}</el-descriptions-item>
              <el-descriptions-item label="异常类型">
                <dict-tag :options="dict.type.alarm_type" :value="selectedAlarm.alarmType" />
              </el-descriptions-item>
              <el-descriptions-item label="异常状态">
                <dict-tag :options="dict.type.alarm_status" :value="selectedAlarm.alarmStatus" />
              </el-descriptions-item>
              <el-descriptions-item label="告警级别">{{ selectedAlarm.alarmLevel || '-' }}</el-descriptions-item>
              <el-descriptions-item label="阈值/实际值">
                {{ formatValue(selectedAlarm.thresholdValue) }} / {{ formatValue(selectedAlarm.actualValue) }}
              </el-descriptions-item>
              <el-descriptions-item label="操作人员">{{ selectedAlarm.operationName || '-' }}</el-descriptions-item>
              <el-descriptions-item label="确认备注">{{ selectedAlarm.confirmRemark || '-' }}</el-descriptions-item>
              <el-descriptions-item label="恢复时间">{{ formatDateTime(selectedAlarm.recoverTime) }}</el-descriptions-item>
              <el-descriptions-item label="异常内容">{{ selectedAlarm.alarmContent || '-' }}</el-descriptions-item>
            </el-descriptions>

            <div class="detail-actions">
              <el-button type="primary" plain :disabled="selectedAlarm.alarmStatus === 0" @click="handleConfirmCurrentAlarm"
                >确认并标记已处理</el-button
              >
              <el-button type="warning" plain @click="handleUpdate(selectedAlarm)">修正告警信息</el-button>
            </div>

            <div class="sop-panel">
              <div class="sop-panel-header">
                <div>
                  <div class="sop-panel-title">命中 SOP</div>
                  <div class="sop-panel-tip">根据当前告警的 `monitorId + cause` 自动命中标准处置步骤，和值班弹窗保持同一口径。</div>
                </div>
                <el-button text type="primary" :disabled="!selectedAlarm" :loading="sopLoading" @click="refreshAlarmActionSteps">刷新 SOP</el-button>
              </div>

              <el-skeleton :loading="sopLoading" animated>
                <template #template>
                  <div v-for="index in 2" :key="index" class="sop-skeleton-row">
                    <el-skeleton-item variant="p" style="width: 100%; height: 68px" />
                  </div>
                </template>
                <template #default>
                  <el-empty v-if="!actionSteps.length" description="当前告警未命中 SOP，请在规则页补充措施步骤" />
                  <div v-else class="sop-list">
                    <article v-for="step in actionSteps" :key="step.objId || step.stepSequence" class="sop-card">
                      <div class="sop-card-sequence">步骤 {{ step.stepSequence || '-' }}</div>
                      <div class="sop-card-desc">{{ step.description || '-' }}</div>
                      <div v-if="step.remark" class="sop-card-remark">{{ step.remark }}</div>
                      <div v-if="step.stepImages?.length" class="sop-card-images">
                        <button
                          v-for="image in step.stepImages"
                          :key="image.objId || image.imageSequence"
                          type="button"
                          class="sop-card-image"
                          @click="previewImage(image.imageUrl)"
                        >
                          <img :src="resolveImageUrl(image.imageUrl)" :alt="image.description || 'SOP 参考图'" />
                          <span>{{ image.description || `图片 ${image.imageSequence || ''}` }}</span>
                        </button>
                      </div>
                    </article>
                  </div>
                </template>
              </el-skeleton>
            </div>
          </template>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="title" v-model="open" width="760px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="点位名称" prop="monitorName">
              <el-input v-model="form.monitorName" placeholder="请输入点位名称" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采集设备名称" prop="collectDeviceName">
              <el-input v-model="form.collectDeviceName" placeholder="请输入采集设备名称" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="记录时间" prop="collectTime">
              <el-date-picker clearable v-model="form.collectTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择记录时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="异常类型" prop="alarmType">
              <el-radio-group v-model="form.alarmType">
                <el-radio v-for="item in dict.type.alarm_type" :key="item.value" :label="Number(item.value)">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="异常状态" prop="alarmStatus">
              <el-radio-group v-model="form.alarmStatus">
                <el-radio v-for="item in dict.type.alarm_status" :key="item.value" :label="Number(item.value)">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="告警级别" prop="alarmLevel">
              <el-input v-model="form.alarmLevel" placeholder="请输入告警级别" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="阈值" prop="thresholdValue">
              <el-input-number v-model="form.thresholdValue" placeholder="请输入阈值" :precision="4" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际值" prop="actualValue">
              <el-input-number v-model="form.actualValue" placeholder="请输入实际值" :precision="4" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="告警标题" prop="alarmTitle">
          <el-input v-model="form.alarmTitle" placeholder="请输入告警标题" />
        </el-form-item>
        <el-form-item label="告警内容" prop="alarmContent">
          <el-input v-model="form.alarmContent" type="textarea" placeholder="请输入告警内容" :rows="3" />
        </el-form-item>
        <el-form-item label="异常数据" prop="alarmData">
          <el-input v-model="form.alarmData" placeholder="请输入异常数据" />
        </el-form-item>
        <el-form-item label="恢复时间" prop="recoverTime">
          <el-date-picker clearable v-model="form.recoverTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择恢复时间" />
        </el-form-item>
        <el-form-item label="确认备注" prop="confirmRemark">
          <el-input v-model="form.confirmRemark" type="textarea" placeholder="请输入确认备注" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="imagePreviewVisible" title="SOP 参考图" width="760px" append-to-body>
      <div class="image-preview-container">
        <img :src="previewImageUrl" alt="SOP 参考图预览" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance } from 'vue';
import { useDict } from '@/utils/dict';
import { parseTime } from '@/utils/ruoyi';
import { getEmsAlarmActionStepsByAlarmInfo } from '@/api/ems/base/emsAlarmActionStep';
import {
  addRecordAlarmData,
  delRecordAlarmData,
  getRecordAlarmDataSummary,
  getRecordAlarmData,
  handleExceptions,
  listRecordAlarmData,
  updateRecordAlarmData
} from '@/api/ems/record/recordAlarmData';
import { useAlarmRealtimeBus } from '@/utils/alarmRealtime';
import type { AlarmOverviewSummaryVO, EmsAlarmActionStepVO, EmsRecordAlarmDataVO } from '@/api/ems/types';

defineOptions({
  name: 'RecordAlarmData',
  dicts: ['alarm_status', 'alarm_type']
} as any);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const dict = reactive({
  type: useDict('alarm_status', 'alarm_type') as any
});

const tableRef = ref();
const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();
const detailRequestToken = ref(0);
const previewImageUrl = ref('');
const imagePreviewVisible = ref(false);

const createQueryParams = () => ({
  pageNum: 1,
  pageSize: 10,
  monitorId: null,
  monitorName: null,
  collectDeviceId: null,
  collectDeviceName: null,
  collectTime: null,
  alarmType: null,
  alarmStatus: null,
  metricCode: null,
  alarmLevel: null,
  thresholdValue: null,
  actualValue: null,
  alarmTitle: null,
  alarmContent: null,
  alarmData: null,
  operationName: null,
  operationTime: null,
  beginOperationTime: null,
  endOperationTime: null,
  recoverTime: null,
  // 推送状态不属于当前标准版告警主链展示范围。
  // pushStatus: null,
  confirmRemark: null,
  cause: null,
  notifyUser: null,
  deviceName: null
});

const createFormData = () => ({
  objId: null,
  monitorId: null,
  monitorName: null,
  collectDeviceId: null,
  collectDeviceName: null,
  collectTime: null,
  alarmType: null,
  alarmStatus: null,
  tenantId: null,
  metricCode: null,
  alarmLevel: null,
  thresholdValue: null,
  actualValue: null,
  alarmTitle: null,
  alarmContent: null,
  alarmData: null,
  operationName: null,
  operationTime: null,
  recoverTime: null,
  // 推送状态与推送次数不再开放前端编辑，避免把扩展通知能力误当成主流程。
  // pushStatus: null,
  // pushCount: null,
  confirmUserId: null,
  confirmRemark: null,
  cause: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  notifyUser: null
});

const createOverviewSummary = (): AlarmOverviewSummaryVO => ({
  totalCount: 0,
  unhandledCount: 0,
  handledCount: 0,
  pushPendingCount: 0,
  pushProcessingCount: 0,
  pushSuccessCount: 0,
  pushFailCount: 0
});

const state = reactive({
  loading: true,
  overviewLoading: false,
  detailLoading: false,
  sopLoading: false,
  ids: [] as Array<number | string>,
  single: true,
  multiple: true,
  showSearch: true,
  total: 0,
  recordAlarmDataList: [] as EmsRecordAlarmDataVO[],
  overviewSummary: createOverviewSummary() as AlarmOverviewSummaryVO,
  selectedAlarm: null as EmsRecordAlarmDataVO | null,
  actionSteps: [] as EmsAlarmActionStepVO[],
  title: '',
  open: false,
  queryParams: createQueryParams() as any,
  form: createFormData() as any,
  rules: {
    objId: [{ required: true, message: '自增标识不能为空', trigger: 'blur' }]
  } as any
});

const {
  loading,
  overviewLoading,
  detailLoading,
  sopLoading,
  ids,
  single,
  multiple,
  showSearch,
  total,
  recordAlarmDataList,
  overviewSummary,
  selectedAlarm,
  actionSteps,
  title,
  open,
  queryParams,
  form,
  rules
} = toRefs(state);

const currentAlarmStatusLabel = computed(() => {
  if (!selectedAlarm.value) {
    return '未选中告警';
  }
  const matched = (dict.type.alarm_status ?? []).find((item) => String(item.value) === String(selectedAlarm.value?.alarmStatus));
  return matched?.label || '状态未知';
});

const formatDateTime = (value?: string | Date | number | null) => {
  if (!value) {
    return '-';
  }
  return parseTime(value, '{y}-{m}-{d} {h}:{i}:{s}');
};

const formatValue = (value?: string | number | null) => {
  if (value === null || value === undefined || value === '') {
    return '-';
  }
  return value;
};

const resolveMonitorName = (row?: EmsRecordAlarmDataVO | null) =>
  row?.monitorName || row?.deviceName || row?.collectDeviceName || row?.monitorId || '-';

const resolveImageUrl = (imageUrl?: string | null) => {
  if (!imageUrl) {
    return '';
  }
  if (/^https?:\/\//.test(imageUrl)) {
    return imageUrl;
  }
  return `${window.location.origin}${imageUrl}`;
};

const previewImage = (imageUrl?: string | null) => {
  if (!imageUrl) {
    return;
  }
  previewImageUrl.value = resolveImageUrl(imageUrl);
  imagePreviewVisible.value = true;
};

const loadAlarmActionSteps = async (row?: EmsRecordAlarmDataVO | null) => {
  if (!row?.monitorId || !row?.cause) {
    actionSteps.value = [];
    return;
  }
  sopLoading.value = true;
  try {
    const response = await getEmsAlarmActionStepsByAlarmInfo(row.monitorId, row.cause);
    actionSteps.value = ((response as any).data ?? []) as EmsAlarmActionStepVO[];
  } catch {
    actionSteps.value = [];
  } finally {
    sopLoading.value = false;
  }
};

const loadAlarmDetail = async (row: EmsRecordAlarmDataVO) => {
  if (!row?.objId) {
    return;
  }

  const requestToken = ++detailRequestToken.value;
  // 先把当前选中行同步到右侧，避免旧请求还没结束时详情面板停留在上一条记录。
  selectedAlarm.value = { ...row } as EmsRecordAlarmDataVO;
  detailLoading.value = true;
  try {
    // 这里仅刷新告警主记录详情，避免页面继续把通知派生数据当成告警主链的一部分。
    const detailRes = await getRecordAlarmData(row.objId);

    if (requestToken !== detailRequestToken.value) {
      return;
    }

    selectedAlarm.value = {
      ...row,
      ...((detailRes as any).data ?? {})
    } as EmsRecordAlarmDataVO;
    await loadAlarmActionSteps(selectedAlarm.value);
  } finally {
    if (requestToken === detailRequestToken.value) {
      detailLoading.value = false;
    }
  }
};

const syncCurrentRow = () => {
  if (!recordAlarmDataList.value.length) {
    detailRequestToken.value++;
    selectedAlarm.value = null;
    return;
  }

  const selectedId = selectedAlarm.value?.objId;
  const targetRow = (selectedId ? recordAlarmDataList.value.find((item) => item.objId === selectedId) : undefined) ?? recordAlarmDataList.value[0];
  if (tableRef.value?.setCurrentRow) {
    tableRef.value.setCurrentRow(targetRow);
  }
  void loadAlarmDetail(targetRow as EmsRecordAlarmDataVO);
};

const getList = async () => {
  loading.value = true;
  overviewLoading.value = true;
  try {
    const [listResult, summaryResult] = await Promise.allSettled([
      listRecordAlarmData(queryParams.value),
      getRecordAlarmDataSummary(queryParams.value)
    ]);

    if (listResult.status !== 'fulfilled') {
      throw listResult.reason;
    }

    const response = listResult.value;
    recordAlarmDataList.value = ((response as any).rows ?? (response as any).data ?? []) as EmsRecordAlarmDataVO[];
    total.value = (response as any).total ?? recordAlarmDataList.value.length ?? 0;

    if (summaryResult.status === 'fulfilled') {
      overviewSummary.value = {
        ...createOverviewSummary(),
        ...(((summaryResult.value as any).data ?? {}) as AlarmOverviewSummaryVO)
      };
    } else {
      overviewSummary.value = createOverviewSummary();
    }

    syncCurrentRow();
  } finally {
    loading.value = false;
    overviewLoading.value = false;
  }
};

const reset = () => {
  // 这里显式重建表单对象，避免弹窗复用时残留上一次的确认信息。
  form.value = createFormData();
  actionSteps.value = [];
  formRef.value?.resetFields();
};

const cancel = () => {
  open.value = false;
  reset();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: EmsRecordAlarmDataVO[]) => {
  ids.value = selection.map((item) => item.objId as string | number);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleRowClick = async (row: EmsRecordAlarmDataVO) => {
  tableRef.value?.setCurrentRow?.(row);
  await loadAlarmDetail(row);
};

const refreshCurrentAlarm = async () => {
  if (!selectedAlarm.value?.objId) {
    return;
  }
  const matched = recordAlarmDataList.value.find((item) => item.objId === selectedAlarm.value?.objId);
  if (matched) {
    await loadAlarmDetail(matched);
  }
};

const refreshAlarmActionSteps = async () => {
  await loadAlarmActionSteps(selectedAlarm.value);
};

const handleConfirmCurrentAlarm = async () => {
  if (!selectedAlarm.value?.objId) {
    return;
  }
  await proxy?.$modal.confirm(`是否确认将告警“${selectedAlarm.value.alarmTitle || resolveMonitorName(selectedAlarm.value)}”标记为已处理？`);
  const response = await handleExceptions(selectedAlarm.value.objId as any);
  const result = ((response as any).data ?? {}) as any;
  const updatedCount = Number(result.updatedCount ?? 0);
  const alreadyHandledCount = Number(result.alreadyHandledCount ?? 0);
  if (updatedCount <= 0 && alreadyHandledCount <= 0) {
    proxy?.$modal.msgWarning((response as any).msg || '告警状态未更新，请刷新后重试');
    return;
  }
  proxy?.$modal.msgSuccess(updatedCount > 0 ? '确认处理成功' : '告警已是已处理状态');
  await getList();
};

const handleUpdate = async (row?: EmsRecordAlarmDataVO) => {
  reset();
  const objId = row?.objId || ids.value[0];
  if (!objId) {
    return;
  }
  const response = await getRecordAlarmData(objId as any);
  // 这里合并默认对象，是为了避免以后后端新增字段时，旧表单把未展示字段清空。
  form.value = {
    ...createFormData(),
    ...((response as any).data ?? {})
  };
  open.value = true;
  title.value = '修改异常数据记录';
};

const submitForm = async () => {
  const valid = await formRef.value?.validate().catch(() => false);
  if (!valid) {
    return;
  }
  if (form.value.objId != null) {
    await updateRecordAlarmData(form.value);
    proxy?.$modal.msgSuccess('修改成功');
  } else {
    await addRecordAlarmData(form.value);
    proxy?.$modal.msgSuccess('新增成功');
  }
  open.value = false;
  await getList();
};

const handleDelete = async (row?: EmsRecordAlarmDataVO) => {
  const objIds = row?.objId || ids.value;
  await proxy?.$modal.confirm(`是否确认删除异常数据记录编号为"${objIds}"的数据项？`);
  await delRecordAlarmData(objIds as any);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

const handleExport = () => {
  proxy?.download(
    'ems/record/recordAlarmData/export',
    {
      ...queryParams.value
    },
    `recordAlarmData_${new Date().getTime()}.xlsx`
  );
};

let stopRealtimeBus: (() => void) | undefined;

onMounted(() => {
  getList();
  stopRealtimeBus = useAlarmRealtimeBus().on(() => {
    void getList();
  });
});

onUnmounted(() => {
  stopRealtimeBus?.();
});
</script>

<style scoped>
.hero-card {
  background:
    linear-gradient(135deg, rgba(93, 25, 31, 0.97), rgba(140, 47, 32, 0.92)), linear-gradient(45deg, rgba(255, 191, 126, 0.16), transparent 42%);
  border: none;
  border-radius: 22px;
  color: #fff4ea;
  margin-bottom: 12px;
  overflow: hidden;
}

.hero-grid {
  display: grid;
  grid-template-columns: minmax(0, 2fr) minmax(280px, 0.95fr);
  gap: 18px;
}

.hero-kicker {
  color: rgba(255, 230, 214, 0.76);
  font-size: 12px;
  letter-spacing: 0.22em;
  margin-bottom: 10px;
}

.hero-title {
  font-size: 30px;
  font-weight: 700;
  line-height: 1.15;
}

.hero-desc {
  color: rgba(255, 236, 223, 0.88);
  font-size: 14px;
  line-height: 1.8;
  margin-top: 12px;
}

.hero-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 18px;
}

.hero-tag {
  border-radius: 999px;
}

.hero-side {
  display: flex;
  align-items: stretch;
}

.hero-panel {
  width: 100%;
  background: linear-gradient(180deg, rgba(255, 245, 237, 0.14), rgba(255, 245, 237, 0.06));
  border: 1px solid rgba(255, 226, 207, 0.16);
  border-radius: 18px;
  padding: 20px 22px;
}

.hero-panel-label {
  color: rgba(255, 229, 212, 0.72);
  font-size: 12px;
  letter-spacing: 0.14em;
  text-transform: uppercase;
}

.hero-panel-value {
  font-size: 22px;
  font-weight: 600;
  line-height: 1.4;
  margin-top: 12px;
}

.hero-panel-foot {
  color: rgba(255, 232, 218, 0.8);
  font-size: 13px;
  line-height: 1.7;
  margin-top: 10px;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 12px;
  margin-bottom: 12px;
}

.summary-card {
  border-radius: 18px;
  border: 1px solid rgba(173, 88, 55, 0.1);
  box-shadow: 0 14px 28px rgba(84, 30, 25, 0.05);
}

.summary-label {
  color: #86695c;
  font-size: 13px;
  margin-bottom: 8px;
}

.summary-value {
  color: #6c2725;
  font-size: 28px;
  font-weight: 700;
  line-height: 1.1;
}

.summary-foot {
  color: #9d8a82;
  font-size: 12px;
  margin-top: 10px;
}

.main-cell {
  line-height: 20px;
  font-weight: 600;
}

.sub-cell {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 18px;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.detail-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.sop-panel {
  border-top: 1px solid var(--el-border-color-lighter);
  padding-top: 16px;
}

.sop-panel-header {
  align-items: center;
  display: flex;
  gap: 12px;
  justify-content: space-between;
  margin-bottom: 12px;
}

.sop-panel-title {
  font-size: 16px;
  font-weight: 600;
}

.sop-panel-tip {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  line-height: 1.7;
  margin-top: 4px;
}

.sop-skeleton-row + .sop-skeleton-row {
  margin-top: 10px;
}

.sop-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.sop-card {
  background: linear-gradient(180deg, rgba(250, 245, 240, 0.9), rgba(255, 251, 248, 0.96));
  border: 1px solid rgba(196, 157, 140, 0.18);
  border-radius: 16px;
  padding: 14px 16px;
}

.sop-card-sequence {
  color: #8d5a47;
  font-size: 12px;
  letter-spacing: 0.12em;
}

.sop-card-desc {
  font-size: 15px;
  font-weight: 600;
  line-height: 1.7;
  margin-top: 8px;
}

.sop-card-remark {
  color: var(--el-text-color-secondary);
  font-size: 13px;
  line-height: 1.7;
  margin-top: 8px;
}

.sop-card-images {
  display: grid;
  gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(132px, 1fr));
  margin-top: 12px;
}

.sop-card-image {
  background: #fff;
  border: 1px solid rgba(196, 157, 140, 0.22);
  border-radius: 12px;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
  text-align: left;
}

.sop-card-image img {
  border-radius: 8px;
  height: 96px;
  object-fit: cover;
  width: 100%;
}

.sop-card-image span {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 1.5;
}

.image-preview-container {
  align-items: center;
  display: flex;
  justify-content: center;
  min-height: 320px;
}

.image-preview-container img {
  max-height: 70vh;
  max-width: 100%;
}

@media (max-width: 1200px) {
  .hero-grid,
  .summary-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (max-width: 768px) {
  .hero-grid,
  .summary-grid {
    grid-template-columns: repeat(1, minmax(0, 1fr));
  }

  .detail-actions {
    flex-direction: column;
  }
}
</style>
