import { Component } from "react"
import ReactDOM from "react-dom"

export interface PortalContentProps {
  /**
   * 附加类名，此类名会增加到最外层的包含块上
   */
  className?: string
  /**
   * 当 Portal 的 children 被加入到 DOM 时的钩子
   */
  onChildrenMount?: () => void

  /**
   * children mounted to
   * @default document.body
   */
  container?: HTMLElement

  visible?: Boolean
}

class PortalContent extends Component<PortalContentProps> {
  container: Element | null | void = null

  timer: any

  // constructor(props) {
  //   super(props);

  //   const { getContainer } = this.props;
  //   this.container = getContainer && getContainer();
  // }

  componentDidMount() {
    this.createContainer()

    this.timer = setTimeout(() => {
      // getContainer 返回ref时，子组件首先执行 componentDidMount,此时ref还未赋值
      if (!this.container) {
        this.createContainer()
      }
    })
  }

  componentWillUnmount() {
    clearTimeout(this.timer)
  }

  createContainer() {
    // this.container = this.props
    this.forceUpdate()
  }

  render() {
    const { children } = this.props
    if (this.container) {
      return ReactDOM.createPortal(children, this.container)
    }
    return null
  }
}

export default PortalContent
