import { isDef } from '@/utils/is'
import { useDebounceFn } from 'ahooks'
import { useContext, useEffect } from 'react'
import { FlowContext } from '../context'
import { Actions } from '../enum'
type LoadingOptions = {
  /** @name 延迟时间 */
  delay?: number
}
const useLoading = (opt: LoadingOptions = { delay: 500 }) => {
  const { flowState, dispatch } = useContext(FlowContext)
  const cancel = () => {
    dispatch({
      type: Actions.SET_FOLW_PROPS,
      payload: {
        canvasLoading: false
      }
    })
  }
  const { run: resetLoading, cancel: tryCancelDebounceFn } = useDebounceFn(cancel, {
    wait: opt.delay
  })
  useEffect(() => {
    return () => tryCancelDebounceFn()
  }, [])
  const run = () => {
    // 若当前loading为true停止执行
    if (isDef(flowState.canvasLoading) && flowState.canvasLoading) {
      return
    }
    dispatch({
      type: Actions.SET_FOLW_PROPS,
      payload: {
        canvasLoading: true
      }
    })
    resetLoading()
  }
  return { run }
}
export default useLoading
