import React, { useState, useEffect } from 'react'
import dayjs from 'dayjs'

interface ICountdownProps {
  countdown: number // 以秒为单位
  onTimeChange: () => void
}

// 倒计时
const Countdown: React.FC<ICountdownProps> = props => {
  const [countTime, setCountTime] = useState(props?.countdown ?? 0)
  const { onTimeChange } = props
  useEffect(() => {
    let timer: NodeJS.Timeout
    if (countTime > 0) {
      timer = setTimeout(() => {
        setCountTime(countTime => countTime - 1)
      }, 1000)
    }
    console.log(countTime)
    if (countTime === 1) {
      onTimeChange()
    }
    return () => clearTimeout(timer)
  }, [countTime])

  return <>{dayjs(countTime * 1000 - 28800000).format('mm:ss')}</>
}

export default Countdown
