import React from 'react'
import clsx from 'clsx'
import { CloseOutlined, EditOutlined, PlusOutlined } from '@ant-design/icons';
import { Tree, Input, Tooltip } from 'antd';
import styles from './style.module.less'
const { TreeNode } = Tree;
const { Search } = Input;

const dataList = [];
const generateList = data => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    const { key, title } = node;
    dataList.push({ key, title });
    if (node.children) {
      generateList(node.children);
    }
  }
};

const getParentKey = (key, tree) => {
  let parentKey;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key;
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children);
      }
    }
  }
  return parentKey;
};

class SearchTree extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      expandedKeys: [],
      // searchValue: '',
      autoExpandParent: true,
    }
  }
  componentWillReceiveProps(nextProps) {
    const { autoExpandParent } = this.state
    if (this.props.data.length < 1) {
      generateList(nextProps.data)
      this.setState({
        expandedKeys: dataList.map(t => '' + t.key)
      })
    }
    if((this.props.searchValue !== nextProps.searchValue) && !autoExpandParent) {
      this.setState({
        autoExpandParent: true,
      });
    }
  }
  onExpand = expandedKeys => {
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };

  onChange = e => {
    // const { data, onSearch } = this.props
    // const { value } = e.target;
    // const expandedKeys = dataList
    //   .map(item => {
    //     if (item.title.toString().indexOf(value) > -1) {
    //       return getParentKey(item.key, data);
    //     }
    //     return null;
    //   })
    //   .filter((item, i, self) => item && self.indexOf(item) === i);
    this.setState({
      // expandedKeys,
      // searchValue: value,
      autoExpandParent: true,
    });
    // onSearch(value)
  };

  toolsRender = item => {
    const { add, del, edit, maxLevel, firstLevelNotDel, showDelBtn = false } = this.props
    return (
      <div className={styles.tools}>
        {
          item.level < maxLevel &&
          <PlusOutlined
            className={styles.icon}
            onClick={(e) => {
              e.stopPropagation()
              add(item)
            }} />
        }
        <EditOutlined
          className={styles.icon}
          onClick={(e) => {
            e.stopPropagation()
            edit(item)
          }} />

        {
          // (
          //   (firstLevelNotDel && item.level !== 1) &&
          //   !(item.children && item.children.length > 0)
          // ) ||
          showDelBtn
          &&
          <CloseOutlined
            className={styles.icon}
            onClick={(e) => {
              e.stopPropagation()
              del(item)
            }} />}
      </div>
    );
  }

  render() {
    const { expandedKeys, autoExpandParent } = this.state;
    const { treeStyles = {}, hiddentoolsBar = false, data, add, onSelect, defaultKeys = [], showAllBtn = false, showAddIcon = false, searchValue } = this.props
    const allList = data[0]?.count ? data.map(t => t.count) : []
    const allCount = allList.length > 0 && allList.reduce((t, n) => t + n)
    const loop = data => (
      data.map(item => {
        const index = item.title.indexOf(searchValue);
        const beforeStr = item.title.substr(0, index);
        const afterStr = item.title.substr(index + searchValue.length);
        const title =
          index > -1 ? (
            <div className={clsx(styles.treeItem, 'flex-center-between')}>
              <Tooltip title={item.title}>
                <div className="ellipsis">
                  {beforeStr}
                  <span className="keyWordsColor">{searchValue}</span>
                  {afterStr}
                  {item.count > 0 && <span className='countBox'>{item.count}</span>}
                </div>
              </Tooltip>
              {!hiddentoolsBar && this.toolsRender(item)}
            </div>
          ) : (
              <div className={clsx(styles.treeItem, 'flex-center-between')}>
                <Tooltip title={item.title}>
                  <div className="ellipsis">
                    {item.title}
                    {item.count && item.count > 0 && <span className='countBox'>{item.count}</span>}
                  </div>
                </Tooltip>
                {!hiddentoolsBar && this.toolsRender(item)}
              </div>
            )
        if (item.children) {
          return (
            <TreeNode key={item.key} title={title}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        // 如果没有子并且没有匹配就隐藏
        if(index < 0) {
          return <TreeNode key={item.key} title={title} />;
        }
      })
    )
    return (
      <div className={styles.searchTree}>
        <div className={styles.tree} style={treeStyles}>
          {showAllBtn && 
            <div
              className={clsx(!defaultKeys[0] && 'active', 'pointer')}
              onClick={() => onSelect([''])}
            >
              全部
              {allCount && <span className='countBox'>{allCount}</span>}
            </div>
          }
          <Tree
            onExpand={this.onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            selectedKeys={defaultKeys}
            // multiple={true}
            onSelect={(selectedKeys) => onSelect(selectedKeys)}
          >
            {loop(data)}
          </Tree>
        </div>
      </div>
    );
  }
}

export default SearchTree;
