import React, { Component } from 'react';
import Icon from '../../icon/index';
import PropTypes from 'prop-types';
/**
 * MessageItem 消息item
 */
export default class MessageItem extends Component {
  static propTypes = {
    className: PropTypes.string,
    onRemove: PropTypes.func,
    children: PropTypes.any,
    direction: PropTypes.oneOf(['top', 'center', 'left', 'bottom', 'right']),
    duration: PropTypes.number,
    onClose: PropTypes.func,
    closable: PropTypes.bool,
  };

  static defaultProps = {
    zIndex: 4000,
    direction: 'top',
    onRemove() {},
    duration: 2,
    onClose() {},
    closable: false,
  };

  directionClass = `im-message-item-${this.props.direction}`;

  componentDidMount() {
    if (this.props.duration) {
      this.closeTimer = setTimeout(() => {
        this.close();
      }, this.props.duration * 1000);
    }
  }

  componentWillUnmount() {
    this.clearCloseTimer();
  }

  // 清除定时
  clearCloseTimer = () => {
    if (this.closeTimer) {
      clearTimeout(this.closeTimer);
      this.closeTimer = null;
    }
  };

  // message关闭时触发
  close = () => {
    this.clearCloseTimer();

    this.props.onRemove(this.props.mKey);
    // 需要保证清除了，才触发onclose，避免用户嵌套使用
    setTimeout(() => {
      this.props.onClose();
    }, 50);
  };

  render() {
    const props = this.props;
    const { className = '' } = this.props;
    const classNames = `im-message-item ${this.directionClass} ${className}`;
    return (
      <div
        className={classNames}
        style={{
          zIndex: props.zIndex,
        }}
      >
        {props.children}
        {props.closable ? (
          <a className="im-message-close" onClick={this.close}>
            <Icon type="close" />
          </a>
        ) : null}
      </div>
    );
  }
}
