import { jwtDecode } from 'jwt-decode';
import { acceptHMRUpdate, defineStore } from 'pinia';

interface BasicUserInfo {
  [key: string]: any;
  /**
   * 头像
   */
  avatar: string;
  /**
   * 用户昵称
   */
  realName: string;

  /**
   * 用户角色
   */
  roles?: string[];
  /**
   * 用户id
   */
  userId: string;

  /**
   * 用户名
   */
  username: string;
}
interface BasicTenantInfo {
  /**
   * 租户名称
   */
  name: string;
  /**
   * 租户Id
   */
  tenantId: string;
}

interface ApplicationInfo {
  /**
   * 刷新次数
   */
  refreshCount: number;
}

interface AccessState {
  /**
   * 应用信息
   */
  applicationInfo: ApplicationInfo | null;
  /**
   * 租户信息
   */
  tenant: BasicTenantInfo | null;

  /**
   * 用户信息
   */
  userInfo: BasicUserInfo | null;

  /**
   * 用户角色
   */
  userRoles: string[];
}

/**
 * @zh_CN 用户信息相关
 */
export const useUserStore = defineStore('core-user', {
  actions: {
    // 检验token是否过期
    checkUserLoginExpire(): boolean {
      try {
        const myToken = this.userInfo?.token;
        if (!myToken) return true;
        const decoded: any = jwtDecode(myToken || '');
        // 获取当前时间戳
        const currentTimeStamp = Date.now() / 1000;
        return currentTimeStamp >= decoded.exp;
      } catch {
        return true;
      }
    },
    setApplicationInfo(applicationInfo: ApplicationInfo) {
      this.applicationInfo = applicationInfo;
    },
    setTenantInfo(tenantInfo: BasicTenantInfo | null) {
      this.tenant = tenantInfo;
    },
    setUserInfo(userInfo: BasicUserInfo | null) {
      // 设置用户信息
      this.userInfo = userInfo;
      // 设置角色信息
      const roles = userInfo?.roles ?? [];
      this.setUserRoles(roles);
    },
    setUserRoles(roles: string[]) {
      this.userRoles = roles;
    },
  },
  persist: {
    // 持久化
    pick: ['userInfo', 'userRoles', 'tenant', 'applicationInfo'],
  },
  state: (): AccessState => ({
    applicationInfo: null,
    tenant: null,
    userInfo: null,
    userRoles: [],
  }),
});

// 解决热更新问题
const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useUserStore, hot));
}
