// 头像逻辑:每个用户每天随机一次;支持自定义(自定义优先,长期保存) import { api } from '../api/index.js' function todayStr() { const d = new Date() return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}` } const customKey = (uid) => `xpx_avatar_custom_${uid}` const dailyKey = (uid) => `xpx_avatar_daily_${uid}` export function getCustomAvatar(uid) { try { return localStorage.getItem(customKey(uid)) || '' } catch (e) { return '' } } export function setCustomAvatar(uid, url) { try { if (url) localStorage.setItem(customKey(uid), url) else localStorage.removeItem(customKey(uid)) } catch (e) { /* ignore */ } } // 立即拉取一张随机头像并写入“当日缓存” export async function refreshDailyAvatar(uid) { const data = await api.getRandomAvatar() const url = data && data.url if (url) { try { localStorage.setItem(dailyKey(uid), JSON.stringify({ date: todayStr(), url })) } catch (e) { /* ignore */ } } return url || '' } // 解析当前应展示的头像:自定义优先;否则用当日缓存;当日无缓存则随机一次 export async function resolveDailyAvatar(uid) { const custom = getCustomAvatar(uid) if (custom) return custom try { const raw = localStorage.getItem(dailyKey(uid)) if (raw) { const obj = JSON.parse(raw) if (obj && obj.date === todayStr() && obj.url) return obj.url } } catch (e) { /* ignore */ } return await refreshDailyAvatar(uid) }