// import Vue from 'vue'
import router from "./router";
import request from '/src/helpers/request'
import { ElMessage } from "element-plus";
import { state } from "./state";
// import NProgress from "nprogress"; // progress bar
// import "nprogress/nprogress.css"; // progress bar style
import { getToken, removeToken } from "./utils/auth";
import qs from 'query-string'
// import getPageTitle from '@/utils/get-page-title'

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

const whiteList = ["/login"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // from.query = to.query
  // start progress bar
  // NProgress.start();
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      // 如果有token直接跳转到首页
      next({ path: "/" });

      // NProgress.done();
    } else {
      const hasGetUserInfo = state.user?.speakerId;
      // 有名字 说明有用户信息 跳走
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // 异步获取用户信息
          const roomUid = sessionStorage.getItem('roomUid')
          const roomDetail = await request.get('/api-web/imLiveBroadcastRoom/queryRoom', {
            params: {
              roomUid: roomUid
            }
          })
          state.user = roomDetail.data
          next({ ...to, replace: true });
        } catch (error: any) {
          // remove token and go to login page to re-login
          // await store.dispatch("user/resetToken");
          if (error.msg) {
            ElMessage.error(error.msg);
          }
          removeToken();
          next(`/login?${qs.stringify(to.query)}`);
          // 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?${qs.stringify(to.query)}`);
      // NProgress.done();
    }
  }
});

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