user.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import { defineStore } from 'pinia'
  2. import { authApi, profileApi } from '../utils/api'
  3. export const useUserStore = defineStore('user', {
  4. state: () => ({
  5. token: uni.getStorageSync('token') || '',
  6. nickname: '',
  7. avatarUrl: '',
  8. isVip: false,
  9. vipEndTime: null,
  10. referralCode: '',
  11. // Daily quota
  12. usedCharts: 0,
  13. maxCharts: 3,
  14. usedChats: 0,
  15. maxChats: 3,
  16. // Commission
  17. totalCommission: 0,
  18. availableCommission: 0
  19. }),
  20. getters: {
  21. isLoggedIn: (state) => !!state.token,
  22. isVipActive: (state) => {
  23. if (!state.vipEndTime) return false
  24. return new Date(state.vipEndTime) > new Date()
  25. }
  26. },
  27. actions: {
  28. async login(openid, nickname, avatarUrl, referralCode) {
  29. const data = { openid, nickname, avatarUrl }
  30. if (referralCode) data.referralCode = referralCode
  31. const res = await authApi.login(data)
  32. const tokenStr = res.token || res
  33. this.token = tokenStr
  34. uni.setStorageSync('token', tokenStr)
  35. this.nickname = nickname
  36. this.avatarUrl = avatarUrl
  37. },
  38. async wechatLogin(code, nickname, avatarUrl) {
  39. const data = { code, nickname, avatarUrl }
  40. const res = await authApi.login(data)
  41. const tokenStr = res.token || res
  42. this.token = tokenStr
  43. uni.setStorageSync('token', tokenStr)
  44. this.nickname = nickname || `微信用户`
  45. this.avatarUrl = avatarUrl || ''
  46. // Fetch full profile after login
  47. try { await this.fetchProfile() } catch (e) {}
  48. },
  49. async fetchProfile() {
  50. const user = await profileApi.info()
  51. this.nickname = user.nickname
  52. this.avatarUrl = user.avatarUrl
  53. this.referralCode = user.referralCode
  54. this.isVip = !!user.vipEndTime && new Date(user.vipEndTime) > new Date()
  55. this.vipEndTime = user.vipEndTime
  56. },
  57. async fetchQuota() {
  58. try {
  59. const quota = await profileApi.quota()
  60. this.usedCharts = quota.dailyChartCount || 0
  61. this.maxCharts = quota.chartLimit > 0 ? quota.chartLimit : 999
  62. this.usedChats = quota.dailyChatCount || 0
  63. this.maxChats = quota.chatLimit > 0 ? quota.chatLimit : 999
  64. } catch (e) { /* ignore */ }
  65. },
  66. async fetchCommissionSummary() {
  67. try {
  68. const summary = await profileApi.commissionSummary()
  69. this.totalCommission = summary.totalEarnings || 0
  70. this.availableCommission = summary.availableBalance || 0
  71. } catch (e) { /* ignore */ }
  72. },
  73. logout() {
  74. this.token = ''
  75. this.nickname = ''
  76. this.avatarUrl = ''
  77. this.usedCharts = 0
  78. this.usedChats = 0
  79. this.totalCommission = 0
  80. this.availableCommission = 0
  81. uni.removeStorageSync('token')
  82. }
  83. }
  84. })