<template>
  <div class="p-2 alarm-info-page">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>报警信息</span>
          <el-button link type="primary" icon="Refresh" @click="loadList">刷新</el-button>
        </div>
      </template>
      <el-form :inline="true" class="query-form">
        <el-form-item label="报警设备类型">
          <el-select v-model="query.deviceType" placeholder="请选择设备类型" clearable class="device-type-select" @change="loadList">
            <el-option v-for="dict in device_type" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="loadList">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" border :data="alarmList" height="680">
        <el-table-column label="报警设备" prop="alarmDeviceName" min-width="150" />
        <el-table-column label="报警位置" prop="alarmPosition" min-width="220" show-overflow-tooltip />
        <el-table-column label="报警时间" prop="alarmTime" min-width="160" />
        <el-table-column label="报警等级" prop="alarmLevel" width="100" />
        <el-table-column label="报警类型" min-width="130">
          <template #default="scope">{{ formatAlarmType(scope.row.alarmType) }}</template>
        </el-table-column>
        <el-table-column label="报警信息" prop="alarmDetail" min-width="280" show-overflow-tooltip />
        <el-table-column label="处理状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.handleTime ? 'success' : 'danger'">{{ scope.row.handleTime ? '已处理' : '未处理' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" prop="handleTime" min-width="160" />
        <el-table-column label="处理人" prop="handler" width="110" />
        <el-table-column fixed="right" label="操作" align="center" width="90">
          <template #default="scope">
            <el-button v-if="!scope.row.handleTime" link type="primary" icon="Check" @click="openHandleDialog(scope.row)">处理</el-button>
            <span v-else>已处理</span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="handleDialog.visible" title="处理报警" append-to-body width="520px">
      <el-form ref="handleFormRef" :model="handleForm" :rules="handleRules" label-width="90px">
        <el-form-item label="报警设备">
          <el-input :model-value="currentAlarm?.alarmDeviceName" disabled />
        </el-form-item>
        <el-form-item label="报警信息">
          <el-input :model-value="currentAlarm?.alarmDetail" type="textarea" disabled />
        </el-form-item>
        <el-form-item label="处理人" prop="handler">
          <el-input v-model="handleForm.handler" placeholder="请输入处理人" />
        </el-form-item>
        <el-form-item label="处理信息" prop="handleInfo">
          <el-input v-model="handleForm.handleInfo" type="textarea" :rows="4" placeholder="请输入处理信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitHandle">确 定</el-button>
          <el-button @click="handleDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="AlarmInfo" lang="ts">
import { handleAlarmDetail, listAlarmDetail } from '@/api/ems/alarmRule';
import { AlarmDetailVO } from '@/api/ems/alarmRule/types';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userStore = useUserStore();
const { device_type } = toRefs<any>(proxy?.useDict('device_type'));

const alarmTypeOptions = [
  { label: '阈值报警', value: '1' },
  { label: '多级阈值报警', value: '2' },
  { label: '持续时间报警', value: '3' },
  { label: '变化率报警', value: '4' },
  { label: '停机报警', value: '5' }
];
const alarmTypeMap = Object.fromEntries(alarmTypeOptions.map((item) => [item.value, item.label]));
const formatAlarmType = (value?: string | number) => alarmTypeMap[String(value || '')] || String(value || '');

const alarmList = ref<AlarmDetailVO[]>([]);
const loading = ref(false);
const currentAlarm = ref<AlarmDetailVO>();
const handleFormRef = ref<ElFormInstance>();
const handleDialog = reactive<DialogOption>({ visible: false, title: '' });
const handleForm = reactive({
  handler: '',
  handleInfo: ''
});
const query = reactive({
  deviceType: undefined as string | number | undefined
});
const handleRules = {
  handler: [{ required: true, message: '处理人不能为空', trigger: 'blur' }],
  handleInfo: [{ required: true, message: '处理信息不能为空', trigger: 'blur' }]
};

const loadList = async () => {
  loading.value = true;
  try {
    const [todayRes, unhandledRes] = await Promise.all([
      listAlarmDetail({ pageNum: 1, pageSize: 1000, today: '1', deviceType: query.deviceType }),
      listAlarmDetail({ pageNum: 1, pageSize: 1000, unhandled: '1', deviceType: query.deviceType })
    ]);
    const map = new Map<string | number, AlarmDetailVO>();
    [...(todayRes.rows || []), ...(unhandledRes.rows || [])].forEach((item) => {
      map.set(item.id, item);
    });
    alarmList.value = [...map.values()].sort((left, right) => String(right.alarmTime || '').localeCompare(String(left.alarmTime || '')));
  } finally {
    loading.value = false;
  }
};

const resetQuery = () => {
  query.deviceType = undefined;
  loadList();
};

const openHandleDialog = (row: AlarmDetailVO) => {
  currentAlarm.value = row;
  handleForm.handler = userStore.nickname || userStore.name || '';
  handleForm.handleInfo = '';
  handleDialog.visible = true;
  nextTick(() => handleFormRef.value?.clearValidate());
};

const submitHandle = () => {
  handleFormRef.value?.validate(async (valid: boolean) => {
    if (!valid || !currentAlarm.value?.id) return;
    await proxy?.$modal.confirm('是否确认处理当前报警？');
    await handleAlarmDetail({
      id: currentAlarm.value.id,
      handler: handleForm.handler,
      handleInfo: handleForm.handleInfo
    });
    proxy?.$modal.msgSuccess('处理成功');
    handleDialog.visible = false;
    await loadList();
  });
};

onMounted(() => {
  loadList();
});
</script>

<style scoped>
.alarm-info-page {
  min-height: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.query-form {
  margin-bottom: 12px;
}

.device-type-select {
  width: 180px;
}
</style>
