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'
import {removeToken} from "@/utils/auth";

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

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

router.beforeEach(async (to, from, next) => {
  // var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  // var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
  // // var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
  // var isIE = (navigator.appName == 'Microsoft Internet Explorer') || ((navigator.appName == 'Netscape') && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))
  // // var isEdge = userAgent.indexOf("Windows NT 6.1; Trident/7.0;") > -1 && !isIE; //判断是否IE的Edge浏览器
  // var isEdge = userAgent.indexOf("Edge") > -1; //判断是否IE的Edge浏览器
  // var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
  // var isSafari = userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1; //判断是否Safari浏览器
  // var isChrome = userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1 && !isEdge; //判断Chrome浏览器


  // start progress bar
  NProgress.start()
  // if (!isChrome) {
  //   if (to.path === '/404') {
  //     next()
  //   }
  //   else{
  //     //  把当前页面隐藏
  //     Message({
  //       message: '请使用Chrome内核的浏览器访问系统，如360、谷歌！',
  //       type: 'error',
  //       duration: 5 * 1000
  //     })
  //     removeToken()
  //     next('/404')
  //
  //   }
  //   NProgress.done
  // }
  // else{
  // }
  // set page title
  document.title = getPageTitle(to.meta.title)
  if (localStorage.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 => {
          if (to.path!=='/dashboard' && to.path!=='/user/profile'){
            let ff = false
            accessRoutes.map((item)=>{
              if (item.children){
                let fpath = item.path
                let Litem = item.children
                Litem.map((Citem)=>{
                  if (fpath+'/'+Citem.path==to.path){
                    ff = true
                  }
                })
              }
            })

            if (!ff){
              Message({
                  message: '越权访问页面不存在！',
                  type: 'error',
                  duration: 5 * 1000
              })
              const searchParams2 = {
                accessUrl: window.location.href
              }
              // 保存越权访问
              service.post('/sysPolicyController/brokenAccessControl', searchParams2).then((res) => {
                removeToken()
                next('/404') // 判断此跳转路由的来源路由是否存在，存在的情况跳转到来源路由，否则跳转到404页面
              }).catch((error) => {
                this.$message.error('越权访问记录出错' + error)
              })
            }
          }

          // 根据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(localStorage.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 {
            // 检测用户密码是否符合要求
            await service.get('/sysUserController/validatePasswordRule').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()
})
