import React from 'react'
import ReactDOM from 'react-dom'
import './index.scss'
import classnames from 'classnames'

function ClosablePopup({
                         title, content, className, closable = true, close = function () {
  }
                       } = {}) {

  function unmountComponent() {
    ReactDOM.unmountComponentAtNode(div)
    if (div && div.parentNode) {
      div.parentNode.removeChild(div)
    }
  }

  function _close() {
    let _c = close()
    if (_c && _c.then) {
      _c.then(() => {
        unmountComponent()
      })
    } else {
      unmountComponent()
    }
  }


  const closablePopup = (
    <div className={'closable-popup-mask'}>
      <div className={classnames(['popup-container', className])}>
        <div className="title">{title}</div>
        <div className="content">
          {content}
        </div>
        {
          closable && <i className={'close iconfont iconiconfront-2'} onClick={_close}/>
        }
      </div>
    </div>
  )
  const div = document.createElement('div')
  document.body.appendChild(div)


  ReactDOM.render(closablePopup, div)

  return {
    close: _close
  }
}

export default ClosablePopup
