import vueStore from "@/store";
import { sessionStore } from "@/store/sessionStore";
import { logicConfig } from "@/logicConfig";
import { userController } from "@/controller/userController";

export class authUtils {
  /**
   *  路由守卫, 每次路由跳转时验证登录
   * @param {*} to
   * @param {*} from
   * @param {*} next
   */
  async routerBeforeEach(to, from, next) {
    //访问登录页面时直接显示
    if (to.path == logicConfig.routerNameConfig.loginRouteName) {
      !vueStore.state.fromPath ? vueStore.commit("updateFromPath", "/") : "";
      next();
      return;
    }

    //如果sessionStore里没有用户ID，说明用户没有登录，此时跳转到登录页
    var userToken = sessionStore.userToken;
    if (!userToken) {
      vueStore.commit("updateFromPath", to.path);
      next({ path: logicConfig.routerNameConfig.loginRouteName });
      return;
    }

    //如果vueStore里存在用户token，说明已经缓存的有用户信息，不需要再次获取
    if (vueStore.state.user.id) {
      //更新面包屑数据
      vueStore.commit("updateBreadcrumbs", { to: to.path });
      var prefitxMenuImg = "/" + (window as any).__systemConf.baseRouteUrl + '/imgs/navigation/';
      var leftMenus = constructorMenu(vueStore.state.menus);
      vueStore.commit("updateMenus", leftMenus);
      return next();
    }
    let userInfoResult = await userController.getUserInfoById();

    if (userInfoResult.result != logicConfig.resultObj.success) {
      console.error("获取用户信息失败，原因：" + userInfoResult.message);
      return next({ path: logicConfig.routerNameConfig.loginRouteName });
    }

    var _userInfo = (userInfoResult.data || {}) as any;
    if (!_userInfo.id) {
      console.error("获取用户信息失败，原因：无效的用户ID");
      return next({ path: logicConfig.routerNameConfig.loginRouteName });
    }

    vueStore.commit("updateUser", {
      id: _userInfo.id,
      name: _userInfo.name,
    });

    var prefitxMenuImg = "/" + (window as any).__systemConf.baseRouteUrl + '/imgs/navigation/';
    var leftMenus = constructorMenu(_userInfo.menus || (window as any).__systemConf.menus);
    vueStore.commit("updateMenus", leftMenus);

    //更新面包屑数据
    vueStore.commit("updateBreadcrumbs", { to: to.path });

    var projects = [];
    _userInfo.projects.forEach((_c) => {
      projects.push({
        id: _c.projectId,
        name: _c.projectName,
        groupCode: _c.groupCode,
        groupName: _c.groupName,
      });
    });
    vueStore.commit("updateProjects", projects);
    vueStore.commit("layout/setProjects", projects);
    vueStore.commit("layout/setprojectId", projects[0].id);
    vueStore.commit("updateSelectProject", projects[0]);

    next();


    function constructorMenu(menus) {
      menus.forEach(_c => {
        if (_c.children && _c.children.length > 0) {
          _c.children = constructorMenu(_c.children);
        } else {
          _c.normalImg = prefitxMenuImg + _c.icon + '_white.png';
          _c.activeImg = prefitxMenuImg + _c.icon + '_yellow.png';
          _c.state = to.path == _c.path ? 'active' : 'normal';
        }
      });
      return menus;
    };

  }
}
