import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { isRelogin } from '@/config/axios/service'
import { getAccessToken } from '@/utils/auth'
import { useTitle } from '@/hooks/web/useTitle'
import { useNProgress } from '@/hooks/web/useNProgress'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { deleteUserCache } from '@/hooks/web/useCache'
import { useDictStoreWithOut } from '@/store/modules/dict'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import * as LoginApi from '@/api/login'
import * as authUtil from '@/utils/auth'

const { start, done } = useNProgress()

const { loadStart, loadDone } = usePageLoading()

const parseURL = (
  url: string | null | undefined
): { basePath: string; paramsObject: { [key: string]: string } } => {
  // 如果输入为 null 或 undefined，返回空字符串和空对象
  if (url == null) {
    return { basePath: '', paramsObject: {} }
  }

  // 找到问号 (?) 的位置，它之前是基础路径，之后是查询参数
  const questionMarkIndex = url.indexOf('?')
  let basePath = url
  const paramsObject: { [key: string]: string } = {}

  // 如果找到了问号，说明有查询参数
  if (questionMarkIndex !== -1) {
    // 获取 basePath
    basePath = url.substring(0, questionMarkIndex)

    // 从 URL 中获取查询字符串部分
    const queryString = url.substring(questionMarkIndex + 1)

    // 使用 URLSearchParams 遍历参数
    const searchParams = new URLSearchParams(queryString)
    searchParams.forEach((value, key) => {
      // 封装进 paramsObject 对象
      paramsObject[key] = value
    })
  }

  // 返回 basePath 和 paramsObject
  return { basePath, paramsObject }
}

// 路由不重定向白名单
const whiteList = [
  '/login',
  '/social-login',
  '/auth-redirect',
  '/bind',
  '/register',
  '/oauthLogin/gitee',
  '/dingding',
  '/deepoil'
]

const loginData = reactive({
  isShowPassword: false,
  captchaEnable: import.meta.env.VITE_APP_CAPTCHA_ENABLE !== 'false',
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE !== 'false',
  loginForm: {
    tenantName: '芋道源码',
    username: '',
    password: '',
    captchaVerification: '',
    rememberMe: false
  }
})
//获取租户ID
const getTenantId = async () => {
  if (loginData.tenantEnable) {
    const res = await LoginApi.getTenantIdByName(loginData.loginForm.tenantName)
    authUtil.setTenantId(res)
  }
}
// 路由加载前
router.beforeEach(async (to, from, next) => {
  start()
  loadStart()
  if (getAccessToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (to.fullPath.includes('portalLogin')) {
      // authUtil.removeToken()
      // deleteUserCache()
      const userStore = useUserStoreWithOut()
      await userStore.loginOut()
      await getTenantId()
      const res = await LoginApi.portalLogin({
        username: to.query.username
      })

      authUtil.setToken(res)
      const source = to.query.source
      if (source && source === 'zhly') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/iotmap' })
      }

      if (source && source === 'zhzq') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/iotmap' })
      }

      if (source && source === 'spzx') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/video_center/protocol' })
      }

      if (source && source === 'qhse') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/qhse/qhse_kanban' })
      }

      if (source && source === 'yyhy') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/operation-meeting/fill' })
      }

      next({ path: '/' })
    } else {
      console.time('permission:first-load')
      // 获取所有字典
      const dictStore = useDictStoreWithOut()
      const userStore = useUserStoreWithOut()
      const permissionStore = usePermissionStoreWithOut()
      if (!dictStore.getIsSetDict) {
        console.time('permission:dict:setDictMap')
        await dictStore.setDictMap()
        console.timeEnd('permission:dict:setDictMap')
      } else {
        console.timeLog('permission:first-load', 'dict cache hit')
      }

      if (!userStore.getIsSetUser) {
        console.log(from, to)
        isRelogin.show = true
        console.time('permission:user:setUserInfoAction')
        await userStore.setUserInfoAction()
        console.timeEnd('permission:user:setUserInfoAction')
        isRelogin.show = false
        // 后端过滤菜单
        console.time('permission:generateRoutes')
        await permissionStore.generateRoutes()
        console.timeEnd('permission:generateRoutes')
        console.time('permission:addRoutes')
        permissionStore.getAddRouters.forEach((route) => {
          router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
        })
        console.timeEnd('permission:addRoutes')
        const redirectPath = from.query.redirect || to.path
        // 修复跳转时不带参数的问题
        const redirect = decodeURIComponent(redirectPath as string)
        const { paramsObject: query } = parseURL(redirect)
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect, query }
        console.timeEnd('permission:first-load')
        next(nextData)
      } else {
        console.timeLog('permission:first-load', 'user cache hit')
        console.timeEnd('permission:first-load')
        next()
      }
    }
  } else {
    authUtil.removeToken()
    deleteUserCache()
    useUserStoreWithOut().resetState()
    if (to.query.username) {
      await getTenantId()
      const res = await LoginApi.portalLogin({
        username: to.query.username
      })

      authUtil.setToken(res)

      const source = to.query.source
      if (source && source === 'zhly') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/iotmap' })
      }

      if (source && source === 'zhzq') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/iotmap' })
      }

      if (source && source === 'spzx') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/video_center/protocol' })
      }

      if (source && source === 'qhse') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/qhse/qhse_kanban' })
      }

      if (source && source === 'qhse_nav') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/qhse/qhse_kanban' })
      }

      if (source && source === 'yyhy') {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
        next({ path: '/operation-meeting/fill' })
      }

      next({ path: '/index' })
    } else if (whiteList.indexOf(to.path) !== -1) {
      const code = to.query.code
      if (code) {
        debugger
        await getTenantId()
        const res = await LoginApi.socialLogin('20', typeof code === 'string' ? code : '', '22')
        authUtil.setToken(res)
        next({ path: 'index' })
      } else {
        next() // 正常导航
      }
      // next()
    } else {
      const source = to.query.source
      if (source) {
        sessionStorage.setItem('LOGIN_SOURCE', source as string)
      }
      if (source && source === 'zhly') {
        next(`/login?redirect=/iotmap`)
      } else if (source && source === 'zhzq') {
        next(`/login?redirect=/iotmap`)
      } else if (source && source === 'spzx') {
        next(`/login?redirect=/video_center/protocol`)
      } else if (source && source === 'qhse') {
        next(`/login?redirect=/qhse/qhse_kanban`)
      } else if (source && source === 'yyhy') {
        next(`/login?redirect=/operation-meeting/fill`)
      } else next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
  }
})

router.afterEach((to) => {
  useTitle(to?.meta?.title as string)
  done() // 结束Progress
  loadDone()
})
