xiangqinxiaochengxu/miniprogram/pages/profile/profile.js
2026-05-18 14:24:55 +08:00

100 lines
2.6 KiB
JavaScript

const request = require('../../utils/request')
const { resolveImageUrl, resolveImageList } = require('../../utils/media')
function addCacheVersion(url, version) {
if (!url) {
return ''
}
const joiner = url.includes('?') ? '&' : '?'
return `${url}${joiner}v=${encodeURIComponent(version)}`
}
function normalizeAvatarState(userInfo) {
const profileImages = resolveImageList(userInfo.profile_images)
return {
...userInfo,
avatar_url: resolveImageUrl(userInfo.avatar_url || ''),
avatar_blur_url: resolveImageUrl(userInfo.avatar_blur_url || ''),
profile_images: profileImages
}
}
Page({
data: {
loading: false,
userInfo: null,
auditTextMap: {
0: '未提交',
1: '待审核',
2: '已通过',
3: '已驳回'
}
},
onShow() {
this.refreshFromCache()
this.loadProfile(true)
},
async loadProfile(silent = false) {
if (!silent) {
this.setData({ loading: true })
}
try {
const userInfo = await request({ url: '/users/me' })
this.applyUserInfo(userInfo)
wx.setStorageSync('profile_page_cache', normalizeAvatarState(userInfo))
} catch (err) {
console.error('Load profile failed:', err)
if (!this.data.userInfo) {
this.setData({ userInfo: null })
}
} finally {
if (!silent) {
this.setData({ loading: false })
}
}
},
applyUserInfo(userInfo) {
const avatarVersion = Date.now().toString()
const normalized = normalizeAvatarState(userInfo)
const previewImage = normalized.profile_images && normalized.profile_images.length
? normalized.profile_images[0]
: normalized.avatar_url
this.setData({
userInfo: {
...normalized,
avatar_url: addCacheVersion(normalized.avatar_url, avatarVersion),
avatar_blur_url: addCacheVersion(normalized.avatar_blur_url, avatarVersion),
previewImage: addCacheVersion(previewImage || '', avatarVersion),
nicknameText: normalized.nickname || '未设置昵称',
auditStatusText: this.data.auditTextMap[normalized.audit_status] || '未知'
}
})
},
refreshFromCache() {
const cached = wx.getStorageSync('profile_page_cache')
if (cached) {
this.applyUserInfo(cached)
}
},
goEdit() {
wx.navigateTo({ url: '/pages/profile-edit/profile-edit' })
},
goAudit() {
wx.navigateTo({ url: '/pages/audit-status/audit-status' })
},
goMyActivities() {
wx.navigateTo({ url: '/pages/my-activities/my-activities' })
},
goMyMatches() {
wx.navigateTo({ url: '/pages/my-matches/my-matches' })
}
})