import React, { Component } from 'react';
import { Modal, Tree } from 'antd';
import { ContextMenuTrigger } from 'react-contextmenu';
import ContextMenuLayout from '../../layouts/ContextMenuLayout';
import './index.less';

class TreeManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      itemTrigger: [],
    };
  }

  getItem(item, level, index, length) {
    if (item.children && item.children.length > 0) {
      return (
        <Tree.TreeNode key={item.key} title={this.getItemWrap(item, level, index, length)}>
          {item.children.map((subItem, i) => {
            return this.getItem(subItem, level + 1, i, item.children.length);
          })}
        </Tree.TreeNode>
      );
    }
    return <Tree.TreeNode key={item.key} title={this.getItemWrap(item, level, index, length)} />;
  }

  getItemWrap(item, level, index, length) {
    if (item.trigger === false || this.props.trigger === false) {
      return item.title;
    }
    return (
      <ContextMenuTrigger collect={() => ({ item, level, index, length })} holdToDisplay={-1} id="tree-manage-trigger">
        {item.title}
      </ContextMenuTrigger>
    );
  }

  onTriggerShow(e) {
    this.setState({ itemTrigger: this.props.triggerMenu(e) });
  }

  onTriggerHide() {
    this.setState({ itemTrigger: [] });
  }

  onTriggerClick() {}

  render() {
    const { treeData = [] } = this.props;
    const { itemTrigger = [] } = this.state;
    return (
      <Modal
        className="tree-modal"
        visible
        title={this.props.title}
        footer={null}
        closable={!!this.props.onCancel}
        onCancel={this.props.onCancel}
      >
        <div className="body">
          {this.props.children && this.props.children}
          {treeData.length > 0 && (
            <Tree showLine autoExpandParent defaultExpandAll {...this.props.tree} onSelect={this.props.onSelect}>
              {treeData.map((item, index) => {
                return this.getItem(item, 1, index, treeData.length);
              })}
            </Tree>
          )}
        </div>
        {this.props.trigger !== false && (
          <ContextMenuLayout
            id="tree-manage-trigger"
            itemTrigger={itemTrigger}
            onTriggerShow={e => this.onTriggerShow(e)}
            onTriggerHide={() => this.onTriggerHide()}
          />
        )}
      </Modal>
    );
  }
}

export default TreeManage;
