import { defineStore } from 'pinia' import { getToken, setToken, getUser, setUser, clearAuth } from '@/utils/auth.js' import { userApi } from '@/api/index.js' export const useUserStore = defineStore('user', { state: () => ({ token: '', userInfo: {}, balance: 0, // 统一可用点数 balanceDetail: {} // 后端原始余额明细 { points, gpt3_balance, gpt4_balance, mj_balance } }), getters: { isLogin: (state) => !!state.token, // 兼容后端多种字段命名 nickname: (state) => state.userInfo.nick_name || state.userInfo.nickname || state.userInfo.user_name || 'AI在线用户', avatar: (state) => state.userInfo.head_url || state.userInfo.avatar || '', // 点数展示文案 pointsText: (state) => (state.balance < 0 ? '不限' : String(state.balance)) }, actions: { /** 从本地存储恢复登录态(App 启动时调用) */ restore() { this.token = getToken() this.userInfo = getUser() }, /** 登录成功后写入 */ setLogin({ token, userInfo }) { this.token = token || '' this.userInfo = userInfo || {} setToken(this.token) setUser(this.userInfo) }, /** 拉取最新用户信息 */ async fetchUserInfo() { const res = await userApi.getInfo() this.userInfo = res.data || {} setUser(this.userInfo) return this.userInfo }, /** * 拉取点数余额。 * 后端返回新版点数 points,同时兼容旧资源包 { gpt3_balance, gpt4_balance, mj_balance }。 * 个人中心优先展示新版点数;旧接口未合并时才回退到旧资源包合计。 */ async fetchBalance() { const res = await userApi.getBalance() const detail = res.data || {} this.balanceDetail = detail if (detail.points !== undefined || detail.point_balance !== undefined) { this.balance = Number(detail.points !== undefined ? detail.points : detail.point_balance) || 0 return this.balance } const { gpt3_balance = 0, gpt4_balance = 0, mj_balance = 0 } = detail if ([gpt3_balance, gpt4_balance, mj_balance].some((v) => v <= -9999)) { this.balance = -1 // 不限 } else { this.balance = gpt3_balance + gpt4_balance + mj_balance } return this.balance }, /** 退出登录/登录失效,清空状态 */ clear() { this.token = '' this.userInfo = {} this.balance = 0 clearAuth() } } })