import { LoginProps, loginFetch, userInfoFetch } from "@/request";
import { errorHook, gHeaders } from "@/request/state";
import { UserInfo } from "@/request/type";
import { encodePwd } from "@/util";
import { ref } from "vue";

export const user = ref<UserInfo>();
export enum UserStatus {
  NOT_LOGIN,
  LOGINED,
  UNKNOWN,
}
export const userStatus = ref<UserStatus>(UserStatus.UNKNOWN);

export const login = async (props: LoginProps) => {
  const data = await loginFetch({
    ...props,
    password: encodePwd(props.password),
  });
  user.value = data.user;
  gHeaders.token = data.token;
  localStorage.setItem("token", data.token);
  await getUserInfo();
};

export const logout = () => {
  localStorage.removeItem("token");
  userStatus.value = UserStatus.NOT_LOGIN;
};

export const getUserInfo = async () => {
  user.value = await userInfoFetch();
  userStatus.value = UserStatus.LOGINED;
};

errorHook.push((code) => {
  if (code === 4008) {
    logout();
  }
});
const token = localStorage.getItem("token");
if (token) {
  gHeaders.token = token;
  getUserInfo();
} else {
  userStatus.value = UserStatus.NOT_LOGIN;
}
