import { SS, LS } from "storage";
import { loginIn, loginOut } from "@/service/network";
import progress from "@/service/progress";

// 声明KEY

const KEY_USER_ID = "mc_user_id"
const KEY_NAME = "mc_user_name"
const KEY_NICK_NAME = "mc_user_nick_name"
const KEY_DESC = "mc_user_description"
const KEY_AVATAR = "mc_user_avatar"

// states
const state = {
  // token
  token: SS.GET_TOKEN() ?? "",
  name: LS.GET(KEY_NAME) ?? "",
  nick: LS.GET(KEY_NICK_NAME) ?? "",
  avatar: LS.GET(KEY_AVATAR) ?? "",
  userId: LS.GET(KEY_USER_ID) ?? "",
  desc: LS.GET(KEY_DESC) ?? "",
};

// mutations
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
    if (token) SS.SET_TOKEN(token);
    else SS.REMOVE_TOKEN();
  },
  SET_NICK: (state, nick) => {
    state.nick = nick;
    if (nick) LS.SET(KEY_NICK_NAME, nick);
    else SS.REMOVE(KEY_NICK_NAME);
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
    if (avatar) LS.SET(KEY_AVATAR, avatar);
    else SS.REMOVE(KEY_AVATAR);
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId;
    if (userId) LS.SET(KEY_USER_ID, userId);
    else SS.REMOVE(KEY_USER_ID);
  },
  SET_DESC: (state, desc) => {
    state.desc = desc;
    if (desc) LS.SET(KEY_DESC, desc);
    else SS.REMOVE(KEY_DESC);
  },
  SET_NAME: (state, name) => {
    state.name = name;
    if (name) LS.SET(KEY_NAME, name);
    else SS.REMOVE(KEY_NAME);
  }
};

// actions
const actions = {
  // login in
  loginIn ({ commit }, payload) {
    return new Promise((resolve, reject) => {
      loginIn(payload).then(
        res => {
          // 登录成功, 更新状态
          commit("SET_TOKEN", res.data.user_id);
          commit("SET_NAME", res.data.name);
          commit("SET_AVATAR", res.data.avatar_url);
          commit("SET_USER_ID", res.data.user_id);
          resolve();
        },
        error => {
          reject(error);
        }
      );
    });
  },
  // login out
  loginOut ({ commit }) {
    return new Promise((resolve, reject) => {
      progress.dialogConfirm("退出登录", "即将登出账号, 点击确认登出").then(
        () => {
          loginOut().then(
            () => {
              // 登出成功, 更新状态
              resolve();
              commit("SET_TOKEN");
              commit("SET_NAME");
              commit("SET_AVATAR");
              commit("SET_USER_ID");
            },
            error => {
              reject(error);
            }
          );
        },
        error => {
          reject(error);
        }
      );
    });
  },
  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN");
      resolve();
    });
  },
  // update
  updateUser ({ commit }, payload) {
    commit("SET_TOKEN", payload.userid);
    commit("SET_NAME", payload.name);
    commit("SET_AVATAR", payload.avatar);
    commit("SET_USER_ID", payload.userid);
  },

};

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