import router from './index';
import http from '@/api';
const whiteList = ['/login', '/login/qrcode', '/login/mobile', '/login/sunshineRun', '/analysis/index', '/analysis/detail'];
const routers = router.getRoutes().map((item) => {
  return item.path;
});
router.beforeEach(async (to, from, next) => {
  if (!routers.includes(to.path)) {
    //不在定义的路由列表里不能跳转
    next(false);
  }
  let token = localStorage.getItem('token');
  if (token) {
    //已登录
    // let myInfo:any = localStorage.getItem("userInfo");
    // let userInfo = JSON.parse(myInfo);
    // let dom = document.querySelectorAll('link');
    // for (let i = 0; i < dom.length; i++) {
    //   if (dom[i].rel === 'icon') {
    //     dom[i].href = userInfo?.logo_url || ''
    //   }
    // }
    if (to.path === '/login') {
      next({ path: '/' });
    } else if (to.path === '/login/qrcode') {
      next({ path: '/gesture' });
    } else if (to.path === '/login/sunshineRun') {
      next({ path: '/sunshineRun' });
    } else {
      //获取百度TTS的token
      http.common.baiduToken({}).then((res: any) => {
        let tok = res.token;
        localStorage.setItem('tok', tok);
      });
      next();
    }
  } else {
    //未登录
    let dom = document.querySelectorAll('link');
    for (let i = 0; i < dom.length; i++) {
      if (dom[i].rel === 'icon') {
        dom[i].href = ''
      }
    }
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
    } else {
      // 否则全部重定向到登录页
      if (to.path === '/gesture') {
        next(`/login/qrcode`);
      } else if (to.path === '/sunshineRun') {
        next(`/login/sunshineRun`);
      } else {
        next(`/login`);
      }
    }
  }
});
