import Cookies from "js-cookie";
import { storageSession } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { request } from "./http";
import { setConfig } from "@/config";
export interface DataInfo<T> {
  /** token */
  token: string;
  userinfo: {
    account: string;
    nickname: string;
    is_super: boolean;
    permission: string[];
  };
  // /** `accessToken`的过期时间（时间戳） */
  // expires: T;
  // /** 用于调用刷新accessToken的接口时所需的token */
  // refreshToken: string;
  // /** 用户名 */
  // username?: string;
  // /** 当前登陆用户的角色 */
  // roles?: Array<string>;
}

export const sessionKey = "u-agency-info";
export const TokenKey = "authorized-agency-token";

/** 获取`token` */
export function getToken(): DataInfo<number> {
  // 此处与`TokenKey`相同，此写法解决初始化时`Cookies`中不存在`TokenKey`报错
  return Cookies.get(TokenKey)
    ? JSON.parse(Cookies.get(TokenKey))
    : storageSession().getItem(sessionKey);
}

/**
 * @description 设置`token`以及一些必要信息并采用无感刷新`token`方案
 * 无感刷新：后端返回`accessToken`（访问接口使用的`token`）、`refreshToken`（用于调用刷新`accessToken`的接口时所需的`token`，`refreshToken`的过期时间（比如30天）应大于`accessToken`的过期时间（比如2小时））、`expires`（`accessToken`的过期时间）
 * 将`accessToken`、`expires`这两条信息放在key值为authorized-token的cookie里（过期自动销毁）
 * 将`username`、`roles`、`refreshToken`、`expires`这四条信息放在key值为`user-info`的sessionStorage里（浏览器关闭自动销毁）
 */
export async function setToken(data: DataInfo<Date>) {
  return new Promise(async resolve => {
    let expires = 0;
    const { token } = data;
    console.log("token", token);

    expires = new Date(data?.expireIn || 0).getTime(); // 如果后端直接设置时间戳，将此处代码改为expires = data.expires，然后把上面的DataInfo<Date>改成DataInfo<number>即可
    const cookieString = JSON.stringify({ token, expires });
    Cookies.set(TokenKey, cookieString);
    // let response = await request.get("/backend/profile");
    // const profile = response?.data?.profile;
    // useUserStoreHook().SET_PROFILE(profile);
    // await getUserInfo(1);
    resolve();
  });
}

export async function getUserInfo(expires) {
  return new Promise(async resolve => {
    let response = await request.get("/mechanism/profile");
    const profile = response?.data?.profile;
    profile.mechanismName && setConfig({ Title: profile.mechanismName });
    useUserStoreHook().SET_PROFILE(profile);
    useUserStoreHook().SET_ISSTAFF(response.data.isStaff);

    resolve();

    // expires > 0
    //   ? Cookies.set(TokenKey, cookieString, {
    //       expires: (expires - Date.now()) / 86400000
    //     })
    //   : Cookies.set(TokenKey, cookieString);
    function setSessionKey(
      username: string,
      roles: Array<string>,
      account: string
    ) {
      useUserStoreHook().SET_USERNAME(username);
      useUserStoreHook().SET_ROLES(roles);
      useUserStoreHook().SET_PROFILE(profile);
      storageSession().setItem(sessionKey, {
        // refreshToken,
        expires,
        username,
        roles,
        profile
      });
    }

    if (profile?.nickname && profile?.permissions) {
      const { nickname, permissions } = profile;
      setSessionKey(nickname, permissions);
    } else {
      const nickname =
        storageSession().getItem<DataInfo<number>>(sessionKey)?.nickname ?? "";
      const permissions =
        storageSession().getItem<DataInfo<number>>(sessionKey)?.permissions ??
        [];
      setSessionKey(nickname, permissions);
    }
  });
}

/** 删除`token`以及key值为`user-info`的session信息 */
export function removeToken() {
  Cookies.remove(TokenKey);
  sessionStorage.clear();
}

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