import React, { useEffect, useRef, useState } from 'react'
import { View } from '@tarojs/components'
import classNames from 'classnames'
import './style.scss'

export default (props) => {
  const { visible = false, closeOnClick = false, onClose, style = {}, aligin = 'center' } = props

  const mounted = useRef(false)
  const [show, setShow] = useState(false)
  const [addonClass, setAddonClass] = useState('')
  
  const layStyle = {
    ...style,
    alignItems: aligin === 'top' ? 'flex-start' : ( aligin === 'bottom' ? 'flex-end' : 'center' )
  }

  const handleClick = () => {
    if (closeOnClick) {
      onClose && onClose()
    }
  }

  useEffect(() => {
    if (visible) {
      setShow(true)

      // 异步触发动效
      const t = setTimeout(() => {
        setAddonClass('show')
        clearTimeout(t)          
      });
    } else {
      if (mounted.current) {
        setAddonClass('hide')

        // 如果监听动画事件会有闪屏
        const t = setTimeout(() => {
          setShow(false)
          clearTimeout(t)          
        }, 500);
      }
    }

    mounted.current = true
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible])

  return show ? (
    <View
      className={classNames('overlay-warpper', addonClass)}
      style={layStyle}
      onClick={handleClick}
    >
      <View>
        {props.children}
      </View>
    </View>
  ) : null
}
