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 { getBrowserToken } from './utils/commonFuc' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import {doEncrypt, doDecryptStr,doSign,doVerifySignature,userinfoEncrypt,userinfoDecrypt} from '@/utils/smutil'
import service from './utils/request'

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

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

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  if (sessionStorage.getItem('jy')) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/dashboard' })
      NProgress.done()
    } else {
      // 登录成功时将路由置空
      if (store.getters.permission_routes.length==0) {
        await store.dispatch('GenerateRoutes').then(accessRoutes => {
          // 根据roles权限生成可访问的路由表
          router.addRoutes(accessRoutes) // 动态添加可访问路由表
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
        }).catch(err => {
          store.dispatch('changeRouters',[])
          console.log('生成路由异常，输出routes:'+store.getters.permission_routes.length)
          next({ path: '/dashboard' })
        })
      }

      // 验证初始密码是否修改了或者超过30天
      if (to.path !=='/dashboard' && to.path !=='/user/profile'){
        // 用户信息解密
        // let decryptUserInfo = userinfoDecrypt(store.getters.userinfo)
        let decryptUserInfo = userinfoDecrypt(sessionStorage.getItem('active'))
        let user = JSON.parse(decryptUserInfo).sysUser
        if (user.lastUpdatePwdTime==null){
          Message({
            type: 'warning',
            message: '需要修改初始密码!'
          });
          next({ path: '/user/profile' })
        }
        else{
          var dateBegin = new Date(user.lastUpdatePwdTime);
          var dateEnd = new Date();
          var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
          var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
          if (dayDiff>=30){
            Message({
              type: 'warning',
              message: '密码超过30天需要修改!'
            })
            next({ path: '/user/profile' })
          }
          else {
            let sysTime2
            let lk2
            await service.get('/sysPolicyController/getLicenseKey').then((res) => {
              sysTime2 = res.data.sysTime
              lk2 = res.data.lk
            }).catch((error) => {
            })
            const searchParams2 = {
              sysTime: sysTime2,
              lk: lk2
            }
            // 检测用户密码是否符合要求
            await service.get('/sysUserController/validatePasswordRule', {params: searchParams2}).then((res) => {
              if (res.data != 'true'){
                Message({
                  type: 'warning',
                  message: '密码规则不符合当前系统设定，请重新修改密码!'+res.data
                })
                next({ path: '/user/profile' })
              }
              else{
                next()
              }
            }).catch((error) => {
              this.$message.error('检测密码规则出错' + error)
            })
          }
        }
      }
      else{
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      if (to.path === '/') {
        next('/login')
        NProgress.done()
      }else if (to.path === '/404') {
        next()
      }
      else{
        // 否则全部重定向到登录页
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

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