import { Login } from "@/api/user";
import { getToken, setToken } from "@/utils/auth";

const getDefaultState = () => {
  return {
    token: getToken()
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    return (state.token = token);
  }
};

const actions = {
  login({ commit }) {
    return new Promise((resolve, reject) => {
      Login()
        .then(res => {
          if (res.code === 0) {
            const token = res.data;
            commit("SET_TOKEN", token);
            setToken(token);
            resolve();
          } else {
            reject(res);
          }
        })
        .catch(error => {
          reject(error);
        });
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
