import Vue from "vue";
import Vuex from "vuex";
import http from "../plugins/http";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    userInfo: null,
    roles: ["ROLE_USER"]
  },
  mutations: {
    updateUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    },
    updateRoles(state, roles) {
      state.roles = roles;
    }
  },
  actions: {
    getUserInfo(content) {
      return http.axios
        .get("/user/my")
        .then(res => {
          let roles = res.data.authorities.map(item => {
            return item.name;
          });
          content.commit("updateRoles", roles);

          content.commit("updateUserInfo", res.data);
          return Promise.resolve();
        })
        .catch(() => {
          localStorage.removeItem("token");
          return Promise.reject();
        });
    }
  }
});
