import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import router from './router'
import { getToken } from '@/utils/auth'
import { isHttp, isPathMatch } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import cache from '@/plugins/cache'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
import useVersionStore from '@/store/modules/version'
import useAppStore from '@/store/modules/app'

NProgress.configure({ showSpinner: false })

// 登录页，物流查询页
const whiteList = ['/login', '/logistics']

export const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true
        // 获取用户信息
        useUserStore().getInfo().then(() => {
          isRelogin.show = false
          // 获取路由表
          usePermissionStore().generateRoutes().then(accessRoutes => {
            // 获取版本信息
            useVersionStore().getVersion().then((res) => {
              // 生成可访问路由表
              accessRoutes.forEach(route => {
                console.log('挂载路由', route)
                if (!isHttp(route.path) ) {
                  router.addRoute(route)
                }
              })
              next({ ...to, replace: true })
            })
          })
        }).catch(err => {
          useUserStore().logOut().then(() => {
            ElMessage.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (isWhiteList(to.path)) {
      next()
    } else {
      if (to.fullPath.includes('jmreport')) {
        cache.session.set('redirect_uri', to.fullPath)
      }
      next(`/login?redirect=${to.fullPath}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
