import type { Router, RouteRecordRaw, RouteRecordName } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
import { useRouterStoreWithOut } from '@/stores/modules/async-router'
import type { AppRouter } from '@/router/config/index'
import { APP_VERSION } from '@/stores/modules/mutation-types'
import { info } from '@/config/index.ts'
import { init as beforeInit } from '@/router/guard/before.ts'

const allowName = ['Login', 'LoginView', '404']
const defaultRouter = '/'


export function _window(key: string) {
  if (window.hasOwnProperty('admin_config')) {
    //@ts-ignore
    return window.admin_config[key]
  }

  return null
}

// 版本校验
const checkVersion = () => {

}






export const setRouteGuard = (router:Router) => {
  router.beforeEach(async (to, from, next) => {
    window.document.title = `${to.meta.title as string} | ${info.title}`
    console.log('from', from)
    // beforeInit()
    // 校验版本
    // checkVersion()
    const userStore = useUserStore()
    const token = userStore.getToken()
    console.log('getToken', token)
    // token失效走退出
    // if (token && !userStore.validToken()) {
    //   // userStore.logout()
    // }

    //  无token
    // if(!token || token === '') {
    //   console.log(to.name && allowName.includes(to.name as string))
    //   if (to.name && allowName.includes(to.name as string)) {
    //     next()
    //   } else {
    //     // next({ path: '/login/index', query: { redirect: to.fullPath } })
    //     next()
    //   }
    // } else {
      console.log('toROuter', to)
      const routerStore = useRouterStoreWithOut()
      const nowRouter = routerStore.ROUTERS
      // 无角色, 重新初始化路由
      // if (!userStore.permissions?.length || (userStore.permissions?.length && !nowRouter.length))
      // if (!(userStore.permissions?.length && nowRouter.length)){
      // 结构化路由
      if (!(nowRouter.length)){
          await routerStore.loadRouter().then(res => {
            const addRoters:AppRouter[] = res
            console.log('addRoters', addRoters)
            // routerStore.setRouter(addRoters)
            addRoters.map((route)=> {
              router.addRoute(route as RouteRecordRaw)
            })
          })
          next({ path: to.fullPath, replace: true, query: to.query })
      } else {
        // const userInfo = userStore.USERINFO ? JSON.parse(userStore.USERINFO) : {}
        // console.log('userInfo', userInfo)
        // if ((token  || token !== '') && !userInfo.sysUserId) {
        //   userStore.getUserInfo()
        // }
          next()
          // if (to.path == '/') {
          //   next({ path: defaultRouter, replace: true, query: to.query })

          // } else {
          //   next()
          // }
        }
    // }
  })
}
