<template>
  <div class="app-container">
    <el-form ref="queryFormRef" :model="queryParams" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <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="collectDeviceId">-->
      <!--        <el-input-->
      <!--          v-model="queryParams.collectDeviceId"-->
      <!--          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-date-picker>
      </el-form-item>
      <el-form-item label="异常类型" prop="alarmType">
        <el-select v-model="queryParams.alarmType" placeholder="请选择异常类型" clearable>
          <el-option v-for="dict in dict.type.alarm_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="异常状态" prop="alarmStatus">
        <el-select v-model="queryParams.alarmStatus" placeholder="请选择异常状态" clearable>
          <el-option v-for="dict in dict.type.alarm_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="操作时间" prop="operationTime">-->
      <!--        <el-date-picker clearable-->
      <!--                        v-model="queryParams.operationTime"-->
      <!--                        type="date"-->
      <!--                        value-format="yyyy-MM-dd"-->
      <!--                        placeholder="请选择操作时间"-->
      <!--        >-->
      <!--        </el-date-picker>-->
      <!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['ems/record:recordAlarmData:add']"-->
      <!--        >新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['ems/record:recordAlarmData:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['ems/record:recordAlarmData:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['ems/record:recordAlarmData:export']"
          >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @query-table="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordAlarmDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="自增标识" align="center" prop="objId" v-if="columns[0].visible" />
      <el-table-column label="计量设备名称" align="center" prop="monitorName" v-if="columns[1].visible" />
      <!-- <el-table-column label="采集设备名称" align="center" prop="collectDeviceName" v-if="columns[2].visible"/> -->
      <el-table-column label="记录时间" align="center" prop="collectTime" width="180" v-if="columns[2].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.collectTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="异常类型" align="center" prop="alarmType" v-if="columns[3].visible">
        <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" v-if="columns[4].visible">
        <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" v-if="columns[5].visible" />
      <el-table-column label="阈值" align="center" prop="thresholdValue" v-if="columns[6].visible" />
      <el-table-column label="实际值" align="center" prop="actualValue" v-if="columns[7].visible" />
      <el-table-column label="告警标题" align="center" prop="alarmTitle" v-if="columns[8].visible" show-overflow-tooltip />
      <el-table-column label="告警内容" align="center" prop="alarmContent" v-if="columns[9].visible" show-overflow-tooltip />
      <el-table-column label="异常数据" align="center" prop="alarmData" v-if="columns[10].visible" />
      <el-table-column label="操作人员" align="center" prop="operationName" v-if="columns[11].visible" />
      <el-table-column label="操作时间" align="center" prop="operationTime" width="180" v-if="columns[12].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.operationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="恢复时间" align="center" prop="recoverTime" width="180" v-if="columns[13].visible">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recoverTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="确认备注" align="center" prop="confirmRemark" v-if="columns[14].visible" show-overflow-tooltip />
      <el-table-column label="备注" align="center" prop="cause" v-if="columns[15].visible" />
      <!-- <el-table-column label="通知用户" align="center" prop="notifyUser" v-if="columns[14].visible"/> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/record:recordAlarmData:edit']"
            >修改
          </el-button>
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="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-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="计量设备名称" prop="monitorName">
          <el-input v-model="form.monitorName" placeholder="请输入计量设备名称" readonly />
        </el-form-item>
        <el-form-item label="采集设备名称" prop="collectDeviceName">
          <el-input v-model="form.collectDeviceName" placeholder="请输入采集设备名称" readonly />
        </el-form-item>
        <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-date-picker>
        </el-form-item>
        <el-form-item label="异常类型" prop="alarmType">
          <el-radio-group v-model="form.alarmType">
            <el-radio v-for="dict in dict.type.alarm_type" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }} </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="异常状态" prop="alarmStatus">
          <el-radio-group v-model="form.alarmStatus">
            <el-radio v-for="dict in dict.type.alarm_status" :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }} </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="告警级别" prop="alarmLevel">
          <el-input v-model="form.alarmLevel" placeholder="请输入告警级别" />
        </el-form-item>
        <el-form-item label="阈值" prop="thresholdValue">
          <el-input-number v-model="form.thresholdValue" placeholder="请输入阈值" :precision="4" />
        </el-form-item>
        <el-form-item label="实际值" prop="actualValue">
          <el-input-number v-model="form.actualValue" placeholder="请输入实际值" :precision="4" />
        </el-form-item>
        <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="请输入告警内容" />
        </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-date-picker>
        </el-form-item>
        <el-form-item label="确认备注" prop="confirmRemark">
          <el-input v-model="form.confirmRemark" type="textarea" placeholder="请输入确认备注" />
        </el-form-item>
        <!--        <el-form-item label="操作人员" prop="operationName">-->
        <!--          <el-input v-model="form.operationName" placeholder="请输入操作人员"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="操作时间" prop="operationTime">-->
        <!--          <el-date-picker clearable-->
        <!--                          v-model="form.operationTime"-->
        <!--                          type="date"-->
        <!--                          value-format="yyyy-MM-dd"-->
        <!--                          placeholder="请选择操作时间"-->
        <!--          >-->
        <!--          </el-date-picker>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备注" prop="cause">-->
        <!--          <el-input v-model="form.cause" placeholder="请输入备注"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="通知用户" prop="notifyUser">-->
        <!--          <el-input v-model="form.notifyUser" placeholder="请输入通知用户"/>-->
        <!--        </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>
  </div>
