import Vue from "vue";
import Vuex from "vuex";
import { login } from "@/api/login";
import { getToken, removeToken, setToken } from "../utils/auth";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: getToken(),
    user: ""
  },
  getters: {
    user: state => state.user
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_USER(state, payload) {
      state.user = payload;
    }
  },
  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(res => {
            setToken(res.data.userinfo.token);
            commit("SET_TOKEN", res.data.userinfo.token);
            commit("SET_USER", res.data.userinfo);
            resolve(res.data.userinfo);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    // 获取登录用户信息
    GetUser() {
      console.log(1111111);
    },
    // 登出
    Logout({ commit }) {
      removeToken();
      commit("SET_TOKEN", "");
      commit("SET_USER", "");
    }
  },
  modules: {}
});
