<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)" prop="ruleObjId">
        <el-input
          v-model="queryParams.ruleObjId"
          placeholder="请输入关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="步骤顺序，从1开始" prop="stepSequence">
        <el-input v-model="queryParams.stepSequence" placeholder="请输入步骤顺序，从1开始" clearable @keyup.enter="handleQuery" />
      </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/base:emsAlarmActionStep: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/base:emsAlarmActionStep: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/base:emsAlarmActionStep: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/base:emsAlarmActionStep:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="emsAlarmActionStepList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="objId" />
      <el-table-column label="关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)" align="center" prop="ruleObjId"> </el-table-column>
      <el-table-column label="步骤顺序，从1开始" align="center" prop="stepSequence"> </el-table-column>
      <el-table-column label="步骤文字描述" align="center" prop="description"> </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"> </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:emsAlarmActionStep:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ems/base:emsAlarmActionStep: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="80px">
        <el-form-item label="关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)" prop="ruleObjId">
          <!-- <el-input v-model="form.ruleObjId" placeholder="请输入关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)" /> -->
          <el-select v-model="form.ruleObjId" placeholder="请选择关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)">
            <el-option v-for="item in recordAlarmRuleList" :key="item.objId" :label="item.ruleName" :value="item.objId" />
          </el-select>
        </el-form-item>
        <el-form-item label="步骤顺序，从1开始" prop="stepSequence">
          <el-input v-model="form.stepSequence" placeholder="请输入步骤顺序，从1开始" />
        </el-form-item>
        <el-form-item label="步骤文字描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" 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 {
  listEmsAlarmActionStep,
  getEmsAlarmActionStep,
  delEmsAlarmActionStep,
  addEmsAlarmActionStep,
  updateEmsAlarmActionStep
} from '@/api/ems/base/emsAlarmActionStep';
import { getEmsRecordAlarmRuleList } from '@/api/ems/record/recordAlarmRule';

defineOptions({
  name: 'EmsAlarmActionStep'
} as any);

const { proxy } = getCurrentInstance() as any;

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

// 这里统一通过工厂函数重建表单，避免弹窗在新增/编辑切换时残留上一条业务数据。
const createFormData = () => ({
  objId: null,
  ruleObjId: null,
  stepSequence: null,
  description: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null
});

// 这里保留原页面字段结构，优先保证 EMS 业务行为与接口入参不发生漂移。
const state = reactive({
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 报警规则列表
  recordAlarmRuleList: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 报警规则具体措施步骤表格数据
  emsAlarmActionStepList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleObjId: null,
    stepSequence: null,
    description: null
  },
  // 表单参数
  form: createFormData(),
  // 表单校验
  rules: {
    ruleObjId: [
      {
        required: true,
        message: '关联的报警规则ID (逻辑关联 ems_record_alarm_rule.obj_id)不能为空',
        trigger: 'blur'
      }
    ],
    stepSequence: [
      {
        required: true,
        message: '步骤顺序，从1开始不能为空',
        trigger: 'blur'
      }
    ]
  }
} as any);

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

const getList = () => {
  loading.value = true;
  listEmsAlarmActionStep(queryParams.value).then((response) => {
    emsAlarmActionStepList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

const getRecordAlarmRuleList = () => {
  getEmsRecordAlarmRuleList().then((response) => {
    recordAlarmRuleList.value = response.data;
  });
};

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

const reset = () => {
  form.value = {
    objId: null,
    ruleObjId: null,
    stepSequence: null,
    description: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  formRef.value?.resetFields();
};

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

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

const handleSelectionChange = (selection) => {
  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 = (row) => {
  reset();
  const objId = row.objId || ids.value;
  getEmsAlarmActionStep(objId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = '修改报警规则具体措施步骤';
  });
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.value.objId != null) {
        updateEmsAlarmActionStep(form.value).then((response) => {
          proxy?.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        addEmsAlarmActionStep(form.value).then((response) => {
          proxy?.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
};

const handleDelete = (row) => {
  const objIds = row.objId || ids.value;
  proxy?.$modal
    .confirm('是否确认删除报警规则具体措施步骤编号为"' + objIds + '"的数据项？')
    .then(function () {
      return delEmsAlarmActionStep(objIds);
    })
    .then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

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

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