<template>
  <div class="p-2">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="规则名称" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          placeholder="请输入规则名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="触发规则" prop="triggerRule">
        <el-select v-model="queryParams.triggerRule" placeholder="请选择触发规则" clearable>
          <el-option
            v-for="dict in trigger_rule"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="通知用户" prop="notifyUser">-->
<!--        <el-input-->
<!--          v-model="queryParams.notifyUser"-->
<!--          placeholder="请输入通知用户"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </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-row :gutter="10" class="mb8">
     <el-col :span="1.5">
       <el-button
         type="primary"
         plain
         icon="Plus"
         @click="handleAdd"

        >新增
        </el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"

        >修改
        </el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"

        >删除
        </el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"

          @click="handleExport"
          v-hasPermi="['ems:record:recordAlarmRule:export']"
        >导出
        </el-button>
      </el-col>-->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="recordAlarmRuleList" @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="ruleId" v-if="columns[1].visible"/>
      <el-table-column label="规则名称" align="center" prop="ruleName" v-if="columns[2].visible"/>
      <el-table-column label="计量设备编号" align="center" prop="monitorId" v-if="columns[3].visible"/>
      <el-table-column label="记录时间" align="center" prop="collectTime" width="180" v-if="columns[4].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="energyType" v-if="columns[5].visible"/>
      <el-table-column label="触发规则" align="center" prop="triggerRule" v-if="columns[6].visible">
        <template #default="scope">
          <dict-tag :options="trigger_rule" :value="scope.row.triggerRule"/>
        </template>
      </el-table-column>
      <el-table-column label="触发阈值次数" align="center" prop="triggerNumber" v-if="columns[7].visible"/>
      <el-table-column label="时间范围(分)" align="center" prop="timeRange" v-if="columns[8].visible"/>
      <el-table-column label="设备离线时间(分钟)" align="center" prop="deviceOfflineTime" v-if="columns[9].visible"/>
      <el-table-column label="通知用户" align="center" prop="notifyUser" v-if="columns[10].visible"/>
      <el-table-column label="备注" align="center" prop="cause" v-if="columns[11].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template #default="scope">
          <el-button

            type="text"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ems:record:recordAlarmRule:edit']"
          >修改
          </el-button>
<!--          <el-button-->
<!--           -->
<!--            type="text"-->
<!--            icon="Delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['ems:record:recordAlarmRule: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="dialogTitle" v-model="dialogOpen" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="规则编号" prop="ruleId">
          <el-input v-model="form.ruleId" placeholder="请输入规则编号" />
        </el-form-item>
        <el-form-item label="规则名称" prop="ruleName">
          <el-input v-model="form.ruleName" placeholder="请输入规则名称"/>
        </el-form-item>
<!--        <el-form-item label="计量设备编号" prop="monitorId">-->
<!--          <el-input v-model="form.monitorId" placeholder="请输入计量设备编号"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="记录时间" prop="collectTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="form.collectTime"-->
<!--                          type="date"-->
<!--                          value-format="YYYY-MM-DD"-->
<!--                          placeholder="请选择记录时间"-->
<!--          >-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="能源类型" prop="energyType">-->
<!--          <el-input v-model="form.energyType" placeholder="请输入能源类型"/>-->
<!--        </el-form-item>-->
        <el-form-item label="触发规则" prop="triggerRule">
          <el-radio-group v-model="form.triggerRule">
            <el-radio
              v-for="dict in trigger_rule"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="触发阈值次数" prop="triggerNumber">-->
<!--          <el-input v-model="form.triggerNumber" placeholder="请输入触发阈值次数"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="时间范围(分)" prop="timeRange">-->
<!--          <el-input v-model="form.timeRange" placeholder="请输入时间范围(分)"/>-->
<!--        </el-form-item>-->
        <el-form-item label="设备离线时间(分钟)" prop="deviceOfflineTime">
          <el-input-number v-model="form.deviceOfflineTime" placeholder="请输入设备离线时间(分钟)"/>
        </el-form-item>
<!--        <el-form-item label="通知用户" prop="notifyUser">-->
<!--          <el-input v-model="form.notifyUser" placeholder="请输入通知用户"/>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="cause">
          <el-input v-model="form.cause" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<!--<script>
