<template>
  <ns-drawer
    v-model:visible="visible"
    width="520"
    :title="infoObject?.id ? '编辑告警规则' : '新增告警规则'"
    :footer-style="{ textAlign: 'right' }"
    :ok="btnClick"
    :cancel="handleClose"
    @close="handleClose"
    placement="right">
    <div style="padding: 18px; width: 100%; overflow: hidden">
      <a-form ref="formRef" :model="infoObject" :rules="rules">
        <a-form-item ref="site" label="站点" name="site">
          <a-tree-select
            v-model:value="infoObject.site"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择站点"
            allow-clear
            tree-default-expand-all
            :tree-data="siteDataTree"
            :field-names="{
              children: 'linkList',
              label: 'orgName',
              value: 'orgId',
            }"
            tree-node-filter-prop="orgName" />
        </a-form-item>
        <a-form-item label="数据来源" name="dataSources">
          <a-cascader
            v-model:value="infoObject.dataSources"
            :options="deviceTypeTreeData"
            :field-names="{
              children: 'children',
              label: 'cnValue',
              value: 'id',
            }"
            :show-search="{ filterDeviceType }"
            @change="selectDeviceType"
            placeholder="请选择数据来源" />
        </a-form-item>
        <a-form-item label="设备/节点" name="deviceNode">
          <a-tree-select
            v-model:value="infoObject.deviceNode"
            style="width: 100%"
            placeholder="请选择设备节点"
            :disabled="!infoObject.dataSources"
            :tree-line="true && { showLeafIcon: false }"
            :tree-data="jdTreeData"
            :field-names="{
              children: 'children',
              label:
                infoObject.dataSources && infoObject.dataSources[1] === 1
                  ? 'deviceName'
                  : 'pointName',
              value: 'id',
            }" />
        </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,
            }"
            @click="clickSwitch" />
        </a-form-item>
        <a-form-item label="异常描述" name="abnormalDescription">
          <a-textarea
            v-model:value="infoObject.abnormalDescription"
            style="height: 32px"
            placeholder="请输入异常描述"
            :autoSize="{ minRows: 1, maxRows: 1 }"
            show-count
            :maxlength="30" />
        </a-form-item>
        <a-form-item label="规则类型" name="ruleType">
          <a-radio-group v-model:value="infoObject.ruleType">
            <a-radio value="1">且 (and) </a-radio>
            <a-radio value="2">或 (or) </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="对比类型" name="comparisonType">
          <a-cascader
            v-model:value="infoObject.comparisonType"
            :options="comparisonTypeData"
            :showSearch="false"
            placeholder="请选择对比类型" />
        </a-form-item>
        <template v-for="index in infoObject.alarmList?.length" :key="index">
          <div style="width: 100%; display: flex; margin-left: 42px; padding: 12px">
            <span style="line-height: 32px">{{ `逻辑${index}:` }}</span>
            <a-select
              v-model:value="infoObject.alarmList[index - 1].logic"
              style="width: 70px; margin-left: 12px"
              :options="ljOptions" />
            <span style="line-height: 32px; margin-left: 32px">{{ `数值${index}:` }}</span>
            <a-input
              style="width: 65px; margin-left: 6px"
              type="number"
              v-model:value="infoObject.alarmList[index - 1].num" />
            <div
              style="width: 70px; align-items: center; cursor: pointer"
              @click="deleteAlarmList(index - 1)">
              <img
                style="width: 14px; margin: 0 12px"
                src="https://files.axshare.com/gsc/4T0UQR/5a/e6/81/5ae6813d499c422383c7a15dd956523f/images/设备规则/u72.svg?pageId=cbce6e61-bc6a-4283-802d-993fce6151c0" />
            </div>
          </div>
          <div
            v-if="
              infoObject.alarmList[index - 1]?.num === null ||
              infoObject.alarmList[index - 1]?.logic === null
            "
            style="width: 100%; color: #ff4d4f; text-align: center; margin-bottom: 5px">
            请选择正确的逻辑{{ index }} 或 输入正确的数值{{ index }}
          </div>
        </template>
        <div
          v-if="infoObject.alarmList?.length < 2"
          style="width: 100%; color: #ff4d4f; text-align: center; margin-bottom: 5px">
          逻辑至少2条
        </div>
        <div style="width: 100%; margin-top: 12px; display: flex; justify-content: flex-end">
          <a-button type="primary" @click="addAlarmList"> 新增</a-button>
        </div>
      </a-form>
    </div>
  </ns-drawer>
