import {
  VuexModule,
  Module,
  getModule,
  Mutation,
  Action
} from "vuex-module-decorators";
import { auth } from "@/utils/cookies";
import { getUserInfo, getToken } from "@/api/user";
import store from "../index";

@Module({ dynamic: true, store, name: "user" })
class User extends VuexModule {
  public Token = auth.getToken() || "";
  public UserInfo: IUser | null = null;
  @Action
  public async getUserInfo() {
    const userInfo = await getUserInfo();
    if (!userInfo) return this.clear();
    this.set_UserInfo(userInfo);
  }
  @Mutation
  private set_UserInfo(userInfo: IUser | null) {
    this.UserInfo = userInfo;
  }
  @Mutation
  private set_token(token: string) {
    auth.setToken((this.Token = token));
  }
  @Action({ commit: "set_token" })
  public async setToken(login: ILogin) {
    return await getToken(login);
  }
  @Mutation
  public clear() {
    this.Token = "";
    this.UserInfo = null;
    auth.removeToken();
  }
}
export default getModule(User);