/*
import {
  listRecordAlarmRule,
  getRecordAlarmRule,
  delRecordAlarmRule,
  addRecordAlarmRule,
  updateRecordAlarmRule
} from '@/api/ems/record/recordAlarmRule'

export default {
  name: 'RecordAlarmRule',
  dicts: ['trigger_rule'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 异常告警规则表格数据
      recordAlarmRuleList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleId: null,
        ruleName: null,
        monitorId: null,
        collectTime: null,
        energyType: null,
        triggerRule: null,
        triggerNumber: null,
        timeRange: null,
        deviceOfflineTime: null,
        notifyUser: null,
        cause: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        objId: [
          { required: true, message: '自增标识不能为空', trigger: 'blur' }
        ]
      },
      columns: [
        { key: 0, label: `自增标识`, visible: false },
        { key: 1, label: `规则编号`, visible: true },
        { key: 2, label: `规则名称`, visible: true },
        { key: 3, label: `计量设备编号`, visible: false },
        { key: 4, label: `记录时间`, visible: false },
        { key: 5, label: `能源类型`, visible: false },
        { key: 6, label: `触发规则`, visible: true },
        { key: 7, label: `触发阈值次数`, visible: false },
        { key: 8, label: `时间范围(分)`, visible: false },
        { key: 9, label: `设备离线时间(分钟)`, visible: true },
        { key: 10, label: `通知用户`, visible: false },
        { key: 11, label: `备注`, visible: true },
        { key: 12, label: `创建人`, visible: false },
        { key: 13, label: `创建时间`, visible: false },
        { key: 14, label: `更新人`, visible: false },
        { key: 15, label: `更新时间`, visible: false }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询异常告警规则列表 */
    getList() {
      this.loading = true
      listRecordAlarmRule(this.queryParams).then(response => {
        this.recordAlarmRuleList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      dialogOpen.value = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        objId: null,
        ruleId: null,
        ruleName: null,
        monitorId: null,
        collectTime: null,
        energyType: null,
        triggerRule: null,
        triggerNumber: null,
        timeRange: null,
        deviceOfflineTime: null,
        notifyUser: null,
        cause: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.objId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      dialogOpen.value = true
      dialogTitle.value = '添加异常告警规则'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const objId = row.objId || this.ids
      getRecordAlarmRule(objId).then(response => {
        this.form = response.data
        dialogOpen.value = true
        dialogTitle.value = '修改异常告警规则'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.objId != null) {
            updateRecordAlarmRule(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              dialogOpen.value = false
              this.getList()
            })
          } else {
            addRecordAlarmRule(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              dialogOpen.value = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const objIds = row.objId || this.ids
      this.$modal.confirm('是否确认删除异常告警规则编号为"' + objIds + '"的数据项？').then(function() {
        return delRecordAlarmRule(objIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ems/record/recordAlarmRule/export', {
        ...this.queryParams
      }, `recordAlarmRule_${new Date().getTime()}.xlsx`)
    }
  }
}
*/
</script>-->
<script setup lang="ts">
import { ref, reactive, toRefs, getCurrentInstance, ComponentInternalInstance, onMounted } from 'vue';
import type { ElFormInstance, FormRules } from 'element-plus';
import { listRecordAlarmRule, getRecordAlarmRule, delRecordAlarmRule, addRecordAlarmRule, updateRecordAlarmRule } from '@/api/ems/record/recordAlarmRule';
import type { RecordAlarmRuleVO, RecordAlarmRuleForm } from '@/api/ems/record/types';

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

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

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 dialogOpen = ref(false);
const dialogTitle = ref('');

const recordAlarmRuleList = ref<RecordAlarmRuleVO[]>([]);

const columns = ref([
  { key: 0, label: `自增标识`, visible: false },
  { key: 1, label: `规则编号`, visible: true },
  { key: 2, label: `规则名称`, visible: true },
  { key: 3, label: `计量设备编号`, visible: false },
  { key: 4, label: `记录时间`, visible: false },
  { key: 5, label: `能源类型`, visible: false },
  { key: 6, label: `触发规则`, visible: true },
  { key: 7, label: `触发阈值次数`, visible: false },
  { key: 8, label: `时间范围(分)`, visible: false },
  { key: 9, label: `设备离线时间(分钟)`, visible: true },
  { key: 10, label: `通知用户`, visible: false },
  { key: 11, label: `备注`, visible: true },
  { key: 12, label: `创建人`, visible: false },
  { key: 13, label: `创建时间`, visible: false },
  { key: 14, label: `更新人`, visible: false },
  { key: 15, label: `更新时间`, visible: false }
]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleId: null,
    ruleName: null,
    monitorId: null,
    collectTime: null,
    energyType: null,
    triggerRule: null,
    triggerNumber: null,
    timeRange: null,
    deviceOfflineTime: null,
    notifyUser: null,
    cause: null
  } as any,
  form: {
    objId: null,
    ruleId: null,
    ruleName: null,
    monitorId: null,
    collectTime: null,
    energyType: null,
    triggerRule: null,
    triggerNumber: null,
    timeRange: null,
    deviceOfflineTime: null,
    notifyUser: null,
    cause: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  } as RecordAlarmRuleForm
});

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

const rules = reactive<FormRules>({
  objId: [{ required: true, message: '自增标识不能为空', trigger: 'blur' }]
});

const getList = () => {
  loading.value = true;
  listRecordAlarmRule(data.queryParams).then((response: any) => {
    recordAlarmRuleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
};

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

const reset = () => {
  data.form = {
    objId: null,
    ruleId: null,
    ruleName: null,
    monitorId: null,
    collectTime: null,
    energyType: null,
    triggerRule: null,
    triggerNumber: null,
    timeRange: null,
    deviceOfflineTime: null,
    notifyUser: null,
    cause: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  formRef.value?.resetFields();
};

const handleQuery = () => {
  data.queryParams.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();
  dialogOpen.value = true;
  dialogTitle.value = '添加异常告警规则';
};

const handleUpdate = (row: any) => {
  reset();
  const objId = row?.objId ?? ids.value;
  getRecordAlarmRule(objId).then((response: any) => {
    data.form = response.data;
    dialogOpen.value = true;
    dialogTitle.value = '修改异常告警规则';
  });
};

const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    if (data.form.objId != null) {
      updateRecordAlarmRule(data.form).then(() => {
        proxy?.$modal.msgSuccess('修改成功');
        dialogOpen.value = false;
        getList();
      });
    } else {
      addRecordAlarmRule(data.form).then(() => {
        proxy?.$modal.msgSuccess('新增成功');
        dialogOpen.value = false;
        getList();
      });
    }
  });
};

const handleDelete = (row?: any) => {
  const objIds = row?.objId ?? ids.value;
  proxy?.$modal
    .confirm('是否确认删除异常告警规则编号为"' + objIds + '"的数据项？')
    .then(() => delRecordAlarmRule(objIds))
    .then(() => {
      getList();
      proxy?.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
};

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

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