import { loginApi, getUserInfoApi, loginOutApi } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
const state = {
  token: getToken(),
  userInfo: {}
};

const mutations = {
  SET_TOKEN(state, params) {
    state.token = params;
  },
  SET_USER_INFO(state, params) {
    state.userInfo = params;
  }
};

const actions = {

  /**
   * 用户登录
   * @param {Object} payload 参数 
   * @param {Function} commit 提交同步处理数据
   */
  userLogin({ commit },payload) {
    return new Promise((resolve, reject) => {

      // 登录api调用
      loginApi(payload).then(res => {
        // 获取token
        commit("SET_TOKEN", res.token);
        setToken(res.token);
        resolve(res);
      }).catch(err => {
        console.log(err);
        reject(err);
      });

    });
  },

  /**
  * 根据token 获取用户信息
  * @param {Object} payload 参数 
  * @param {Function} commit 提交同步处理数据
  */
  getUserInfo({ commit },payload) {
    return new Promise((resolve, reject) => {

      // 用户信息api调用
      getUserInfoApi().then(res => {
        // 获取token
        commit("SET_USER_INFO", res.data);
        resolve(res);
      }).catch(err => {
        console.log(err);
        removeToken();
        reject(err);
      });

    });
  },

  /**
    * 退出登录
    */
  loginOut() {
    return new Promise((resolve, reject) => {

      // 退出登录api调用
      loginOutApi().then(res => {
        // 获取token
        commit("SET_TOKEN", "");
        removeToken();
        resolve(res);
      }).catch(err => {
        console.log(err);
        removeToken();
        reject(err);
      });

    });
  }

};

const getters = {

};

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