import { user } from '../mutation-types';
import { login } from '@/api/user';
import { setToken, getToken, removeToken } from '@/utils/auth';
import { resetRouter } from '@/router';

const getDefaultSate = () => {
  const token = getToken();

  return {
    access_token: token?.access_token ?? '',
    session_id: token?.session_id ?? '',
    user_code: token?.user_code ?? '',
    user_real_name: token?.user_real_name ?? '',
    user_type: token?.user_type ?? '',
    user_name: token?.user_name ?? '',
    image_url: token?.image_url ?? '',
    language_type: token?.language_type ?? 'ZH',
    popedom_code_list: token?.popedom_code_list ?? [],
  };
};

const state = getDefaultSate();

const mutations = {
  [user.RESET_STATE]: (state) => {
    Object.assign(state, getDefaultSate());
  },
  [user.SET_USER_INFO]: (
    state,
    { user_code, user_real_name, user_type, language_type, session_id, image_url, popedom_code_list, access_token },
  ) => {
    state.user_code = user_code;
    state.user_real_name = user_real_name;
    state.user_type = user_type;
    state.language_type = language_type;
    state.session_id = session_id;
    state.image_url = image_url;
    state.language_type = language_type || 'ZH';
    state.popedom_code_list = popedom_code_list;
    state.access_token = access_token;
  },
};

const actions = {
  // 登录
  login({ commit }, loginForm) {
    return new Promise((reslove, reject) => {
      login(loginForm)
        .then((response) => {
          setToken(response);
          commit(user.SET_USER_INFO, response);
          reslove();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // 用户退出
  signOut({ commit }) {
    return new Promise((resolve) => {
      removeToken();
      resetRouter();
      commit(user.RESET_STATE);
      resolve();
    });
  },

  enterSys({ commit }) {
    return new Promise((reslove) => {
      commit(user.RESET_STATE);
      reslove();
    });
  },
};

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