/**
 * tree 基础组件支持各种自定义其他tree可用过它来拓展
 */
import React from 'react';
import PropTypes from 'prop-types';
import { Tree } from 'antd';
import IconFont from '../../themeComponents/IconFont';
import HightLevel from '../HightLevel';
import './index.less';

const TreeNode = Tree.TreeNode;

class TreeView extends React.Component {
  static propTypes = {
    treeNodeProps: PropTypes.shape({
      treeNodeClass: PropTypes.func,
      prefix: PropTypes.func,
      suffix: PropTypes.func,
      treeNodeIcon: PropTypes.func,
      disableCheckbox: PropTypes.func
    })
  };
  constructor() {
    super();
    this.treeRef = React.createRef();
  }
  renderTreeNodes = list => {
    const { treeNodeProps = {} } = this.props;
    const { treeNodeClass, prefix, suffix, treeNodeIcon, keyword, disableCheckbox, key = 'id', nameKey = 'name', RenderTreeTitle } = treeNodeProps;
    const whatClass = treeNodeClass ? treeNodeClass : () => '';
    const nodeProps = {};
    const disable = disableCheckbox ? disableCheckbox : () => false;
    return list.map(node => {
      const className = whatClass(node);
      if (treeNodeIcon) {
        nodeProps.icon = treeNodeIcon(node);
      }
      if (disableCheckbox) {
        nodeProps.disableCheckbox = disable(node);
      }
      return (
        <TreeNode
          {...nodeProps}
          className={className}
          title={<TreeNodeTitle node={node} nameKey={nameKey} keyword={keyword} prefix={prefix} suffix={suffix} RenderTreeTitle={RenderTreeTitle} />}
          key={node[key]}
          dataRef={node}
          isLeaf={node.isLeaf}
        >
          {node.children && this.renderTreeNodes(node.children)}
        </TreeNode>
      );
    });
  };

  getCheckedKeys() {
    if (!this.props.checkable || !this.treeRef.current) {
      return [];
    }
    return this.treeRef.current.tree.state.checkedKeys;
  }
  render() {
    const { className = '', treeData = [], showIcon = true, treeNodeProps, ...props } = this.props;
    return (
      <Tree
        className={`lm-base-tree-component ${className}`}
        showIcon={showIcon}
        ref={this.treeRef}
        switcherIcon={<IconFont style={{ fontSize: 20, verticalAlign: '-0.4em' }} type="icon-S_Arrow_SmallDown" />}
        {...props}
      >
        {this.renderTreeNodes(treeData)}
      </Tree>
    );
  }
}

function TreeNodeTitle({ node, nameKey, prefix, keyword, suffix, RenderTreeTitle }) {
  if (RenderTreeTitle) {
    return <RenderTreeTitle node={node} nameKey={nameKey} keyword={keyword} />;
  }
  return (
    <span title={node[nameKey]}>
      {prefix && prefix(node)}
      <HightLevel keyword={keyword} name={node[nameKey]} />
      {suffix && suffix(node)}
    </span>
  );
}

export default TreeView;
