/*
  Toast组件
*/
import React, {useEffect, useRef, useState} from 'react'
import Icon from '../icon'
import {iconType} from './utils'
import './index.less'
interface ToastConfig {
  type: string
  content?: string | React.ReactNode
  duration?: number
  mask?: boolean
  position?: 'bottom' | 'middle' | 'top'
  contentStyle?: any
  top?: number
  id?: number
  messageType?: 'info' | 'fail' | 'success' | 'warn'
  onClose?(): void
  destroyDom?(key: number): void
}
const Toast: React.FC<ToastConfig> = (props: ToastConfig) => {
  const {
    type = 'info',
    content,
    duration = 3,
    top,
    mask = true,
    position = 'middle',
    contentStyle,
    id,
    messageType,
  } = props
  const timer = useRef<any>(null)
  const [showMast, setShowMast] = useState(false)
  const isDurationClose: string[] = ['loading', 'hide']
  const messageTop = position === 'top' && top ? {top: `${top}px`} : {}
  const toastClassName = `toast-${
    type === 'message' ? 'message' : mask ? 'mask' : 'no-mask'
  } ${position}`
  useEffect(() => {
    setShowMast(true)
    if (!isDurationClose.includes(type)) {
      timer.current = setTimeout(() => {
        hide()
      }, 1000 * duration)
    }
  }, [props])
  useEffect(() => {
    setShowMast(true)
    if (isDurationClose.includes(type)) {
      if (type === 'hide') {
        hide()
      }
    } else {
      timer.current = setTimeout(() => {
        hide()
      }, 1000 * duration)
    }
  }, [type])
  const hide = () => {
    setShowMast(false)
    if (timer.current) {
      clearTimeout(timer.current)
    }
    props?.onClose?.()
    props?.destroyDom?.(id!)
  }
  const iconRender = messageType && <Icon className="icon-type" name={iconType[messageType]} />
  if (!showMast) return <div />
  return (
    <span className={toastClassName} style={messageTop}>
      <div
        className={`toast-box${typeof content === 'string' ? ' center' : ''}`}
        style={contentStyle}>
        {iconRender}
        <div className="toast-content">
          {type === 'loading' ? content || 'Loading...' : content}
        </div>
      </div>
    </span>
  )
}

export default Toast
