import { getStorage, setStorage, removeStorage } from "../storage"; /** SDK 登录用户信息接口 */ export interface UserInfoInterface { token: string; user_name: string; reg_time: string; uid: number; openid: string; game_id: number; pop_content?: string; pop_title?: string; is_first_login?: boolean; is_reactive_user?: boolean; share_ext?:string; } const STORAGE_KEY = "userInfo"; const DEFAULT_INFO: UserInfoInterface = { token: "", user_name: "", reg_time: "", uid: 0, openid: "", game_id: 0, }; /** * SDK 登录用户信息模型 * 单例模式,自动从缓存加载/保存 */ class UserInfoModel { private static instance: UserInfoModel | null = null; private data: UserInfoInterface; private constructor() { // 从缓存加载数据 this.data = getStorage(STORAGE_KEY, DEFAULT_INFO) ?? DEFAULT_INFO; } static getInstance(): UserInfoModel { if (!UserInfoModel.instance) { UserInfoModel.instance = new UserInfoModel(); } return UserInfoModel.instance; } /** 获取用户信息 */ get(): UserInfoInterface { let launchOptions = wx.getLaunchOptionsSync(); let query = launchOptions.query; const share_ext = query.share_ext; this.data.share_ext = share_ext ? share_ext : ""; return this.data; } /** 保存用户信息到缓存 */ save(info: UserInfoInterface): boolean { this.data = info; return setStorage(STORAGE_KEY, info); } /** 更新部分用户信息 */ update(partial: Partial): boolean { this.data = { ...this.data, ...partial }; return setStorage(STORAGE_KEY, this.data); } /** 清除用户信息 */ clear(): boolean { this.data = { ...DEFAULT_INFO }; return removeStorage(STORAGE_KEY); } /** 是否已登录 */ isLoggedIn(): boolean { return !!this.data.token && this.data.uid > 0; } /** 获取 token */ getToken(): string { return this.data.token; } /** 获取 uid */ getUid(): number { return this.data.uid; } } export default UserInfoModel;