import pagesJson from '@/pages.json'
const pagesConfig = pagesJson.pages

// 检查登录状态
function checkIsLoggedIn() {
  return !!uni.getStorageSync('token')
}

// 检查是否是代理
function checkIsAgent() {
  const agentInfo = uni.getStorageSync('agentInfo')
  return agentInfo?.isAgent
}

// 添加路由拦截器
function setupRouterGuard() {
  const methods = ['navigateTo', 'redirectTo', 'reLaunch', 'switchTab']

  methods.forEach(method => {
    uni.addInterceptor(method, {
      invoke(e) {
        const url = e.url.split('?')[0]
        const currentPageConfig = pagesConfig.find(page => '/' +page.path ===  url) // 根据路径查找 pages.json 中的配置


        // 检查是否需要登录
        if (currentPageConfig?.auth && !checkIsLoggedIn()) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })

          // 跳转到登录页
          uni.redirectTo({
            url: '/pages/login'
          })

          return false
        }

        // 检查是否需要代理身份
        if (currentPageConfig?.agent && !checkIsAgent()) {
          uni.navigateTo({
            url: '/pages/invitationAgentApply'
          })

          return false
        }

        return true
      },
      fail(err) {
        console.error('路由拦截器错误:', err)
        return false
      }
    })
  })
}

export { setupRouterGuard }
