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 userId = sessionStore.userId;
    if (!userId) {
      vueStore.commit("updateFromPath", to.path);
      next({ path: logicConfig.routerNameConfig.loginRouteName });
      return;
    }

    //如果vueStore里存在用户ID，说明已经缓存的有用户信息，不需要再次获取
    if (vueStore.state.user.id) {
      //更新面包屑数据
      vueStore.commit("updateBreadcrumbs", { to: to.path });
      return next();
    }

    let userControllerInstance = new userController();
    let userInfoResult = await userControllerInstance.getUserInfoById();

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

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

    vueStore.commit("updateUser", {
      id: _userInfo.userId,
      name: _userInfo.userName,
    });
    vueStore.commit("updateMenus", (window as any).__systemConf.menus);

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

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

    next();
  }
}
