| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import { defineStore } from 'pinia'
- import { ref, computed } from 'vue'
-
- export const useUserStore = defineStore('user', () => {
- const userId = ref(null)
- const userInfo = ref(null)
- const vipInfo = ref(null)
-
- // 获取VIP状态
- const isVIP = computed(() => {
- if (!vipInfo.value) return false
- return new Date(vipInfo.value.expireTime) > new Date()
- })
-
- // 用户登录
- const login = async (username, password) => {
- const res = await uni.request({
- url: 'https://api.aiyadianzi.ltd/auth/login',
- method: 'POST',
- data: { username, password }
- })
-
- userId.value = res.data.userId
- userInfo.value = res.data.userInfo
- vipInfo.value = res.data.vipInfo
-
- uni.setStorageSync('token', res.data.token)
- }
-
- // 购买VIP
- const purchaseVIP = async (plan) => {
- const res = await uni.request({
- url: 'https://api.aiyadianzi.ltd/vip/purchase',
- method: 'POST',
- data: {
- userId: userId.value,
- planId: plan.id
- },
- header: { Authorization: `Bearer ${uni.getStorageSync('token')}` }
- })
-
- vipInfo.value = {
- type: plan.type,
- expireTime: res.data.expireTime
- }
- }
-
- // 初始化用户
- const initUser = async () => {
- const token = uni.getStorageSync('token')
- if (!token) return
-
- try {
- const res = await uni.request({
- url: 'https://api.aiyadianzi.ltd/auth/profile',
- header: { Authorization: `Bearer ${token}` }
- })
-
- userId.value = res.data.userId
- userInfo.value = res.data.userInfo
- vipInfo.value = res.data.vipInfo
- } catch (err) {
- console.error('用户初始化失败', err)
- uni.removeStorageSync('token')
- }
- }
-
- return {
- userId,
- userInfo,
- vipInfo,
- isVIP,
- login,
- purchaseVIP,
- initUser
- }
- })
|