import { useEffect } from 'react'
import Taro from '@tarojs/taro'
import { useAuth } from './useAuth'

/**
 * 要求认证的hook
 * 如果用户未登录，则重定向到登录页
 */
export const useRequireAuth = () => {
  const { isLoggedIn, isLoading } = useAuth()

  useEffect(() => {
    if (!isLoading && !isLoggedIn) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1500
      })

      setTimeout(() => {
        Taro.redirectTo({
          url: '/pages/login/index'
        })
      }, 1500)
    }
  }, [isLoggedIn, isLoading])

  return { isLoggedIn, isLoading }
}