/**
 * Created by baoyinghai on 4/5/17.
 */
import React from 'react';

export default class DropMenu extends React.Component {

  _renderOtherBtns = () => {
    const btns = this.props.renderTopButtons;
    if (btns && btns.length > 1) {
      return (
        <ul className="menu-drop-list">
          {btns.slice(1).map((link, index) => <li key={'other-btn' + index}>{link}</li>)}
        </ul>
      );
    }
    return (
      <ul className="menu-drop-list">
        <li key={'other-btn'}><a>无其他操作</a></li>
      </ul>
    );
  };

  _switchHandler = e => {
    if (this.tag && this.tag.compareDocumentPosition(e.target) !== 20 && this.props.showOtherBtns) {
      const { moreBtnBlur } = this.props;
      moreBtnBlur && moreBtnBlur();
    }
  };

  componentDidMount() {
    const querySelector = this.props.querySelector;
    const tags = document.querySelectorAll('.' + querySelector + ' .menu-drop');
    if (tags.length > 0) {
      this.tag = tags[tags.length - 1];
    }
  }

  componentWillUnmount() {
    window.removeEventListener('click', this._switchHandler);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.showOtherBtns) {
      setTimeout(() => window.addEventListener('click', this._switchHandler));
    } else {
      window.removeEventListener('click', this._switchHandler);
    }
  }

  render() {
    return (
      <div className="menu-drop" style={this.props.style} onClick={this.props.moreBtnBlur}>
        {this._renderOtherBtns()}
      </div>
    );
  }

}

