import storage from "../../utils/storage";

const userInfo = storage.getAuth();

function translateOrToName(arr) {
  return arr.map((item) => {
    if (item.children && item.children.length) {
      item.children = translateOrToName(item.children);
    }
    return {
      ...item,
      or: item.name,
    };
  });
}
export default {
  namespaced: true,
  state: {
    userInfo: userInfo || {},
    username: userInfo.username || "",
    owner: userInfo.owner || "",
    roles: userInfo.roles || [],
    menus: [],
    resources: [],
  },
  getters: {
    auth: (state) => state.userInfo,
  },
  mutations: {
    SET_NAME(state, name) {
      state.username = name;
    },
    SET_OWNER(state, owner) {
      state.owner = owner;
    },
    SET_ROLES(state, roles) {
      state.roles = roles;
    },
    SET_MENUS(state, menus) {
      if (!menus.length) {
        // 在权限返回为空的时候给menus加一条空数据，防止下次路由进入再次空校验
        state.menus.push({});
      } else {
        state.menus = translateOrToName(menus);
      }
    },
    CLEAR_MENUS(state) {
      state.menus = [];
    },
    SET_RESOURCES(state, resources) {
      state.resources = translateOrToName(resources);
    },
  },
  actions: {
    setInfo({ commit }, authInfo) {
      if (typeof authInfo === "object") {
        commit("SET_NAME", authInfo.username);
        commit("SET_OWNER", authInfo.owner);
        commit("SET_ROLES", authInfo.roles);
        storage.setAuth(authInfo);
        storage.setToken(authInfo.token);
      }
    },
    setMenu({ commit }, menu) {
      commit("SET_MENUS", menu);
    },
    setResources({ commit }, resources) {
      commit("SET_RESOURCES", resources);
    },
    logout({ commit }) {
      commit("SET_NAME", "");
      commit("SET_OWNER", "");
      commit("SET_ROLES", []);
      commit("CLEAR_MENUS", []);
      commit("SET_RESOURCES", []);
      storage.remove("auth");
      storage.remove("token");
    },
  },
};
