import React from "react";
import { createPortal } from "react-dom";
import { isBrowser } from "../Utils/utils";

import styles from "./Modal.less";

export interface ModalProps {
  visible: boolean;
  onCancel: (e: any) => void;
  container?: HTMLElement;
}

export class Modal extends React.PureComponent<ModalProps> {
  static hasShowWarning = false;

  render() {
    if (!isBrowser()) return null; // 服务端无需渲染下列代码，渲染也会出错
    const DEFAULT_CONTAINER: HTMLElement | null = document.getElementById(
      "container"
    );
    const { children, visible, onCancel, container } = this.props;
    let finalMountContainer: HTMLElement;
    if (!container) {
      if (!DEFAULT_CONTAINER) {
        if (!Modal.hasShowWarning) {
          Modal.hasShowWarning = true;
        }
        finalMountContainer = document.body;
      } else {
        if (!Modal.hasShowWarning) {
          Modal.hasShowWarning = true;
        }
        finalMountContainer = DEFAULT_CONTAINER;
      }
    } else {
      finalMountContainer = container;
    }
    return (
      visible &&
      createPortal(
        <div className={styles.wrapper}>
          <div className={styles.overlay} onClick={onCancel} />
          <div className={styles.container}>{children}</div>
        </div>,
        finalMountContainer
      )
    );
  }
}

export default Modal;
