/* eslint-disable no-restricted-syntax */
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { GetWebMenuInfo, getWebModuleTree } from '@/services/webConfig/api';
import { message, Input, Tree, Empty, Tooltip, notification } from 'antd';
import lodash from 'lodash';
import {
  FolderFilled,
  FileOutlined,
  InfoCircleOutlined,
  HomeOutlined,
  DesktopOutlined,
} from '@ant-design/icons';
import styles from './TreeSelect.less';
const TreeSelect = (props, ref) => {
  const { value, onChange, menuChange, code, initCurrentMenu, userMode, curWeb } = props;
  const [menuWebList, setMenuWebList] = useState({});
  const [webList, setWebList] = useState([]);
  const [visible, setVisible] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const { TreeNode } = TreeSelect;
  const [keepKey, setKeepKey] = useState([]);
  useEffect(() => {
    getMenu();
  }, []);

  const getMenu = () => {
    getWebModuleTree('super')
      .then(res => {
        const { data } = res;
        if (res.code === 0) {
          let list = [];
          let arr = data.filter(item => item.id === 'Web4SingleStation');
          let datalist = arr[0].children;
          datalist.map((i, j) => {
            let aa = [];
            i.children.map(k => {
              if (k.text === '菜单管理') {
                aa = k.children;
              }
            });
            let a = {};
            a.value = `praent${j}`;
            a.text = i.text;
            a.children = aa;
            a.menuID = `praent${j}`;
            a.key = `praent${j}`;
            a.item = 'father';
            list.push(a);
          });
          let str = list.find(i => i.text === curWeb.text);
          setMenuWebList(str);
          setWebList(str.children);
          let aa = getKey(str.children);
          setKeepKey(aa);
          setExpandedKeys([...aa]);
        } else {
          notification.error({
            message: '提示',
            duration: 3,
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };

  const filterList = val => {
    if (!val) {
      val = '';
    }
    if (val !== '') {
      let newTree = menuWebList.children.map(item => mapTree(item, val));
      let filter = filterTree(newTree);
      let newData = filterTreeParent(filter);
      let arr = [];
      newData.map(i => {
        if (i.children.length !== 0 || i.show !== '') {
          arr.push(i);
        }
      });
      setWebList(arr);
      let aa = getKey(arr);
      setExpandedKeys([...aa]);
    } else {
      setWebList(menuWebList.children);
      setExpandedKeys([...keepKey]);
    }
  };

  const getKey = (users, allKeys = []) => {
    users.forEach(v => {
      let name = v.menuID || v.key;
      if (v.children.length > 0) {
        name && allKeys.push(name);
      }
      if (v.children.length > 0) {
        return getKey(v.children, allKeys);
      }
    });

    return allKeys;
  };

  const mapTree = (val, word) => {
    const obj = { ...val };
    const hasChild = obj.children.length > 0;
    let status = '';
    if (!condition(obj, word) && word !== '' && obj.children.length === 0) {
      status = false;
    }
    if (condition(obj, word) && word !== '' && obj.children.length === 0) {
      status = true;
    }
    return {
      title: obj.text || obj.title,
      key: obj.menuID || obj.key,
      icon: obj.menuType === 'Web4MenuGroup' ? <FolderFilled /> : <FileOutlined />,
      menuType: obj.menuType,
      disabled: hasChild || obj.pageUrl === null,
      pageUrl: obj.pageUrl,
      product: obj.product,
      show: status,
      children: hasChild ? obj.children.map(i => mapTree(i, word)) : [],
    };
  };

  const filterTree = data => {
    let result = [];
    for (let item of data) {
      if (item.show !== false) {
        let node = { ...item };
        if (item.children) {
          node.children = filterTree(item.children);
        }
        result.push(node);
      }
    }
    return result;
  };

  const filterTreeParent = data => {
    let result = [];
    for (let item of data) {
      if (item.show !== '' || item.children.length > 0) {
        let node = { ...item };
        if (item.children) {
          node.children = filterTreeParent(item.children);
        }
        result.push(node);
      }
    }
    return result;
  };

  // 过滤条件
  const condition = (node, val) => {
    let name = node.title || node.text;
    return name?.includes(val) || node.pageUrl?.includes(val);
  };

  const changeValue = e => {
    // 过滤数组
    onChange(e.target.value);
    filterList(e.target.value);
    setVisible(true);
  };

  const onSelect = (selectedKeysValue, info) => {
    onChange(info.node.pageUrl);
    setVisible(false);
  };

  const onExpand = expandedKeysValue => {
    setExpandedKeys(expandedKeysValue);
  };

  return (
    <div className={styles.treeSelect}>
      <Input
        allowClear
        placeholder="请选填写菜单功能路径"
        value={value}
        onFocus={() => filterList(value)}
        onClick={() => setVisible(!visible)}
        onChange={changeValue}
        onBlur={() => setVisible(false)}
      />
      <div
        className={styles.dropBox}
        onMouseDown={event => {
          event.preventDefault();
        }}
        style={{ display: visible ? 'block' : 'none' }}
      >
        <Tree
          onExpand={onExpand}
          selectedKeys={null}
          showIcon
          expandedKeys={expandedKeys}
          autoExpandParent
          onSelect={onSelect}
          treeData={webList && webList.map(val => mapTree(val))}
          style={{ width: '100%' }}
        />
        {Object.keys(webList).length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> : null}
      </div>
    </div>
  );
};

export default forwardRef(TreeSelect);