import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Dropdown } from 'amos-antd';
import './style.scss';
/**
 * 右键菜单
 *
 * @class RightClickMenu
 * @extends {Component}
 */
class ContextMenu extends Component {

  static propTypes = {
    children: PropTypes.any,
    style: PropTypes.object,
    onContextMenu: PropTypes.func,
    menu: PropTypes.any
  };

  static defaultProps = {
    menu: <div />,
    style: {}
  };

  constructor(props) {
    super(props);
    this.state = {
      show: false,
      left: 0,
      top: 0
    };
  }

  componentDidMount() {
    document.addEventListener('click', this._handleClick);
    document.addEventListener('contextmenu', this._handleGloabContextMenu);
    document.addEventListener('scroll', this._handleScroll);
  }

  componentWillUnmount() {
    document.removeEventListener('contextmenu', this._handleGloabContextMenu);
    document.removeEventListener('click', this._handleClick);
    document.removeEventListener('scroll', this._handleScroll);
  }

  _handleClick = (event) => {
    const { show } = this.state;
    const wasOutside = !(event.target.contains === this.root);

    if (wasOutside && show) {
      this.setState({ show: false });
    }
  };

  _handleScroll = () => {
    const { show } = this.state;

    if (show) {
      this.setState({ show: false });
    }
  };

  _handleGloabContextMenu = (e) => {
    this.setState({
      show: false, left: 0 , top: 0
    });
  }

  _handleContextMenu = (e) => {
    const _rect = e.currentTarget.getBoundingClientRect();
    const left = e.nativeEvent.clientX - _rect.left;
    const top = e.nativeEvent.clientY - _rect.top;
    const time = 100;
    this.props.onContextMenu && this.props.onContextMenu(e);
    clearTimeout(this.timer);
    this.setState({ show: false, left: 0 , top: 0 }, () => {
      this.timer = setTimeout(() => {
        this.setState({ show: true, left , top });
      }, time);
    });
    e.preventDefault();
  }

  render() {
    const { style = {} } = this.props;
    const { show, left, top } = this.state;
    return (
      <div ref={node => this.node = node} {...this.props} style={{ ...style, position: 'relative' }} onContextMenu={this._handleContextMenu}>
        { this.props.children }
        {
          this.props.menu && <Dropdown overlay={this.props.menu} visible={show} trigger={['click']} placement="bottomLeft">
            <span style={{ left, top, position: 'absolute' }} />
          </Dropdown>
        }
      </div>
    );
  }
}

export default ContextMenu;
