import React, { Component } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Dialog from '../../dialog/src/DialogWrap';
import Button from '../../button/lib/Button';
import Icon from '../../icon/index';
// @require '../style/index.scss'
/**
 * 在body里生成 wrap element
 * 如果已经有了不会重复生成
 * @returns {Element}
 */
function mockWrap() {
  const WrapId = 'im-confirm-root';
  let wrap = window.document.getElementById(WrapId);
  if (wrap === null) {
    wrap = document.createElement('div');
    wrap.id = WrapId;
    document.body.appendChild(wrap);
  }
  return wrap;
}

/**
 * Confirm 操作确认
 */
class ConfirmWrap extends Component {

  static propTypes = {
    style: PropTypes.object,
    className: PropTypes.string,
    /**
     * 消息内容
     */
    children: PropTypes.any.isRequired,
    /**
     * 消息类型
     */
    type: PropTypes.oneOf(['info', 'success', 'alert', 'question']),
    /**
     * 当用户点 确定 时回调
     */
    onConfirm: PropTypes.func,
    /**
     * 当用户点 取消 时回调
     */
    onCancel: PropTypes.func,
  }

  static defaultProps = {}

  handleConfirm = () => {
    const { onConfirm } = this.props;
    if (typeof onConfirm === 'function') {
      onConfirm();
    }
    this.destroy();
  }

  handleCancel = () => {
    const { onCancel } = this.props;
    if (typeof onCancel === 'function') {
      onCancel();
    }
    this.destroy();
  }

  /**
   * 销毁自己
   */
  destroy = () => {
    unmountComponentAtNode(mockWrap());
  }

  render() {
    const { className, style, children, type } = this.props;
    return (
      <Dialog
        className={classnames('im-confirm', className)}
        style={style}
        title="确认操作"
        visible
        onClose={this.handleCancel}
        button={[
          <Button key="confirm" onClick={this.handleConfirm}>确定</Button>,
          <Button key="cancel" color="weak" onClick={this.handleCancel}>取消</Button>]}
      >
        <div className="im-confirm-icon"><Icon type={type} /></div>
        <div className="im-confirm-content">{children}</div>
      </Dialog>
    );
  }
}

/**
 * 显示出confirm
 * @param jsx 显示的消息内容
 * @param type 消息类型
 * @returns {Promise} 在用户点击 确定 时 resolve，取消 时 reject
 */
export default function (jsx, type = 'info') {
  return new Promise((resolve, reject) => {
    let wrapDom = mockWrap();
    let confirm = <ConfirmWrap type={type} onConfirm={resolve} onCancel={reject}>{jsx}</ConfirmWrap>;
    render(confirm, wrapDom);
  });
}
