<template>
  <ns-drawer
    v-model:visible="visible"
    width="520"
    :title="infoObject?.id ? '编辑告警规则' : '新增告警规则'"
    :footer-style="{ textAlign: 'right' }"
    :ok="btnClick"
    :cancel="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="zdTreeData"
            tree-node-filter-prop="label" />
        </a-form-item>
        <a-form-item label="设备类型" name="deviceType">
          <a-cascader
            v-model:value="infoObject.deviceType"
            :options="deviceTypeTreeData"
            :field-names="{
              children: 'children',
              label: 'deviceType',
              value: 'id',
            }"
            :show-search="{ filter }"
            @change="selectDeviceType"
            placeholder="请选择设备类型" />
        </a-form-item>
        <a-form-item label="设备名称" name="deviceName">
          <a-select
            v-model:value="infoObject.deviceName"
            :disabled="!(infoObject && infoObject.deviceType && infoObject.deviceType.length > 0)"
            style="width: 100%"
            :autoClearSearchValue="true"
            @change="selectDevice"
            placeholder="请选择设备名称">
            <template v-for="(item, index) in deviceNameTreeData" :key="index">
              <a-select-option :value="item.id">
                {{ item.deviceName }}
              </a-select-option>
            </template>
          </a-select>
        </a-form-item>
        <a-form-item label="设备点位" name="devicePoint">
          <a-select
            v-model:value="infoObject.devicePoint"
            show-search
            placeholder="请选择设备点位"
            :disabled="!infoObject?.deviceName"
            style="width: 100%"
            :options="dwOptions"
            :filter-option="filterOption"
            @focus="handleFocus"
            @change="handleChange" />
        </a-form-item>
        <a-form-item label="启用规则" name="enableRules">
          <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="valueType">
          <a-select
            v-model:value="infoObject.valueType"
            show-search
            placeholder="请选择取值类型"
            style="width: 100%"
            :options="qzOptions"
            :filter-option="filterOption"
            @change="handleQzChange" />
        </a-form-item>
        <a-form-item label="异常描述" name="abnormalDescription">
          <a-textarea
            v-model:value="infoObject.abnormalDescription"
            style="height: 32px"
            :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>
        <template v-for="index in infoObject.alarmList?.length" :key="index">
          <div
            style="
              width: 100%;
              display: flex;
              margin-left: 42px;
              padding: 12px;
              border-color: #ff4d4f !important;
            ">
            <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"
              @change="handleQzChange" />
            <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, toRaw, watch } from 'vue';
  import type { CascaderProps, TreeSelectProps, SelectProps } from 'ant-design-vue';
  import type { ShowSearchType } from 'ant-design-vue/es/cascader';
  import { device } from '/@/api/deviceManage';
  import { http } from '/nerv-lib/util';

  import type { Rule } from 'ant-design-vue/es/form';
  import { async } from '@antv/x6/lib/registry/marker/async';

  const visible = ref(false);
  //表单数据
  const infoObject = ref({
    id: null,
    site: null,
    ruleType: null,
    abnormalDescription: null,
    deviceType: [],
    devicePoint: null,
    valueType: null,
    deviceName: null,
    enableRules: 0,
    alarmList: [{ id: null, alarm: null, number: null, isDelete: '0' }],
  });
  //删除的逻辑列表
  const delAlarmList = ref([]);
  const formRef = ref();
  //组织数
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  //站点数
  const zdTreeData = ref<TreeSelectProps['treeData']>([
    {
      label: '铁路总局(T01)',
      value: 'T01',
      children: [
        {
          label: '济阳站(T0101)',
          value: 'T0101',
        },
      ],
    },
  ]);
  //设备类型树
  let deviceTypeTreeData = ref([]);
  //设备树
  let deviceNameTreeData = ref([]);
  //选择设备类型方法
  const selectDeviceType = (value: any, selectedOptions: any) => {
    //获取该类型设备
    getDevicePage({
      orgId: orgId.value,
      code: selectedOptions[selectedOptions.length - 1].code,
      pageNum: 1,
      pageSize: 999,
    });
  };
  //选择设备方法
  const selectDevice = (value: string) => {
    console.log(`selected ${value}`);
  };
  //获取设备列表
  const getDevicePage = (value: any) => {
    http.post(device.queryDevicePage, value).then((res) => {
      if (res.msg === 'success') {
        deviceNameTreeData.value = res.data.records;
      }
    });
  };
  //获取设备点位
  const getDevicePoint = (value: any) => {
    http.post(device.queryDevicePoint, value).then((res) => {
      if (res.msg === 'success') {
        console.log(res, '数据');
      }
    });
  };
  //设备点位
  const dwOptions = ref<SelectProps['options']>([
    { value: '电压 (U)', label: '电压 (U)', code: '1' },
    { value: '电流 (I)', label: '电流 (I)', code: '2' },
    { value: '电流 (I)', label: 'a相电流 (Ia)', code: '3' },
  ]);
  const filter: ShowSearchType['filter'] = (inputValue: any, path: any) => {
    return path.some(
      (option: any) => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );
  };
  //取值类型
  const qzOptions = ref<SelectProps['options']>([
    { value: '实时值', label: '实时值', code: '1' },
    { value: '平均值', label: '平均值', code: '2' },
  ]);
  //逻辑
  const ljOptions = ref<SelectProps['options']>([
    { value: '1', label: '≥' },
    { value: '2', label: '>' },
    { value: '3', label: '≤' },
    { value: '4', label: '<' },
    { value: '5', label: '=' },
  ]);
  //设备点位方法
  const filterOption = (input: string, option: any) => {
    console.log('搜索', option.value);
    return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  const handleFocus = () => {
    console.log('点击');
  };
  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
    console.log('选择', infoObject.value.devicePoint);
    //获得code
    dwOptions.value.forEach((item) => {
      if (item.value === value) {
        console.log('符合', item.code);
      }
    });
  };
  const handleQzChange = (value: string) => {
    //获得code
    qzOptions.value.forEach((item) => {
      if (item.value === value) {
        console.log('符合', item.code);
      }
    });
  };
  //开关
  const clickSwitch = () => {
    if (infoObject.value.enableRules === 1) {
      infoObject.value.enableRules = 0;
    } else {
      infoObject.value.enableRules = 1;
    }
  };
  const emit = defineEmits(['editObject']);

  // 定义一个递归函数来查找每一级的id 设备类型回显 层级方法
  function findParentIds(tree: any, targetId: number, result: any) {
    for (let item of tree) {
      if (item.children && item.children.length > 0) {
        if (item.children.some((child: any) => child.id === targetId)) {
          result.unshift(item.id); // 将当前节点的id添加到结果数组的最前面
          findParentIds(tree, item.id, result); // 递归查找父级节点的id
          break; // 找到后可以退出循环
        }
      }
    }
  }
  // 递归 获取当前 选择的设备类型 对象  用来获取设备列表
  const findNodeById = (nodes: any, id: any) => {
    for (let node of nodes) {
      if (node.id === id) {
        //获取设备树
        getDevicePage({ orgId: orgId.value, code: node.code, pageNum: 1, pageSize: 99 });
        return;
      } else if (node.children.length > 0) {
        const found = findNodeById(node.children, id);
        if (found) {
          //获取设备树
          getDevicePage({ orgId: orgId.value, code: found.code, pageNum: 1, pageSize: 99 });
          return;
        }
      }
    }
    return null; // 没有找到目标节点，返回 null
  };
  //父调子 页面显示方法
  const toggle = async (value: any) => {
    //获取设备类型
    await http
      .post(device.queryDeviceTree, { orgId: orgId.value, pageNum: 1, pageSize: 10 })
      .then((res) => {
        if (res.msg === 'success') {
          deviceTypeTreeData.value = res.data;
        }
      });
    //判断 是新增 还是修改
    if (value) {
      infoObject.value = value;
      // 获取 选择的设备类型对象
      let selectDevice = ref([value.deviceType]);
      findNodeById(deviceTypeTreeData.value, value.deviceType);
      //获取设备点位
      getDevicePoint({ id: 1 });
      // 修改时
      findParentIds(deviceTypeTreeData.value, value.deviceType, selectDevice.value);
      infoObject.value.deviceType = selectDevice.value;
    } else {
      //获取设备树
      infoObject.value = {
        id: null,
        site: null,
        ruleType: null,
        abnormalDescription: null,
        deviceType: [],
        devicePoint: null,
        valueType: null,
        deviceName: null,
        enableRules: 0,
        alarmList: [{ id: null, alarm: null, number: null, isDelete: '0' }],
      };
    }

    visible.value = !visible.value;
  };
  //表单 判断规格
  const rules: infoObject<string, Rule[]> = {
    site: [{ required: true, message: '请选择站点', trigger: 'change' }],
    deviceType: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
    enableRules: [{ required: true, message: '请选择启用规则', trigger: 'change' }],
    deviceName: [{ required: true, message: '请选择设备名称', trigger: 'change' }],
    devicePoint: [{ required: true, message: '请选择设备点位', trigger: 'change' }],
    valueType: [{ required: true, message: '请选择取值类型', trigger: 'change' }],
    ruleType: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
    abnormalDescription: [{ required: true, message: '请输入异常描述', trigger: 'blur' }],
    alarm: [{ required: true, message: '请选择逻辑', trigger: 'blur' }],
    number: [{ required: true, message: '请输入数值', trigger: 'blur' }],
  };
  // 开关选择
  const changeSwitch = () => {
    console.log(infoObject.value.selectSwitch, '开关');
  };
  // 确认按钮
  const btnClick = () => {
    console.log(infoObject.value, '数据');
    infoObject.value.alarmList.forEach((item) => {
      if (item.logic === null || item.num === null) {
        // NsMessage.error('请选择逻辑和数值');
        return;
      }
    });
    if (infoObject.value.alarmList.length < 2) {
      NsMessage.error('请选择逻辑和数值');
      return;
    }
    //数据是否验证通过
    formRef.value.validate().then(() => {
      console.log('values', infoObject.value);
      let data = toRaw(infoObject);
      //逻辑列表
      data.alarmList = [...infoObject.value.alarmList, ...delAlarmList.value];
      //设备类型 只取最后一级的id
      data.deviceType = infoObject.value.deviceType[infoObject.value.deviceType.length - 1];
      delAlarmList.value = [];
    });
    //调用接口
    // http
    //         .post(props.api, data)
    //         .then(() => {
    //           isLoading.value = false;
    //           NsMessage.success('操作成功', 1, () => {
    //             navigateBack();
    //           });
    //         })
    //         .catch(() => {
    //           isLoading.value = false;
    //         });
  };
  //取消按钮
  const handleClose = () => {
    // 清楚校验错误信息
    formRef.value.resetFields();
    //对象清空
    infoObject.value = {
      id: null,
      site: null,
      ruleType: null,
      abnormalDescription: null,
      deviceType: [],
      devicePoint: null,
      enableRules: 0,
      alarmList: [{ id: null, alarm: null, number: null, isDelete: '0' }],
    };
    visible.value = false;
    delAlarmList.value = [];
  };
  // 新增逻辑列表
  const addAlarmList = () => {
    if (infoObject.value.alarmList) {
      infoObject.value.alarmList.push({ logic: null, num: null });
    } else {
      infoObject.value.alarmList = [{ logic: null, num: null }];
    }
  };
  // 删除 逻辑列表、
  const deleteAlarmList = (index: number) => {
    // 确保 index 在有效范围内
    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);
    } else {
      console.error('Invalid index: ', index);
    }
  };
  defineExpose({
    toggle,
    handleClose,
    dwOptions,
    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>
