import { useUserStore } from '@/store'

const loginRoute = '/pages/user/login'

const isLogin = () => {
  const userStore = useUserStore()
  return userStore.isLogin
}

const navigateToInterceptor = {
  invoke({ url }: { url: string }) {
    const path = url.split('?')[0]
    const needLoginPages: string[] = []
    const isNeedLogin = needLoginPages.includes(path)
    if (!isNeedLogin) {
      return true
    }
    const hasLogin = isLogin()
    if (hasLogin) {
      return true
    }
    const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
    uni.navigateTo({ url: redirectRoute })
    return false
  },
}

export const routeInterceptor = {
  install() {
    uni.addInterceptor('navigateTo', navigateToInterceptor)
    uni.addInterceptor('reLaunch', navigateToInterceptor)
    uni.addInterceptor('redirectTo', navigateToInterceptor)
    uni.addInterceptor('switchTab', navigateToInterceptor)
  },
}
