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

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

export const isSuper = computed(() => user.value ? user.value.roles.filter(item => item.roleKey === "super_admin").length > 0 : false)

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

export const logout = async (isLogin = false) => {
  isLogin && await loginOutFetch();
  isLogin && localStorage.setItem("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();
  }
});

export const logintAuth = getUserInfo;

const token = localStorage.getItem("token");
if (token) {
  gHeaders['relics-token'] = token;
} else {
  userStatus.value = UserStatus.NOT_LOGIN;
}
