Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

76 linhas
2.4 KiB

  1. import { defineStore } from 'pinia'
  2. import { getToken, setToken, getUser, setUser, clearAuth } from '@/utils/auth.js'
  3. import { userApi } from '@/api/index.js'
  4. export const useUserStore = defineStore('user', {
  5. state: () => ({
  6. token: '',
  7. userInfo: {},
  8. balance: 0, // 统一可用点数
  9. balanceDetail: {} // 后端原始余额明细 { points, gpt3_balance, gpt4_balance, mj_balance }
  10. }),
  11. getters: {
  12. isLogin: (state) => !!state.token,
  13. // 兼容后端多种字段命名
  14. nickname: (state) => state.userInfo.nick_name || state.userInfo.nickname || state.userInfo.user_name || 'AI在线用户',
  15. avatar: (state) => state.userInfo.head_url || state.userInfo.avatar || '',
  16. // 点数展示文案
  17. pointsText: (state) => (state.balance < 0 ? '不限' : String(state.balance))
  18. },
  19. actions: {
  20. /** 从本地存储恢复登录态(App 启动时调用) */
  21. restore() {
  22. this.token = getToken()
  23. this.userInfo = getUser()
  24. },
  25. /** 登录成功后写入 */
  26. setLogin({ token, userInfo }) {
  27. this.token = token || ''
  28. this.userInfo = userInfo || {}
  29. setToken(this.token)
  30. setUser(this.userInfo)
  31. },
  32. /** 拉取最新用户信息 */
  33. async fetchUserInfo() {
  34. const res = await userApi.getInfo()
  35. this.userInfo = res.data || {}
  36. setUser(this.userInfo)
  37. return this.userInfo
  38. },
  39. /**
  40. * 拉取点数余额。
  41. * 后端返回新版点数 points,同时兼容旧资源包 { gpt3_balance, gpt4_balance, mj_balance }。
  42. * 个人中心优先展示新版点数;旧接口未合并时才回退到旧资源包合计。
  43. */
  44. async fetchBalance() {
  45. const res = await userApi.getBalance()
  46. const detail = res.data || {}
  47. this.balanceDetail = detail
  48. if (detail.points !== undefined || detail.point_balance !== undefined) {
  49. this.balance = Number(detail.points !== undefined ? detail.points : detail.point_balance) || 0
  50. return this.balance
  51. }
  52. const { gpt3_balance = 0, gpt4_balance = 0, mj_balance = 0 } = detail
  53. if ([gpt3_balance, gpt4_balance, mj_balance].some((v) => v <= -9999)) {
  54. this.balance = -1 // 不限
  55. } else {
  56. this.balance = gpt3_balance + gpt4_balance + mj_balance
  57. }
  58. return this.balance
  59. },
  60. /** 退出登录/登录失效,清空状态 */
  61. clear() {
  62. this.token = ''
  63. this.userInfo = {}
  64. this.balance = 0
  65. clearAuth()
  66. }
  67. }
  68. })