</template>

<script setup lang="ts">
import { useDict } from '@/utils/dict';
import { parseTime } from '@/utils/ruoyi';
import {
  addRecordAlarmData,
  delRecordAlarmData,
  getRecordAlarmData,
  listRecordAlarmData,
  updateRecordAlarmData
} from '@/api/ems/record/recordAlarmData';

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

const { proxy } = getCurrentInstance() as any;

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

const queryFormRef = ref<any>();
const formRef = ref<any>();

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 state = reactive({
  loading: true,
  ids: [] as Array<number | string>,
  single: true,
  multiple: true,
  showSearch: true,
  total: 0,
  recordAlarmDataList: [] as any[],
  title: '',
  open: false,
  // 技术字段保留在查询对象里，便于导出和后端扩展过滤，但页面上不直接渲染这些字段。
  queryParams: createQueryParams() as any,
  form: createFormData() as any,
  rules: {
    objId: [{ required: true, message: '自增标识不能为空', trigger: 'blur' }]
  } as any,
  columns: [
    { key: 0, label: '自增标识', visible: false },
    { key: 1, label: '计量设备名称', visible: true },
    { key: 2, label: '记录时间', visible: true },
    { key: 3, label: '异常类型', visible: true },
    { key: 4, label: '异常状态', visible: true },
    { key: 5, label: '告警级别', visible: true },
    { key: 6, label: '阈值', visible: true },
    { key: 7, label: '实际值', visible: true },
    { key: 8, label: '告警标题', visible: true },
    { key: 9, label: '告警内容', visible: true },
    { key: 10, label: '异常数据', visible: true },
    { key: 11, label: '操作人员', visible: true },
    { key: 12, label: '操作时间', visible: true },
    { key: 13, label: '恢复时间', visible: true },
    { key: 14, label: '确认备注', visible: true },
    { key: 15, label: '备注', visible: false },
    { key: 16, label: '创建人', visible: false },
    { key: 17, label: '创建时间', visible: true },
    { key: 18, label: '更新人', visible: false },
    { key: 19, label: '更新时间', visible: false }
  ] as any[]
});

const { loading, ids, single, multiple, showSearch, total, recordAlarmDataList, title, open, queryParams, form, rules, columns } = toRefs(state);

const getList = async () => {
  loading.value = true;
  const response = await listRecordAlarmData(queryParams.value);
  recordAlarmDataList.value = response.rows ?? response.data ?? [];
  total.value = response.total ?? 0;
  loading.value = false;
};

const reset = () => {
  // 这里显式重建表单对象，避免沿用旧引用导致弹窗残留上次编辑值。
  form.value = createFormData();
  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: any[]) => {
  ids.value = selection.map((item) => item.objId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加异常数据记录';
};

const handleUpdate = async (row?: any) => {
  reset();
  const objId = row?.objId || ids.value;
  const response = await getRecordAlarmData(objId);
  // 详情回填时合并默认对象，避免后端后续补字段后旧页面把隐藏字段重新置丢。
  form.value = {
    ...createFormData(),
    ...(response.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?: any) => {
  const objIds = row?.objId || ids.value;
  await proxy?.$modal.confirm(`是否确认删除异常数据记录编号为"${objIds}"的数据项？`);
  await delRecordAlarmData(objIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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

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