<template>
  <div class="p-2">
    <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">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="82px">
            <el-form-item label="告警标题" prop="alarmTitle">
              <el-input v-model="queryParams.alarmTitle" placeholder="请输入告警标题" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <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="channelType">
              <el-select v-model="queryParams.channelType" placeholder="请选择推送渠道" clearable style="width: 160px">
                <el-option v-for="item in channelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="推送状态" prop="pushStatus">
              <el-select v-model="queryParams.pushStatus" placeholder="请选择推送状态" clearable style="width: 160px">
                <el-option v-for="item in pushStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="推送目标" prop="targetValue">
              <el-input v-model="queryParams.targetValue" placeholder="请输入推送目标" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="推送时间" prop="pushTime">
              <el-date-picker clearable v-model="queryParams.pushTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择推送时间" />
            </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>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ems/base:alarmPushLog:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['ems/base:alarmPushLog:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['ems/base:alarmPushLog:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/base:alarmPushLog:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="alarmPushLogList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="columns[0].visible" label="序号" type="index" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="告警标题" align="center" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.alarmTitle || '-' }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[2].visible" label="点位名称" align="center" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.monitorName || scope.row.monitorCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="推送渠道" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="channelTypeOptions" :value="scope.row.channelType" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[4].visible" label="推送目标" align="center" prop="targetValue" min-width="160" show-overflow-tooltip />
        <el-table-column v-if="columns[5].visible" label="告警级别" align="center" prop="alarmLevel" width="110" />
        <el-table-column v-if="columns[6].visible" label="推送状态" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="pushStatusOptions" :value="scope.row.pushStatus" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[7].visible" label="响应信息" align="center" prop="responseMsg" min-width="220" show-overflow-tooltip />
        <el-table-column v-if="columns[8].visible" label="推送时间" align="center" prop="pushTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.pushTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="110" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:alarmPushLog:edit']" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:alarmPushLog:remove']" />
            </el-tooltip>
          </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-dialog :title="dialog.title" v-model="dialog.visible" width="720px" append-to-body>
      <el-form ref="alarmPushLogFormRef" :model="form" :rules="rules" label-width="96px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="关联告警" prop="alarmObjId">
              <el-select v-model="form.alarmObjId" placeholder="请选择关联告警" filterable style="width: 100%" @change="handleAlarmChange">
                <el-option v-for="item in alarmOptions" :key="item.objId" :label="buildAlarmOptionLabel(item)" :value="item.objId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="告警级别">
              <el-input v-model="form.alarmLevel" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="推送渠道" prop="channelType">
              <el-select v-model="form.channelType" placeholder="请选择推送渠道" style="width: 100%">
                <el-option v-for="item in channelTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推送状态" prop="pushStatus">
              <el-select v-model="form.pushStatus" placeholder="请选择推送状态" style="width: 100%">
                <el-option v-for="item in pushStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="推送目标" prop="targetValue">
          <el-input v-model="form.targetValue" placeholder="请输入推送目标，如手机号、邮箱或 Webhook 地址" />
        </el-form-item>

        <el-form-item label="推送内容" prop="pushContent">
          <editor v-model="form.pushContent" :min-height="192" />
        </el-form-item>

        <el-form-item label="响应信息" prop="responseMsg">
          <el-input v-model="form.responseMsg" type="textarea" :rows="3" placeholder="请输入响应信息" />
        </el-form-item>

        <el-form-item label="推送时间" prop="pushTime">
          <el-date-picker clearable v-model="form.pushTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择推送时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AlarmPushLog" lang="ts">
import { listAlarmPushLog, getAlarmPushLog, delAlarmPushLog, addAlarmPushLog, updateAlarmPushLog } from '@/api/ems/base/alarmPushLog';
import { listRecordAlarmData } from '@/api/ems/record/recordAlarmData';
import type { AlarmPushLogVO, AlarmPushLogQuery, AlarmPushLogForm } from '@/api/ems/base/alarmPushLog/types';
import type { EmsRecordAlarmDataVO } from '@/api/ems/types';
import { parseTime } from '@/utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const channelTypeOptions = [
  { label: '站内消息', value: 'SITE' },
  { label: '短信', value: 'SMS' },
  { label: '邮件', value: 'EMAIL' },
  { label: 'Webhook', value: 'WEBHOOK' }
];

const pushStatusOptions = [
  { label: '待推送', value: 'PENDING' },
  { label: '推送中', value: 'PROCESSING' },
  { label: '推送成功', value: 'SUCCESS' },
  { label: '推送失败', value: 'FAIL' }
];

