import { getAllSysDict } from "@/api/sysDict";
import { setItem, getItem, removeAllItem } from "@/utils/storage";
import router from "@/router";
export default {
  namespaced: true,
  state: () => ({
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token;
      setItem(TOKEN, token);
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo;
    }
  },
  actions: {
    /*
     *登录请求动作
     */
    login(ctx, userInfo) {
      const { username, password } = userInfo;
      return new Promise((resolve, reject) => {
        login({
          username,
          password: md5(password)
        })
          .then((data) => {
            this.commit("user/setToken", data.token);
            // 保存登录时间
            setTimeStamp();
            resolve();
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /*
     * 获取用户信息
     */
    async getUserInfo(ctx) {
      const res = await getUserInfo();
      this.commit("user/setUserInfo", res);
      return res;
    },

    /*
     * 退出登录
     */
    async logout(ctx) {
      this.commit("user/setToken", "");
      this.commit("user/setUserInfo", {});
      removeAllItem();
      // 待补充 清理权限相关的配置
      router.push("/login");
    },

    /*
     * 获取 分页查询字典信息
     */
    async getAllSysDict(ctx, params) {
      const res = await getAllSysDict();
      return res;
    }
  }
};
