import { defineStore } from 'pinia' import { authApi, profileApi } from '../utils/api' export const useUserStore = defineStore('user', { state: () => ({ token: uni.getStorageSync('token') || '', nickname: '', avatarUrl: '', isVip: false, vipEndTime: null, referralCode: '', // Daily quota usedCharts: 0, maxCharts: 3, usedChats: 0, maxChats: 3, // Commission totalCommission: 0, availableCommission: 0 }), getters: { isLoggedIn: (state) => !!state.token, isVipActive: (state) => { if (!state.vipEndTime) return false return new Date(state.vipEndTime) > new Date() } }, actions: { async login(openid, nickname, avatarUrl, referralCode) { const data = { openid, nickname, avatarUrl } if (referralCode) data.referralCode = referralCode const res = await authApi.login(data) const tokenStr = res.token || res this.token = tokenStr uni.setStorageSync('token', tokenStr) this.nickname = nickname this.avatarUrl = avatarUrl }, async wechatLogin(code, nickname, avatarUrl) { const data = { code, nickname, avatarUrl } const res = await authApi.login(data) const tokenStr = res.token || res this.token = tokenStr uni.setStorageSync('token', tokenStr) this.nickname = nickname || `微信用户` this.avatarUrl = avatarUrl || '' // Fetch full profile after login try { await this.fetchProfile() } catch (e) {} }, async fetchProfile() { const user = await profileApi.info() this.nickname = user.nickname this.avatarUrl = user.avatarUrl this.referralCode = user.referralCode this.isVip = !!user.vipEndTime && new Date(user.vipEndTime) > new Date() this.vipEndTime = user.vipEndTime }, async fetchQuota() { try { const quota = await profileApi.quota() this.usedCharts = quota.dailyChartCount || 0 this.maxCharts = quota.chartLimit > 0 ? quota.chartLimit : 999 this.usedChats = quota.dailyChatCount || 0 this.maxChats = quota.chatLimit > 0 ? quota.chatLimit : 999 } catch (e) { /* ignore */ } }, async fetchCommissionSummary() { try { const summary = await profileApi.commissionSummary() this.totalCommission = summary.totalEarnings || 0 this.availableCommission = summary.availableBalance || 0 } catch (e) { /* ignore */ } }, logout() { this.token = '' this.nickname = '' this.avatarUrl = '' this.usedCharts = 0 this.usedChats = 0 this.totalCommission = 0 this.availableCommission = 0 uni.removeStorageSync('token') } } })