import { router } from './index.js'
import { getToken } from  '@/utils/auth'
import { useUsersStore } from "@/pinia/user.js";
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login', '/auth-redirect', '/bag-monitor'] // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  const store = useUsersStore()
  const hasToken = getToken('TOKEN')
  // start progress bar
  NProgress.start()
  if (hasToken) {
    if (to.path.includes('/login')) {
      if (to.path == '/login') {
        next()
      } else {
        next('/login')
      }
      NProgress.done()
    } else {
      const hasRoles = store.roles && store.roles.length > 0
      if (hasRoles) {
        if (from.path.includes('/login') || to.path.includes('/dashboard')) {
          next()
        } else {
          // 攀长特安全问题修复 未授权路由禁止跳转
          if (store.customerId == 138) {
            let hasPermission = false
            store.roles.forEach((i) => {
              let arr = to.path.split('/')
              if (arr[arr.length - 1] === i.url) {
                hasPermission = true
              }
            })
            if (hasPermission) {
              next()
            } else {
              Message.warning({
                type: 'warning',
                message: '没有访问权限,如果需要访问请联系管理员',
                duration: 2000
              });
              router.go(-1)
            }
          } else {
            next()
          }
        }
      } else {
        try {
          next()
        } catch (error) {
          console.log(error)
          // remove token and go to login page to re-login
          await store.resetToken()
        //   Message.warning(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      // next(`/login?redirect=${to.path}`)
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
    // finish progress bar
    NProgress.done()
  })
  