import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { addStyle } from 'dt2react';
import { Button } from 'amos-framework';
import AddView from './AddView';
import EditView from './EditView';

/**
 *
 * 右键菜单
 * @class componentName
 * @extends {Component}
 */
class ContextMenu extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false
    };
  }

  componentDidMount() {
    document.addEventListener('click', this._handleClick);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this._handleClick);
  }

  showMenu = (event, key) => {
    let { treeLocation } = this.props;
    const clickX = event.clientX;
    const clickY = event.clientY;
    addStyle(this.contextMenu, 'top', `${clickY - treeLocation.top - 50}px`);
    addStyle(this.contextMenu, 'left', `${clickX - treeLocation.left}px`);
    this.setState({ visible: true });
  };

  _handleClick = event => {
    const { visible } = this.state;
    const wasOutside = !(event.target.contains === this.contextMenu);
    if (wasOutside && visible) {
      this.setState({ visible: false });
    }
  };

  render() {
    let { visible } = this.state;
    let { selectedKeys, currentNode, editTreeData, addTreeData, onDelClick } = this.props;
    let showStyle = visible ? 'inline' : 'none';
    return (
      <div style={{ display: showStyle }} ref={node => (this.contextMenu = node)} className="contextMenu">
        <div className="contextMenu--option">
          <AddView selectedKeys={selectedKeys} addTreeData={addTreeData} />
        </div>
        <div className="contextMenu--option">
          <EditView currentNode={currentNode} selectedKeys={selectedKeys} editTreeData={editTreeData} />
        </div>
        <div className="contextMenu--option">
          <Button onClick={onDelClick}>删除视图</Button>
        </div>
      </div>
    );
  }
}

ContextMenu.propTypes = {
  treeLocation: PropTypes.object,
  selectedKeys: PropTypes.array,
  editTreeData: PropTypes.func,
  currentNode: PropTypes.object,
  addTreeData: PropTypes.func,
  onDelClick: PropTypes.func
};

export default ContextMenu;
