<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">
            <!-- 特殊处理情况 -->
            <!-- <template #title="{ value: val, label }">
                  <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                  <template v-else>{{ label }}</template>
                </template> -->
          </a-tree-select>
        </a-form-item>
        <a-form-item label="数据来源" name="sbtype">
          <a-cascader
            v-model:value="infoObject.sbtype"
            :options="sbOptions"
            :show-search="{ filter }"
            placeholder="请选择数据来源" />
        </a-form-item>
        <a-form-item label="设备节点" name="jdDevice">
          <a-tree-select
            v-model:value="infoObject.jdDevice"
            style="width: 100%"
            placeholder="请选择设备节点"
            :tree-line="true && { showLeafIcon: false }"
            :tree-data="jdTreeData" />
        </a-form-item>
        <a-form-item label="启用规则" name="delivery">
          <a-switch
            v-model:checked="infoObject.delivery"
            :class="{
              'blue-background': infoObject.delivery,
              'grey-background': !infoObject.delivery,
            }" />
        </a-form-item>
        <a-form-item label="异常描述" name="desc">
          <a-textarea
            v-model:value="infoObject.desc"
            style="height: 32px"
            :autoSize="{ minRows: 1, maxRows: 1 }"
            show-count
            :maxlength="30" />
        </a-form-item>
        <a-form-item label="规则类型" name="resource">
          <a-radio-group v-model:value="infoObject.resource">
            <a-radio value="1">且 (and) </a-radio>
            <a-radio value="2">或 (or) </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="对比类型1" name="qzType">
          <a-cascader
            v-model:value="infoObject.sbtype"
            :options="sbOptions"
            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"
              @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 } 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';

  const visible = ref(false);
  //表单数据
  const infoObject = ref({
    id: null,
    site: null,
    jdDevice: null,
    resource: null,
    desc: null,
    sbtype: null,
    delivery: null,
    alarmList: [{ logic: null, num: null }],
  });
  //删除的逻辑列表
  const delAlarmList = ref([]);
  const formRef = ref();
  //站点数
  const zdTreeData = ref<TreeSelectProps['treeData']>([
    {
      label: '铁路总局(T01)',
      value: 'T01',
      children: [
        {
          label: '济阳站(T0101)',
          value: 'T0101',
        },
      ],
    },
  ]);
  //设备类型树
  const sbOptions: CascaderProps['options'] = [
    {
      value: '3',
      label: '3.电梯',
      children: [
        {
          value: '301',
          label: '301.扶梯',
        },
        {
          value: '302',
          label: '301.直梯',
        },
      ],
    },
    {
      value: '4',
      label: '4.冷热源',
      children: [
        {
          value: '401',
          label: '402.冷水机组',
        },
        {
          value: '402',
          label: '403.热泵机组',
        },
        {
          value: '403',
          label: '403.锅炉',
        },
        {
          value: '404',
          label: '404.水处理机组',
        },
        {
          value: '405',
          label: '405.板式热交换机组',
        },
      ],
    },
  ];
  //节点数据
  const jdTreeData = ref([
    {
      title: 'parent 1',
      value: 'parent 1',
      children: [
        {
          title: 'parent 1-0',
          value: 'parent 1-0',
          children: [
            {
              title: 'my leaf',
              value: 'leaf1',
            },
            {
              title: 'your leaf',
              value: 'leaf2',
            },
          ],
        },
        {
          title: 'parent 1-1',
          value: 'parent 1-1',
        },
      ],
    },
  ]);
  //设备点位
  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.sbAdress);
    //获得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 emit = defineEmits(['editObject']);
  //父调子 页面显示方法
  const toggle = (value: any) => {
    //获取设备类型
    http.post(device.queryDeviceTree, null).then((res) => {
      console.log(res, '请求出来的数据');
      NsMessage.success('操作成功');
    });
    //判断 是新增 还是修改
    if (value) {
      infoObject.value = value;
    } else {
      infoObject.value = {
        id: null,
        site: null,
        jdDevice: null,
        resource: null,
        desc: null,
        sbtype: null,
        delivery: null,
        alarmList: [{ logic: null, num: null }],
      };
    }

    visible.value = !visible.value;
  };
  //表单 判断规格
  const rules: Record<string, Rule[]> = {
    site: [{ required: true, message: '请选择站点', trigger: 'change' }],
    sbtype: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
    delivery: [{ required: true, message: '请选择启用规则', trigger: 'change' }],
    jdDevice: [{ required: true, message: '请选择设备名称', trigger: 'change' }],
    sbAdress: [{ required: true, message: '请选择设备点位', trigger: 'change' }],
    qzType: [{ required: true, message: '请选择取值类型', trigger: 'change' }],
    resource: [{ required: true, message: '请选择规则类型', trigger: 'change' }],
    desc: [{ 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, toRaw(infoObject));
      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,
      resource: null,
      desc: null,
      sbtype: null,
      delivery: null,
      alarmList: [{ alarm: null, number: null }],
    };
    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) => {
    if (infoObject.value.alarmList[index]?.id) {
      delAlarmList.value.push(infoObject.value.alarmList[index]);
    }
    infoObject.value.alarmList.splice(index, 1);
  };
  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>
