import { storageLocal } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";

export interface UserInfo {
  /** 用户名 */
  username: string;
  /** 用户性别 */
  gender: number;
  /** 用户昵称 */
  nickname?: string;
  /**用户邮箱 */
  email?: string;
  /**用户手机号 */
  phone?: string;
  /**用户角色 */
  roles?: Array<string>;
  /**用户权限 */
  permissions?: Array<string>;
  /**用户部门ID */
  department_id?: string;
  /**用户头像 */
  avatar?: string;
  /**用户数据库ID */
  id?: string;
}

export const userTokenKey = "user-token";

export const userInfoKey = "user-info";

export interface UserToken {
  /**
   * 用户Token
   */
  accessToken: string;
  /**
   * 过期时间（时间戳）
   */
  expiresTime: number;
  /**
   *  用于调用刷新accessToken的接口时所需的token
   */
  refreshToken: string;
}

/**存储用户Token信息 */
export function setToken(data: UserToken) {
  useUserStoreHook().SET_ACCESSTOKEN(data.accessToken);
  useUserStoreHook().SET_REFRESHTOKEN(data.refreshToken);
  useUserStoreHook().SET_EXPIRES(data.expiresTime);
  storageLocal().setItem(userTokenKey, data);
}

/**存储用户信息 */
export function setUserInfo(data: UserInfo) {
  useUserStoreHook().SET_AVATAR(data.avatar);
  useUserStoreHook().SET_USERNAME(data.username);
  useUserStoreHook().SET_NICKNAME(data.nickname);
  useUserStoreHook().SET_EMAIL(data.email);
  useUserStoreHook().SET_PHONE(data.phone);
  useUserStoreHook().SET_DEPARTMENT_ID(data.department_id);
  useUserStoreHook().SET_ROLES(data.roles);
  useUserStoreHook().SET_PERMISSIONS(data.permissions);
  useUserStoreHook().SET_ID(data.id);
  useUserStoreHook().SET_GENDER(data.gender);
  storageLocal().setItem(userInfoKey, data);
}

/** 删除`token`以及key值为`user-info`的localStorage信息 */
export function removeToken() {
  storageLocal().removeItem(userTokenKey);
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return "Bearer " + token;
};

/**
 * 获取Token信息
 * @returns
 */
export function getTokenInfo(): {
  isRefresh: boolean;
  isExpire: boolean;
  accesstoken: string;
  refreshToken: string;
} {
  const userStore = useUserStoreHook();
  const expires = userStore?.expires ?? 0;
  const now = Date.now();
  const diff = expires - now / 1000;
  const accessToken = userStore?.accessToken ?? "";
  const refreshToken = userStore?.refreshToken ?? "";

  if (diff > 0) {
    return {
      isRefresh: diff <= 1800000,
      isExpire: false,
      accesstoken: accessToken,
      refreshToken: refreshToken
    };
  } else {
    return {
      isRefresh: true,
      isExpire: true,
      accesstoken: accessToken,
      refreshToken: refreshToken
    };
  }
}