</template>
<script lang="ts" setup>
  import { NsMessage } from '/nerv-lib/component';
  import { ref } from 'vue';
  import type { SelectProps } from 'ant-design-vue';
  import type { ShowSearchType } from 'ant-design-vue/es/cascader';
  import { device, group } from '/@/api/deviceManage';
  import { energyAlarms } from '/@/api/alarmSettings/energyAlarm';
  import { http } from '/nerv-lib/util';
  import { dict } from '/@/api';
  import { async } from '@antv/x6/lib/registry/marker/async';

  // import type { Rule } from 'ant-design-vue/es/form';

  const visible = ref(false);
  //父级数据
  const energyAlarm = ref({});
  //组织数
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  //表单数据
  const infoObject = ref({
    id: null,
    site: null,
    deviceNode: null,
    ruleType: null,
    abnormalDescription: null,
    dataSources: null,
    enableRules: 0,
    alarmList: [{ id: null, logic: null, num: null, isDelete: 0 }],
  });
  const emit = defineEmits(['editObject']);
  //删除的逻辑列表
  const delAlarmList = ref([]);
  //对比类型
  const comparisonTypeData = ref([
    {
      value: '1',
      label: '数值',
      children: [
        {
          value: '1',
          label: '输入数值',
        },
        {
          value: '2',
          label: '同比',
        },
        {
          value: '3',
          label: '环比',
        },
        {
          value: '4',
          label: '对比基准',
        },
      ],
    },
    {
      value: '2',
      label: '比例',
      children: [
        {
          value: '1',
          label: '输入比例',
        },
        {
          value: '2',
          label: '同比',
        },
        {
          value: '3',
          label: '环比',
        },
        {
          value: '4',
          label: '对比基准',
        },
      ],
    },
  ]);
  const formRef = ref();
  //站点数
  const siteDataTree = ref([]);
  //数据来源
  let deviceTypeTreeData = ref([]);
  //节点数据
  const jdTreeData = ref([]);
  //选择设备时 获取的数据
  // 选择 数据来源 查询 设备节点
  const selectDeviceType = async (value: any, selectedOptions: any) => {
    if (!infoObject.value.id) {
      infoObject.value.deviceNode = null;
    }
    if (value[value.length - 1] === 1) {
      //选择设备
      await http
        .post(device.queryDevicePage, {
          pageNum: 1,
          pageSize: 999,
          energyType: selectedOptions[0].cnValue,
          orgId: orgId.value,
        })
        .then((res) => {
          jdTreeData.value = res.data.records;
        });
    } else {
      //选择节点时 获取数据
      await http
        .post(group.queryDeviceGroupTree, {
          pageNum: 1,
          pageSize: 999,
          energyType: selectedOptions[0].cnValue,
          orgId: orgId.value,
        })
        .then((res) => {
          jdTreeData.value = res.data;
        });
    }
  };

  //搜索设备类型
  const filterDeviceType: ShowSearchType['filter'] = (inputValue: any, path: any) => {
    return path.some(
      (option: any) => option.cnValue.toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  };
  //逻辑
  const ljOptions = ref<SelectProps['options']>([
    { value: 0, label: '≥' },
    { value: 1, label: '>' },
    { value: 2, label: '≤' },
    { value: 3, label: '<' },
    { value: 4, label: '=' },
  ]);
  //开关
  const clickSwitch = () => {
    if (infoObject.value.enableRules === 1) {
      infoObject.value.enableRules = 0;
    } else {
      infoObject.value.enableRules = 1;
    }
  };
  //父调子 页面显示方法
  const toggle = async (value: any, info: any) => {
    // 数据来源
    let energyType = await dict({ params: { dicKey: 'ENERGY_TYPE' } });
    if (energyType.data.data) {
      energyType.data.data.forEach((item: any) => {
        item.children = [
          {
            id: 1,
            cnValue: '设备',
          },
          {
            id: 2,
            cnValue: '节点',
          },
        ];
      });
      deviceTypeTreeData.value = energyType.data.data;
    } else {
      deviceTypeTreeData.value = [];
    }

    //能源告警
    energyAlarm.value = info;
    // 获取站点数据
    http.post('/carbon-smart/user/login/logInInfo', {}).then((res) => {
      if (res.msg === 'success') {
        siteDataTree.value = res.data.linkList;
      }
    });
    //判断 是新增 还是修改
    if (value) {
      await http.post(energyAlarms.configFindById, { id: value.id }).then((res) => {
        if (res.msg === 'success') {
          infoObject.value = res.data;
          // 拼凑成 修改回显形式
          infoObject.value.dataSources = [
            infoObject.value.dataSourcesType,
            infoObject.value.dataSourcesWay,
          ];
          delete infoObject.value.dataSourcesType;
          delete infoObject.value.dataSourcesWay;
          infoObject.value.comparisonType = infoObject.value.comparisonType.split(',');
          infoObject.value.ruleType = infoObject.value.ruleType + '';
          infoObject.value.alarmList = infoObject.value.hxAlarmRuleLogicList || [];
          delete infoObject.value.hxAlarmRuleLogicList;
          //获取设备/节点

          if (deviceTypeTreeData && deviceTypeTreeData.value.length > 0) {
            deviceTypeTreeData.value.forEach((item: any) => {
              if (item.id === infoObject.value.dataSources[0]) {
                selectDeviceType(infoObject.value.dataSources, [{ ...item }]);
              }
            });
          }
        }
      });
    } else {
      infoObject.value = {
        id: null,
        site: null,
        deviceNode: null,
        ruleType: null,
        abnormalDescription: null,
        dataSources: null,
        enableRules: 0,
        alarmList: [{ id: null, logic: null, num: null, isDelete: 0 }],
      };
    }

    visible.value = !visible.value;
  };
  //表单 判断规格
  const rules = {
    site: [{ required: true, message: '请选择站点', trigger: 'change' }],
    dataSources: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
    deviceNode: [{ required: true, message: '请选择设备名称', trigger: 'change' }],
    sbAdress: [{ required: true, message: '请选择设备点位', trigger: 'change' }],
    comparisonType: [{ required: true, message: '请选择对比类型', trigger: 'change' }],
    ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
    abnormalDescription: [
      {
        required: true,
        message: '请输入异常描述',
        trigger: 'blur',
        validator: (rules: any, abnormalDescription: any, cbfn: any) => {
          if (abnormalDescription.trim() !== '') {
            cbfn();
          } else {
            cbfn('告警标题不能为空');
          }
        },
      },
    ],
  };
  // 确认按钮
  const btnClick = () => {
    infoObject.value.alarmList.forEach((item) => {
      if (item.logic === null || item.num === null) {
        return;
      }
    });
    if (infoObject.value.alarmList.length < 2) {
      NsMessage.error('请选择逻辑和数值');
      return;
    }
    //数据是否验证通过
    formRef.value.validate().then(() => {
      //处理数据
      let data = { ...infoObject.value };
      //关联能耗告警id
      data.equipmentAlarmId = energyAlarm.value.id;
      data.errorCode = energyAlarm.value.errorCode;
      data.dataSourcesType = data.dataSources[0];
      data.dataSourcesWay = data.dataSources[1];
      delete data.dataSources;
      data.hxAlarmRuleLogicList = [...infoObject.value.alarmList, ...delAlarmList.value];
      data.comparisonType = data.comparisonType.toString();
      data.hxAlarmRuleLogicList.forEach((item) => {
        const num = Number(item.num);
        if (!isNaN(num)) {
          item.num = Number(num.toFixed(2));
        } else {
          item.num = 0; // 可以设置为0或其他默认值
        }
      });
      data.ruleType = Number(data.ruleType);
      delete data.alarmList;
      http
        .post(energyAlarms.configAddOrUpNewData, data)
        .then((res) => {
          if (res.msg === 'success') {
            // 操作成功时的处理
            if (data.id) {
              NsMessage.success('告警规则编辑成功');
            } else {
              NsMessage.success('告警规则新增成功');
            }
            emit('editObject', null);
            handleClose();
          }
        })
        .catch((error) => {
          // 错误处理
          console.error('请求失败：', error);
        });
    });
  };
  //取消按钮
  const handleClose = () => {
    // 清楚校验错误信息
    formRef.value.resetFields();
    //对象清空
    infoObject.value = {
      id: null,
      site: null,
      ruleType: null,
      deviceNode: null,
      abnormalDescription: null,
      dataSources: null,
      enableRules: 0,
      alarmList: [{ id: null, logic: null, num: null, isDelete: 0 }],
    };
    visible.value = false;
    delAlarmList.value = [];
  };
  // 新增逻辑列表
  const addAlarmList = () => {
    if (infoObject.value.alarmList) {
      infoObject.value.alarmList.push({ id: null, logic: null, num: null, isDelete: 0 });
    } else {
      infoObject.value.alarmList = [{ id: null, logic: null, num: null, isDelete: 0 }];
    }
  };
  // 删除 逻辑列表、
  const deleteAlarmList = (index: number) => {
    if (index < infoObject.value.alarmList.length && index >= 0) {
      const alarmItemToDelete = infoObject.value.alarmList[index];
      if (alarmItemToDelete?.id) {
        // 添加到 delAlarmList 中，并标记为已删除
        delAlarmList.value.push({ ...alarmItemToDelete, isDelete: 1 });
      }
      // 从 infoObject 中删除该元素
      infoObject.value.alarmList.splice(index, 1);
    }
  };
  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>
