/**
 * imui.DialogWrap
 * @author jero
 * @date 2016-07-28
 *
 */
import React, { Component } from 'react';
import ReactDom from 'react-dom';
import PropTypes from 'prop-types';
import Dialog from './Dialog';
// @require '../style/index.scss'
const renderSubtreeIntoContainer = ReactDom.unstable_renderSubtreeIntoContainer;

class DialogWrap extends Component {
  static propTypes = {
    style: PropTypes.object,
    className: PropTypes.string,
    /**
     * 是否出现遮罩
     */
    mask: PropTypes.bool,
    /**
     * 是否可见
     */
    visible: PropTypes.bool,
    /**
     * 宽度
     */
    width: PropTypes.number,
    /**
     * 关闭后的回调
     */
    onClose: PropTypes.func,
    /**
     * 关闭之前的回调，返回 false 可以阻止关闭
     */
    onBeforeClose: PropTypes.func,
    /**
     * 是否支持ESC键关闭
     */
    supportESC: PropTypes.bool,
    /**
     * 标题，可为空
     */
    title: PropTypes.node,
    /**
     * 副标题，可为空
     */
    subTitle: PropTypes.node,
    /**
     * z-index，大于 -1 生效
     */
    zIndex: PropTypes.number,
    /**
     * 按钮，请使用 imui.Button
     */
    button: PropTypes.arrayOf(PropTypes.element),
    /**
     * 是否显示右上角的 x
     */
    closeable: PropTypes.bool,
    /**
     * 大小模式
     */
    size: PropTypes.oneOf(['small', 'medium', 'large']),
    /**
     * 消息类型
     * - 传值时：渲染为Tips组件，可以用于指定tip等级
     * - 未传值：需要使用子组件(children)指定弹窗展示内容
     */
    type: PropTypes.oneOf(['info', 'success', 'alert', 'question']),
    /**
     * 消息内容, 与type配合使用
     */
    msg: PropTypes.string,
    /**
     * 消息内容副标题, 与msg配合使用
     */
    subMsg: PropTypes.string,
  };

  static defaultProps = {
    mask: true, // 是否遮罩
    visible: false, // 是否可见
    onClose() {}, // 关闭之后的回调
    onBeforeClose() {}, // 关闭之前的回调，返回 false 可以阻止关闭
    supportESC: false, // 支持ESC键关闭
    title: '', // 标题，可为空
    // zIndex: 1050,
    button: [], // 按钮，请使用 imui.Button
    closeable: true, // 是否显示右上角的 x
    size: 'small',
  };

  componentDidMount() {
    const body = document.body;
    const container = this.container = document.createElement('div');
    container.className = 'im-dialog-root';
    body.appendChild(container);

    this.renderDialog(this.props);
  }

  componentWillReceiveProps(props) {
    this.renderDialog(props);
  }

  componentWillUnmount() {
    this.container.parentNode.removeChild(this.container);
  }

  renderDialog(p) {
    const { children, ...props } = p;

    renderSubtreeIntoContainer(this,
      <Dialog
        {...props}
      >
        {children}
      </Dialog>, this.container);
  }

  render() {
    return null;
  }
}

export default DialogWrap;
