// import Vue from 'vue'
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

let isOpen = false

router.onError((error) => {
  if (error instanceof Error) {
    const isChunkLoadFailed = error.name.indexOf('chunk')
    const targetPath = router.history.pending.fullPath;
    if (isChunkLoadFailed && !isOpen) {
      isOpen = true
      // console.log(router.app.$confirm)
      // router.push({ path: "/403", query: { path: targetPath } })
      router.app.$confirm("网站有更新请点击确定刷新页面?", "更新提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // router.replace(targetPath);
          location.hash = targetPath
          window.location.reload()
        })
        .catch(() => {
          return
        });
    }
  }
});

function getFirstMenu(routes) {
  let firstMenu = null
  routes.forEach(item => {
    if(!firstMenu && item.children.length > 0) {
      item.children.forEach(child => {
        if(!firstMenu && !child.hidden) {
          firstMenu = item.path + '/' + child.path
        }
      })
    }
  })
  return firstMenu
}


router.beforeEach(async (to, from, next) => {
  // from.query = to.query
  // start progress bar
  NProgress.start()
  // set page title
  // document.title = getPageTitle(to.meta.title)
  document.title = getPageTitle()
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果有tonken直接跳转到首页
        next({ path: '/' })

      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.name
      // 有名字 说明有用户信息 跳走
      if (hasGetUserInfo) {
        // const accessRoutes = await store.dispatch('permission/generateRoutes')

        // 动态添加可访问的路由
        // router.addRoutes(accessRoutes)
          next()
      } else {
        try {
          // 异步获取用户信息
          await store.dispatch('user/getInfo')
          // 请求接口 生成可访问路由
          const accessRoutes = await store.dispatch('permission/generateRoutes')
          // 动态添加可访问的路由
          router.addRoutes(accessRoutes)
          // 确保addroutes完整的hack方法
          // 设置replace:true，这样导航就不会留下历史记录。
          let firstMenu = getFirstMenu(accessRoutes)
          localStorage.setItem('firstMenuUrl', firstMenu)
          if(to.path == '/main/main') {
            next({ path: firstMenu, replace: true })
          } else {
            next({ ...to, replace: true })
          }
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    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`)
      NProgress.done()
    }
  }
})

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


