import { login, logout, getInfo, userRouters } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import { Message } from "element-ui";
import AES from "@/utils/crypto";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: "",
    avatar: "",
    menuAuthority: [],
  };
};
//*:*:*
const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_MENU: (state, permissions) => {
    state.menuAuthority = permissions;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password, code, uuid } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        username: username.trim(),
        password: AES.encrypt(password, "1234567890abcdef"),
        code: code,
        uuid: uuid,
      })
        .then((response) => {
          if (response.code == 200) {
            localStorage.setItem("token", response.token);
            localStorage.setItem("userId", response.userId);
          } else {
            // localStorage.setItem("username",username)
            // localStorage.setItem("password",password)
            Message.error(response.msg);
            // setTimeout(() => {
            //   window.history.go(0)
            // }, 1000)
          }
          setTimeout(() => {
            resolve();
          }, 1000);
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  getMenu({ commit }) {
    return new Promise((resolve, reject) => {
      userRouters().then((res) => {
        if (res.code == 200) {
          commit("SET_MENU", res.data);
          resolve();
        }
      });
    });
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo().then((res) => {
        if (res.code == 200) {
          localStorage.setItem("id", res.user.id);

          commit("SET_NAME", res.user.userName);
          commit("SET_AVATAR", res.user.avatar);
          resolve(res.user);
        }
      });
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(localStorage.getItem("token"))
        .then(() => {
          removeToken(); // must remove  token  first
          resetRouter();
          commit("RESET_STATE");
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

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