<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="关联规则" prop="ruleObjId">
        <el-select v-model="queryParams.ruleObjId" placeholder="请选择关联规则" clearable filterable style="width: 260px">
          <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="步骤顺序" prop="stepSequence">
        <el-input-number v-model="queryParams.stepSequence" :min="1" :precision="0" controls-position="right" style="width: 180px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @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="small" @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="small" :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="small"
          :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="small" @click="handleExport" v-hasPermi="['ems/base:emsAlarmActionStep:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:show-search="showSearch" :columns="columns" @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 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="220" show-overflow-tooltip>
        <template #default="scope">
          {{ resolveRuleName(scope.row.ruleObjId) }}
        </template>
      </el-table-column>
      <el-table-column v-if="columns[2].visible" label="步骤顺序" align="center" prop="stepSequence" width="120" />
      <el-table-column v-if="columns[3].visible" label="步骤描述" align="center" prop="description" min-width="260" show-overflow-tooltip />
      <el-table-column v-if="columns[4].visible" label="备注" align="center" prop="remark" min-width="220" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template #default="scope">
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:emsAlarmActionStep:edit']">修改</el-button>
          <el-button size="small" 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="560px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="关联规则" prop="ruleObjId">
          <el-select v-model="form.ruleObjId" placeholder="请选择关联规则" filterable style="width: 100%">
            <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="步骤顺序" prop="stepSequence">
          <el-input-number v-model="form.stepSequence" :min="1" :precision="0" controls-position="right" style="width: 100%" />
        </el-form-item>
        <el-form-item label="步骤描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请输入步骤描述" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" 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';
import type { EmsAlarmActionStepVO, EmsRecordAlarmRuleVO } from '@/api/ems/types';

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

const { proxy } = getCurrentInstance() as any;

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

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: [] }
]);

const createFormData = () => ({
  objId: null,
  ruleObjId: null,
  stepSequence: 1,
  description: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null
});

const state = reactive({
  loading: true,
  ids: [],
  recordAlarmRuleList: [] as EmsRecordAlarmRuleVO[],
  single: true,
  multiple: true,
  showSearch: true,
  total: 0,
  emsAlarmActionStepList: [] as EmsAlarmActionStepVO[],
  title: '',
  open: false,
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleObjId: null,
    stepSequence: null,
    description: null
  },
  form: createFormData(),
  rules: {
    ruleObjId: [{ required: true, message: '关联规则不能为空', trigger: 'change' }],
    stepSequence: [{ required: true, message: '步骤顺序不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '步骤描述不能为空', trigger: 'blur' }]
  }
} as any);

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

const resolveRuleName = (ruleObjId?: string | number) =>
  recordAlarmRuleList.value.find((item) => item.objId === ruleObjId)?.ruleName || (ruleObjId ? String(ruleObjId) : '-');

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

const loadRuleOptions = () => {
  getEmsRecordAlarmRuleList().then((response) => {
    recordAlarmRuleList.value = (response.data ?? response.rows ?? []) as EmsRecordAlarmRuleVO[];
  });
};

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

const reset = () => {
  form.value = createFormData();
  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[0];
  if (!objId) {
    return;
  }
  getEmsAlarmActionStep(objId).then((response) => {
    form.value = {
      ...createFormData(),
      ...(response.data ?? {})
    };
    open.value = true;
    title.value = '修改报警规则具体措施步骤';
  });
};

const submitForm = () => {
  formRef.value?.validate((valid) => {
    if (!valid) {
      return;
    }
    if (form.value.objId != null) {
      updateEmsAlarmActionStep(form.value).then(() => {
        proxy?.$modal.msgSuccess('修改成功');
        open.value = false;
        getList();
      });
      return;
    }
    addEmsAlarmActionStep(form.value).then(() => {
      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();
  loadRuleOptions();
});
</script>
