<template>
  <ns-drawer
    v-model:visible="visible"
    width="562px"
    :title="' '"
    :footer-style="{ textAlign: 'right' }"
    :ok="btnClick"
    :cancel="handleClose"
    placement="right"
    @close="handleClose">
    <div class="ns-title-extra-box title">
      <span style="margin-left: 6px">{{ infoObject?.id ? '编辑' : '新增' }}</span>
    </div>
    <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 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 || infoObject.alarmFrequency === 3"
        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="intervalDurationUnitData" />
          </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="监测频率" name="monitorFrequency">
        <a-select
          v-model:value="infoObject.monitorFrequency"
          placeholder="请选择监测频率"
          style="width: 100%"
          allowClear
          :options="MonitorFrequencyEnumm" />
      </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 { energyAlarms } from '/@/api/alarmManagement/alarmSettings/energyAlarm';
  import { getAllEnum } from '/@/api';

  const visible = ref(false);
  // 间隔单位 默认值
  const handleChangeAlarmFrequency = () => {
    if (infoObject.value.alarmFrequency !== 1 && !infoObject.value.intervalDurationUnit) {
      infoObject.value.intervalDurationUnit = 1;
    }
    if (infoObject.value.alarmFrequency === 3) {
      infoObject.value.repetitions = null;
    }
  };
  //组织id
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;

  //表单数据
  const infoObject = ref({
    alarmTitle: null,
    alarmFrequency: null,
    priority: null,
    monitorFrequency: null,
    createWorkOrder: null,
    orgId: null,
    enableRules: 0,
  });
  const formRef = ref();
  const emit = defineEmits(['editObject']);
  //告警频率 优先级 监测频率
  const AlarmFrequencyEnum = ref([]);
  const PriorityEnum = ref([]);
  const intervalDurationUnitData = ref([]);
  const MonitorFrequencyEnumm = ref([]);
  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' }],
    intervalDuration: [
      {
        required: true,
        message: '请输入正确的间隔时长',
        trigger: 'change',
        validator: (rules: any, intervalDuration: any, cbfn: any) => {
          if (intervalDuration && intervalDuration > 0) {
            cbfn();
          } else {
            cbfn('请输入正确的间隔时长');
          }
          if (!infoObject.value.intervalDurationUnit) {
            cbfn('请选择间隔时长单位');
          }
        },
      },
    ],
    repetitions: [
      {
        required: true,
        message: '请输入正确的重复次数',
        trigger: 'change',
        validator: (rules: any, repetitions: any, cbfn: any) => {
          if (repetitions && repetitions > 0) {
            cbfn();
          } else {
            cbfn('请输入正确的重复次数');
          }
        },
      },
    ],
    createWorkOrder: [{ required: true, message: '请选择是否创建工单', trigger: 'change' }],
    monitorFrequency: [{ required: true, message: '请选择监测频率', trigger: 'change' }],
    priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
    monitorTimeUnit: [{ required: true, message: '请选择监测时长单位', trigger: 'change' }],
  };
  const getMenu = async () => {
    let enumData = await getAllEnum({
      params: [
        'PriorityEnum',
        'MonitorFrequencyEnumm',
        'AlarmFrequencyEnum',
        'IntervalDurationUnitEnum',
      ],
    });
    PriorityEnum.value = enumData.data.PriorityEnum;
    MonitorFrequencyEnumm.value = enumData.data.MonitorFrequencyEnumm;
    AlarmFrequencyEnum.value = enumData.data.AlarmFrequencyEnum;
    intervalDurationUnitData.value = enumData.data.IntervalDurationUnitEnum;
  };
  const toggle = (value: any) => {
    //获取枚举 回显
    getMenu();
    //判断 是新增 还是修改
    if (value) {
      infoObject.value = value;
    } else {
      infoObject.value = {
        orgId: null,
        alarmTitle: null,
        alarmFrequency: null,
        priority: null,
        monitorFrequency: null,
        createWorkOrder: null,
        enableRules: 0,
      };
    }
    visible.value = !visible.value;
  };
  //开关
  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(() => {
      let data = { ...infoObject.value };
      if (!data.orgId) {
        data.orgId = orgId.value;
      }
      data.createWorkOrder = Number(data.createWorkOrder);
      if (data.alarmFrequency === 1) {
        data.repetitions = null;
        data.intervalDuration = null;
        data.intervalDurationUnit = null;
      }
      //调用接口
      http.post(energyAlarms.addOrUpNewData, data).then(() => {
        emit('editObject', null);
        if (infoObject.value.id) {
          NsMessage.success('告警编辑成功');
        } else {
          NsMessage.success('告警创建成功');
        }
        handleClose();
      });
    });
  };
  const handleClose = () => {
    // 清楚校验错误信息
    formRef.value.resetFields();
    infoObject.value = {
      alarmTitle: null,
      alarmFrequency: null,
      priority: null,
      monitorFrequency: null,
      createWorkOrder: null,
      enableRules: 0,
    };
    visible.value = false;
  };
  defineExpose({
    toggle,
    handleClose,
    formRef,
  });
</script>
<style scoped lang="less">
  .drawerContainer {
    height: 100%;
    display: flex;
    justify-content: space-between;
  }
  .title {
    width: 200px;
    height: 22px;
    opacity: 1;
    /** 文本1 */
    font-size: 16px;
    font-weight: 700;
    letter-spacing: 0px;
    line-height: 21px;
    color: rgba(51, 51, 51, 1);
    margin-bottom: 24px;
    margin-left: 24px;
  }
  .blue-background.ant-switch-checked {
    background-color: linear-gradient(
      180deg,
      rgba(1, 206, 255, 1) 0%,
      rgba(57, 215, 187, 1) 100%
    ) !important;
  }

  .grey-background.ant-switch {
    background-color: rgba(238, 238, 238, 1) !important;
  }

  .blue-background.ant-switch-checked .ant-switch-handle {
    background-color: linear-gradient(
      180deg,
      rgba(1, 206, 255, 1) 0%,
      rgba(57, 215, 187, 1) 100%
    ) !important;
  }
  .ant-switch-checked {
    background-color: rgba(57, 215, 187, 1) !important;
  }
  .grey-background.ant-switch .ant-switch-handle {
    background-color: rgba(238, 238, 238, 1) !important;
  }
  :deep(.ant-form-item-label) {
    z-index: 20;
    text-align: right;
    width: 23%;
  }
</style>