<template>
  <ns-drawer
    v-model:visible="visible"
    width="520"
    :title="infoObject?.id ? '编辑告警' : '新增告警'"
    :footer-style="{ textAlign: 'right' }"
    :ok="btnClick"
    :cancel="handleClose"
    placement="right"
    @close="handleClose">
    <a-form ref="formRef" :model="infoObject" :rules="rules">
      <a-form-item name="alarmTitle" label="告警标题">
        <ns-input allowClear v-model:value="infoObject.alarmTitle" placeholder="请输入告警标题" />
      </a-form-item>
      <a-form-item name="monitorTime" label="监测时长">
        <ns-input-number
          allowClear
          v-model:value="infoObject.monitorTime"
          placeholder="请输入监测时长" />
      </a-form-item>
      <a-form-item label="监测时长单位" name="monitorTimeUnit">
        <a-select
          v-model:value="infoObject.monitorTimeUnit"
          placeholder="请选择监测时长单位"
          style="width: 100%"
          allowClear
          :options="MonitorTimeUnitEnum" />
      </a-form-item>
      <a-form-item label="告警频率" name="alarmFrequency">
        <a-select
          v-model:value="infoObject.alarmFrequency"
          placeholder="请选择告警频率"
          style="width: 100%"
          allowClear
          :options="AlarmFrequencyEnum"
          @change="handleChangeAlarmFrequency" />
      </a-form-item>
      <a-form-item v-if="infoObject.alarmFrequency === 2" name="repetitions" label="重复次数">
        <ns-input-number v-model:value="infoObject.repetitions" placeholder="请输入重复次数" />
      </a-form-item>
      <a-form-item v-if="infoObject.alarmFrequency === 2" name="intervalDuration" label="间隔时长">
        <ns-input-number
          style="width: 100%"
          v-model:value="infoObject.intervalDuration"
          placeholder="请输入间隔时长">
          <template #addonAfter>
            <a-select
              v-model:value="infoObject.intervalDurationUnit"
              placeholder="请选择间隔时长单位"
              style="width: 80px"
              allowClear
              :options="IntervalDurationUnitEnum" />
          </template>
        </ns-input-number>
      </a-form-item>
      <a-form-item label="优先级" name="priority">
        <a-select
          v-model:value="infoObject.priority"
          placeholder="请选择优先级"
          style="width: 100%"
          allowClear
          :options="PriorityEnum" />
      </a-form-item>
      <a-form-item label="启用规则">
        <a-switch
          :checked="infoObject?.enableRules === 1 ? true : false"
          :class="{
            'blue-background': infoObject?.enableRules === 1 ? true : false,
            'grey-background': infoObject?.enableRules === 1 ? false : true,
          }"
          style="margin-left: 6px"
          @change="changeSwitch" />
      </a-form-item>
      <a-form-item label="是否创建工单" name="createWorkOrder">
        <a-radio-group v-model:value="infoObject.createWorkOrder">
          <a-radio value="1">是 </a-radio>
          <a-radio value="0">否 </a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </ns-drawer>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { NsMessage } from '/nerv-lib/component';
  import { http } from '/nerv-lib/util';
  import { deviceAlarms } from '/@/api/alarmManagement/alarmSettings/deviceAlarms';
  import { getAllEnum } from '/@/api';

  const visible = ref(false);
  //组织id
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  //表单数据
  const infoObject = ref({
    id: null,
    alarmTitle: null,
    alarmFrequency: null,
    monitorTime: null,
    monitorTimeUnit: null,
    priority: null,
    createWorkOrder: null,
    intervalDurationUnit: null,
    repetitions: null,
    intervalDuration: null,
    enableRules: 0,
  });
  const formRef = ref();
  const emit = defineEmits(['editObject']);
  const AlarmFrequencyEnum = ref([]);
  const MonitorTimeUnitEnum = ref([]);
  const IntervalDurationUnitEnum = ref([]);
  const PriorityEnum = ref([]);
  const getMenu = async () => {
    let enumData = await getAllEnum({
      params: [
        'PriorityEnum',
        'MonitorTimeUnitEnum',
        'AlarmFrequencyEnum',
        'IntervalDurationUnitEnum',
      ],
    });
    PriorityEnum.value = enumData.data.PriorityEnum;
    MonitorTimeUnitEnum.value = enumData.data.MonitorTimeUnitEnum;
    AlarmFrequencyEnum.value = enumData.data.AlarmFrequencyEnum;
    IntervalDurationUnitEnum.value = enumData.data.IntervalDurationUnitEnum;
  };
  const toggle = (value: any) => {
    //获取枚举 回显
    getMenu();
    //判断 是新增 还是修改
    if (value) {
      infoObject.value = value;
    } else {
      infoObject.value = {
        id: null,
        alarmTitle: null,
        alarmFrequency: null,
        monitorTime: null,
        monitorTimeUnit: null,
        priority: null,
        createWorkOrder: null,
        intervalDurationUnit: null,
        repetitions: null,
        intervalDuration: null,
        enableRules: 0,
      };
    }
    visible.value = !visible.value;
  };
  // 间隔单位 默认值
  const handleChangeAlarmFrequency = () => {
    if (infoObject.value.alarmFrequency === 2 && !infoObject.value.intervalDurationUnit) {
      infoObject.value.intervalDurationUnit = 1;
    }
  };
  //表单 判断规格
  const rules = {
    alarmTitle: [
      {
        required: true,
        message: '请输入告警标题',
        trigger: 'change',
        validator: (rules: any, alarmTitle: any, cbfn: any) => {
          if (alarmTitle && alarmTitle.trim() !== '') {
            cbfn();
          } else {
            cbfn('告警标题不能为空');
          }
        },
      },
    ],
    alarmFrequency: [{ required: true, message: '请选择告警频率', trigger: 'change' }],
    monitorTime: [
      {
        required: true,
        trigger: 'change',
        validator: (rules: any, monitorTime: any, cbfn: any) => {
          if (Number.isInteger(monitorTime) && monitorTime > 0) {
            cbfn();
          } else {
            cbfn('请输入正确的监测时长');
          }
        },
      },
    ],
    intervalDuration: [
      {
        required: true,
        trigger: 'change',
        validator: (rules: any, intervalDuration: any, cbfn: any) => {
          if (
            Number.isInteger(intervalDuration) &&
            intervalDuration > 0 &&
            infoObject.value.intervalDurationUnit
          ) {
            cbfn();
          } else {
            cbfn('请输入正确的间隔时长');
          }
        },
      },
    ],
    repetitions: [
      {
        required: true,
        trigger: 'change',
        validator: (rules: any, repetitions: any, cbfn: any) => {
          if (Number.isInteger(repetitions) && repetitions > 0) {
            cbfn();
          } else {
            cbfn('请输入正确的重复次数');
          }
        },
      },
    ],
    createWorkOrder: [{ required: true, message: '请选择是否创建工单', trigger: 'change' }],
    priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
    monitorTimeUnit: [{ required: true, message: '请选择监测时长单位', trigger: 'change' }],
  };
  //开关
  const changeSwitch = () => {
    switch (infoObject.value.enableRules) {
      case 1:
        infoObject.value.enableRules = 0;
        break;
      case 0:
        infoObject.value.enableRules = 1;
        break;
    }
  };
  const btnClick = () => {
    //表单校验
    formRef.value.validate().then(() => {
      // 告警频率重复时 都换成分钟  比较 监测时长 和 间隔时长  重复次数 * 间隔 <= 监测
      if (infoObject.value.alarmFrequency === 2) {
        // 监测时长
        let monitorTime = 0;
        switch (infoObject.value.monitorTimeUnit) {
          case 1:
            monitorTime = Number(infoObject.value.monitorTime) * 1;
            break;
          case 2:
            monitorTime = Number(infoObject.value.monitorTime) * 60;
            break;
          case 3:
            monitorTime = Number(infoObject.value.monitorTime) * 60 * 24;
            break;
        }
        // 间隔时长
        let intervalTime = 0;
        switch (infoObject.value.intervalDurationUnit) {
          case 1:
            intervalTime =
              Number(infoObject.value.intervalDuration) * 1 * Number(infoObject.value.repetitions);
            break;
          case 2:
            intervalTime =
              Number(infoObject.value.intervalDuration) * 60 * Number(infoObject.value.repetitions);
            break;
          case 3:
            intervalTime =
              Number(infoObject.value.intervalDuration) *
              60 *
              24 *
              Number(infoObject.value.repetitions);
            break;
        }
        if (intervalTime > monitorTime) {
          NsMessage.error(
            '间隔时长超过了告警监测周期的最大值。请设置1分钟到' +
              infoObject.value.monitorTime +
              ['分', '小时', '天'][infoObject.value.monitorTimeUnit - 1] +
              '之间的间隔时长',
          );
          return;
        }
      }
      //调用接口
      let data = { ...infoObject.value };
      data.createWorkOrder = Number(data.createWorkOrder);
      if (data.alarmFrequency !== 2) {
        data.repetitions = null;
        data.intervalDuration = null;
        data.intervalDurationUnit = null;
      }
      if (!data.orgId) {
        data.orgId = orgId.value;
      }
      http.post(deviceAlarms.addOrUpNewData, data).then(() => {
        if (infoObject.value.id) {
          NsMessage.success('告警编辑成功');
        } else {
          NsMessage.success('告警创建成功');
        }
        visible.value = false;
        emit('editObject', null);
      });
    });
  };
  const handleClose = () => {
    // 清楚校验错误信息
    formRef.value.resetFields();
    visible.value = false;
  };
  defineExpose({
    toggle,
    handleClose,
    formRef,
  });
</script>
<style scoped lang="less">
  .drawerContainer {
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
  .blue-background.ant-switch-checked {
    background-color: linear-gradient(
      180deg,
      rgba(1, 206, 255, 1) 0%,
      rgba(0, 150, 229, 1) 100%
    ) !important;
  }

  .grey-background.ant-switch {
    background-color: grey !important;
  }

  .blue-background.ant-switch-checked .ant-switch-handle {
    background-color: linear-gradient(
      180deg,
      rgba(1, 206, 255, 1) 0%,
      rgba(0, 150, 229, 1) 100%
    ) !important;
  }

  .grey-background.ant-switch .ant-switch-handle {
    background-color: grey !important;
  }
  :deep(.ant-form-item-label) {
    z-index: 20;
    text-align: right;
    width: 23%;
  }
</style>
../../../../api/alarmManagement/alarmSettings/deviceAlarms
