/**
 * imui.DialogApi
 * @author moxhe
 * @date 2018-03-15
 */
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import DialogWrap from './DialogWrap';
import Button from '../../button/index';

class DialogApi extends Component {
  static propTypes = {
    okText: PropTypes.string,
    cancelText: PropTypes.string,
    zIndex: PropTypes.number,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
  };

  static defaultProps = {
    okText: '确定',
    cancelText: '',
    zIndex: 4000,
    onOk() {},
    onCancel() {},
    onClose() {},
  }

  chains = (fn) => {
    return () => {
      if (this.props.hideDialog) {
        this.props.hideDialog();
      }

      fn();
    };
  };

  getButtons = () => {
    const { chains } = this;
    const { okText, cancelText, onOk, onCancel } = this.props;
    const buttons = [
      <Button key="confirm" onClick={chains(onOk)}>{okText}</Button>,
    ];

    if (cancelText) {
      buttons.push(
        <Button key="cancel" color="weak" onClick={chains(onCancel)}>{cancelText}</Button>
      );
    }

    return buttons;
  }

  render() {
    const { className, type, button } = this.props;
    const buttons = typeof button === 'undefined' ? this.getButtons() : button;
    const cls = classnames(`im-dialog--${type}`, {
      [className]: !!className,
    });

    return (
      <DialogWrap {...this.props}
        className={cls}
        visible
        button={buttons}
        onClose={this.chains(this.props.onClose)}
      />
    );
  }
}

function showDialog(props, type) {
  const container = document.createElement('div');
  document.body.appendChild(container);

  const hideDialog = () => {
    ReactDOM.unmountComponentAtNode(container);
    if (container.remove) { // @fix don't support in IE
      container.remove();
    }
  };

  // 处理props参数
  if (type) {
    props.type = type;
    props.className = `im-dialog--api ${props.className || ''}`;
  } else {
    props.children = props.msg;
  }
  props.hideDialog = hideDialog;

  ReactDOM.render(<DialogApi {...props} />, container);

  return {
    remove: hideDialog,
    destroy: hideDialog,
  };
}

Object.assign(DialogWrap, {
  show(msg) {
    let props = typeof msg === 'string' ? { msg } : msg;

    return showDialog(props);
  },

  info(msg) {
    let props = typeof msg === 'string' ? { msg } : msg;

    return showDialog(props, 'info');
  },

  alert(msg) {
    let props = typeof msg === 'string' ? { msg } : msg;

    return showDialog(props, 'alert');
  },

  success(msg) {
    let props = typeof msg === 'string' ? { msg } : msg;

    return showDialog(props, 'success');
  },

  confirm(msg) {
    let props = typeof msg === 'string' ? { msg } : msg;

    props.cancelText = '取消';
    return showDialog(props, 'question');
  },
});

// module.exports = DialogWrap;
export default DialogWrap;
