import React, { Component } from 'react'
import './index.scss'
import classnames from 'classnames'
import propTypes from 'prop-types'

class ClosablePopup extends Component {

  state = {
    visible: this.props.visible
  }

  close = () => {
    const {close} = this.props
    close ? close() : this.setState({visible: false})
  }

  componentDidUpdate(prevProps) {
    const {visible} = this.props
    if (prevProps.visible !== visible) {
      this.setState({
        visible
      })
    }
  }


  render() {
    const {title, className, children, closable = true} = this.props
    return (
      this.state.visible
        ?
        <div className={'closable-popup-mask'}>
          <div className={classnames(['popup-container', className])}>
            <div className="title">{title}</div>
            <div className="content">
              {children}
            </div>
            {
              closable && <i className={'close iconfont iconiconfront-2'} onClick={this.close}/>
            }
          </div>
        </div>
        : null
    )
  }
}

ClosablePopup.propTypes = {
  title: propTypes.string.isRequired,
  visible: propTypes.bool,
  closable: propTypes.string,
  close: propTypes.func
}

export default ClosablePopup
