import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import Icon from '../../icon';
// @require '../style/index.scss'
/**
 * 提示信息
 */
export default class Alert extends React.Component {

  static propTypes = {
    /**
     * 组件样式
     */
    style: PropTypes.object,
    /**
     * 选择器自定义类名
     */
    className: PropTypes.string,
    /**
     * 可包含子组件
     */
    children: PropTypes.any,
    /**
     * 消息类型
     */
    type: PropTypes.oneOf(['success', 'info', 'warning', 'danger', 'global', 'module']),
    /**
     * @transformable
     * 是否显示
     */
    visible: PropTypes.bool,
    /**
     * 是否可以关闭
     */
    closeable: PropTypes.bool,
    /**
     * 关闭时回调
     */
    onClose: PropTypes.func,
  };

  static defaultProps = {
    type: 'warning',
    visible: true,
    closeable: true
  };

  state = {
    visible: this.props.visible
  };

  componentWillReceiveProps(nextProps) {
    const { visible } = nextProps;
    this.setState({
      visible,
    });
  }

  close = () => {
    this.setState({
      visible: false
    });
    const { onClose } = this.props;
    if (onClose) {
      onClose();
    }
  };

  render() {
    const { className, style, children, closeable, type } = this.props;
    const { visible } = this.state;

    if (visible) {
      let style2 = Object.assign({}, style, closeable ? { paddingRight: '30px' } : {});
      let needAlertIcon = type === 'global' || type === 'module';

      return (
        <div
          className={classNames('im-alert', `im-alert-${type}`, className)}
          style={style2}
        >
          {needAlertIcon ? <Icon type="alert" /> : children}
          {needAlertIcon ? <span className="im-alert-module-multiline">{children}</span> : null}
          {closeable ? <Icon type="close" onClick={this.close} /> : null}
        </div>
      );
    }
    return null;
  }
}
