/**
 * 用户令牌信息
 */
import { setCache, getCache } from '@/utils/cache';
import { loginByWxLoginCode, refreshToken } from '@/api/login';

export default {
  state: () => ({
    access_token: getCache('access_token') || '',
    refresh_token: getCache('refresh_token') || '',
  }),
  mutations: {
    SET_ACCESS_TOKEN(state, data) {
      state.access_token = data;
      setCache('access_token', state.access_token);
    },
    SET_REFRESH_TOKEN(state, data) {
      state.refresh_token = data;
      setCache('refresh_token', state.refresh_token);
    },
  },
  actions: {
    LoginByWxCode({ commit }, data) {
      return new Promise((resolve, reject) => {
        loginByWxLoginCode(data)
          .then(res => {
            if (res.access_token) {
              commit('SET_ACCESS_TOKEN', res.access_token);
              commit('SET_REFRESH_TOKEN', res.refresh_token);
              resolve();
            }
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    RefreshToken({ commit }, data) {
      return new Promise((resolve, reject) => {
        refreshToken(data)
          .then(res => {
            if (res.access_token) {
              commit('SET_ACCESS_TOKEN', res.access_token);
              commit('SET_REFRESH_TOKEN', res.refresh_token);
              resolve();
            }
          })
          .catch(err => {
            reject(err);
          });
      });
    },
  },
};
