/*
 * @Author: your name
 * @Date: 2021-07-15 09:33:39
 * @LastEditTime: 2021-07-16 14:21:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \evm-store\tools\frontend\src\store\modules\frontend-login.js
 */
import Cookies from "js-cookie";
import api from "@/utils/request";

const TokenKey = "Authorization";

const state = {
  mobile: "",
  token: null,
  userinfo: {},
  // checkMobile: {
  //     mobile: '',
  //     data: '',
  // },
};

const actions = {
  async ["logoutClean"](
    {
      commit,
      rootState: {
        route: { path },
      },
    },
    config
  ) {
    const {
      data: { code, data },
    } = await api.post("/auth/clean", { ...config });
    if (code === "0") {
      commit("removeAuthToken");
    }
  },
  setToken({ commit }, token) {
    commit("setToken", token);
  },
  removeToken({ commit }) {
    commit("removeToken");
  },
  setUserInfo({ commit }, userinfo) {
    commit("setUserInfo", userinfo);
  },
  removeUserInfo({ commit }, userinfo) {
    commit("removeUserInfo", userinfo);
  },
};

const mutations = {
  ["receiveAuthToken"](state, payload) {
    Cookies.set(TokenKey, payload.access_token, {
      expires: payload.expires_in / 86400,
    });
  },
  ["removeAuthToken"](state) {
    Cookies.remove(TokenKey);
  },
  ["receiveMobile"](state, payload) {
    state.mobile = payload;
  },
  setToken: (state, token) => {
    state.token = token;
    Cookies.set(TokenKey, token);
  },
  removeToken: (state, token) => {
    state.token = null;
    Cookies.remove(TokenKey, token);
  },
  setUserInfo: (state, name) => {
    state.userinfo = name;
    Cookies.set("userinfo", name);
  },
  removeUserInfo: (state, name) => {
    state.userinfo = null;
    Cookies.remove("userinfo", name);
  },
};

const getters = {
  ["getMobile"](state) {
    return state.mobile;
  },
  ["getToken"](state) {
    return state.token;
  },
  ["getUserInfo"](state) {
    return state.userinfo;
  },
};

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