const alarmOptions = ref<EmsRecordAlarmDataVO[]>([]);
const alarmPushLogList = ref<AlarmPushLogVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '告警标题', visible: true, children: [] },
  { key: 2, label: '点位名称', visible: true, children: [] },
  { key: 3, label: '推送渠道', visible: true, children: [] },
  { key: 4, label: '推送目标', visible: true, children: [] },
  { key: 5, label: '告警级别', visible: true, children: [] },
  { key: 6, label: '推送状态', visible: true, children: [] },
  { key: 7, label: '响应信息', visible: true, children: [] },
  { key: 8, label: '推送时间', visible: true, children: [] }
]);

const queryFormRef = ref<ElFormInstance>();
const alarmPushLogFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const createFormData = (): AlarmPushLogForm => ({
  id: undefined,
  alarmObjId: undefined,
  alarmTitle: undefined,
  monitorCode: undefined,
  monitorName: undefined,
  channelType: 'SITE',
  targetValue: undefined,
  alarmLevel: undefined,
  pushContent: undefined,
  pushStatus: 'PENDING',
  responseMsg: undefined,
  pushTime: undefined
});

const data = reactive<PageData<AlarmPushLogForm, AlarmPushLogQuery>>({
  form: createFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    alarmTitle: undefined,
    monitorName: undefined,
    channelType: undefined,
    targetValue: undefined,
    pushStatus: undefined,
    pushTime: undefined,
    params: {}
  },
  rules: {
    alarmObjId: [{ required: true, message: '关联告警不能为空', trigger: 'change' }],
    channelType: [{ required: true, message: '推送渠道不能为空', trigger: 'change' }],
    targetValue: [{ required: true, message: '推送目标不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const buildAlarmOptionLabel = (item: EmsRecordAlarmDataVO) =>
  `${item.alarmTitle || '未命名告警'} / ${item.monitorName || item.monitorId || '-'} / ${parseTime(item.collectTime, '{y}-{m}-{d} {h}:{i}:{s}') || '-'}`;

const syncAlarmSnapshot = (alarmObjId?: string | number) => {
  const selectedAlarm = alarmOptions.value.find((item) => item.objId === alarmObjId);
  // 推送日志本质是告警记录的派生数据，页面只让用户选业务告警对象，技术主键和关联名称由前端同步回填。
  form.value.alarmTitle = selectedAlarm?.alarmTitle;
  form.value.monitorCode = selectedAlarm?.monitorId;
  form.value.monitorName = selectedAlarm?.monitorName;
  form.value.alarmLevel = selectedAlarm?.alarmLevel;
};

const loadAlarmOptions = async () => {
  // 这里优先直接拿较大的业务列表做下拉；如果后续告警量继续扩大，再演进成弹窗分页选择器。
  const response = await listRecordAlarmData({
    pageNum: 1,
    pageSize: 1000
  } as any);
  alarmOptions.value = (((response as any).rows ?? (response as any).data ?? []) as EmsRecordAlarmDataVO[]) || [];
};

const getList = async () => {
  loading.value = true;
  try {
    const res = await listAlarmPushLog(queryParams.value);
    alarmPushLogList.value = ((res as any).rows ?? []) as AlarmPushLogVO[];
    total.value = Number((res as any).total ?? 0);
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = createFormData();
  alarmPushLogFormRef.value?.resetFields();
};

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

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

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

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加报警推送日志';
};

const handleUpdate = async (row?: AlarmPushLogVO) => {
  reset();
  const targetId = row?.id ?? ids.value[0];
  if (!targetId) {
    return;
  }
  const res = await getAlarmPushLog(targetId);
  form.value = {
    ...createFormData(),
    ...((res as any).data ?? {})
  };
  dialog.visible = true;
  dialog.title = '修改报警推送日志';
};

const handleAlarmChange = (alarmObjId?: string | number) => {
  syncAlarmSnapshot(alarmObjId);
};

const submitForm = () => {
  alarmPushLogFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      syncAlarmSnapshot(form.value.alarmObjId);
      if (form.value.id) {
        await updateAlarmPushLog(form.value);
      } else {
        await addAlarmPushLog(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: AlarmPushLogVO) => {
  const targetIds = row?.id ?? ids.value;
  await proxy?.$modal.confirm(`是否确认删除报警推送日志编号为"${targetIds}"的数据项？`);
  await delAlarmPushLog(targetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

onMounted(async () => {
  await loadAlarmOptions();
  await getList();
});
</script>
