import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN, ACCESS_EXPIRE } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import { allowList, homePage } from '@/config/router.config'
import defaultSettings from '@/config/defaultSettings'

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

const loginRoutePath = '/user/login'

let tokenTimer = null

router.beforeEach((to, from, next) => {
  const expire = storage.get(ACCESS_EXPIRE)
  // let token = storage.get(ACCESS_TOKEN)
  let token = sessionStorage.getItem(ACCESS_TOKEN);

  /* token 续订 start */
  const {
    renew: {open,interval}
  } = defaultSettings
  tokenTimer = null
  if (open) {
    tokenTimer = setInterval(() => {
      store.dispatch('Renew')
    }, interval)
  }
  /* token 续订 end */

  /* 国际化数据不存在时 从远程获取 start */
  if (store.getters.langData == null) {
    //  store.dispatch('getLangData')
  }
  /* 国际化数据不存在时 从远程获取 end */

  // start progress bar
  NProgress.start()
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
  /* has token and not expire */
  let isExpired = Number(expire) <= Date.now()
  if (token && !isExpired) {
    if (to.path === loginRoutePath) {
      /* when has token route to login back to homePage */
      next({ path: homePage })
    } else {
      // check login user.roles is null
      if (store.getters.userInfo == null) {
        // request login userInfo
        store
          .dispatch('GetInfo')
          .then(res => {
            const { menus } = store.getters
            // generate dynamic router
            store.dispatch('GenerateRoutes', { menus }).then((routers) => {
              // 动态添加可访问路由表
              //console.log(store.getters.addRouters)
              for (let x of routers) {
                router.addRoute(x)
              }
              //console.log(router.getRoutes())
              //在router4 中addRoutes方法过期
              //router.addRoutes(store.getters.addRouters)  
              // 请求带有 redirect 重定向时，登录自动重定向到该地址
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // set the replace: true so the navigation will not leave a history record
                next({ ...to, replace: true })
                NProgress.done()
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
            })
          })
          .catch(err => {
            // notification.error({
            //   message: '错误',
            //   description: '请求用户信息失败，请重试'
            // })

            // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
            store.dispatch('Logout').then(() => {
              next({ path: loginRoutePath, query: { redirect: to.fullPath } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      store.dispatch('Logout').then(() => {
        next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      })
      
    }
  }
})

router.afterEach((to, from) => {
  store.commit('SET_MENU_ID', to.meta.menuId) // set current menuId
  NProgress.done() // finish progress bar
})
