import { defineStore } from 'pinia' import { ref, computed } from 'vue' import * as api from '@/api/user' import { API_BASE } from '@/config' export const useUserStore = defineStore('user', () => { const userInfo = ref(null) const loading = ref(false) const nickname = computed(() => { return userInfo.value?.nickname || uni.getStorageSync('xc:nickname') || '小菜' }) const avatarUrl = computed(() => { const filename = userInfo.value?.avatar_url || uni.getStorageSync('xc:avatar_url') || '' if (!filename) return '' // 已是完整 URL(http/blob)直接返回 if (filename.startsWith('http') || filename.startsWith('blob:')) return filename // 拼接:API_BASE + /user/avatar/ + 文件名 return `${API_BASE}/user/avatar/${filename}` }) async function fetchUserInfo() { loading.value = true try { userInfo.value = await api.getUserInfo() if (userInfo.value) { uni.setStorageSync('xc:nickname', userInfo.value.nickname) uni.setStorageSync('xc:avatar_url', userInfo.value.avatar_url) } } catch (e) { console.error('[UserStore] fetchUserInfo error:', e) throw e } finally { loading.value = false } } async function updateProfile(nickname: string) { await api.updateNickname(nickname) if (userInfo.value) userInfo.value.nickname = nickname uni.setStorageSync('xc:nickname', nickname) } async function uploadAvatar(filePath: string) { const result = await api.uploadAvatar(filePath) if (userInfo.value) userInfo.value.avatar_url = result.avatar_url uni.setStorageSync('xc:avatar_url', result.avatar_url) return avatarUrl.value } return { userInfo, loading, nickname, avatarUrl, fetchUserInfo, updateProfile, uploadAvatar } })