import { UserProfile } from '../types/index' import { api } from './api' const USER_KEY = 'wangquan_user' export async function login(): Promise { const { userInfo } = await api.login() wx.setStorageSync(USER_KEY, JSON.stringify(userInfo)) return userInfo } export function getCachedUser(): UserProfile | null { try { const raw = wx.getStorageSync(USER_KEY) return raw ? JSON.parse(raw) : null } catch { return null } } export async function requireLocation(): Promise<{ latitude: number; longitude: number }> { return new Promise((resolve, reject) => { wx.getLocation({ type: 'gcj02', success: res => resolve({ latitude: res.latitude, longitude: res.longitude }), fail: () => { wx.showModal({ title: '需要位置权限', content: '汪圈需要获取您的位置来显示附近的宠物,请在设置中开启位置权限', confirmText: '去设置', success: res => { if (res.confirm) wx.openSetting({}) reject(new Error('位置权限被拒绝')) }, }) }, }) }) } export async function chooseAndUploadMedia(count = 9): Promise { return new Promise((resolve, reject) => { wx.chooseMedia({ count, mediaType: ['image'], sourceType: ['album', 'camera'], maxDuration: 30, camera: 'back', success: async res => { try { wx.showLoading({ title: '上传中...', mask: true }) const uploads = res.tempFiles.map(f => { const ext = f.tempFilePath.split('.').pop() || 'jpg' const cloudPath = `posts/${Date.now()}_${Math.random().toString(36).slice(2)}.${ext}` return wx.cloud.uploadFile({ cloudPath, filePath: f.tempFilePath }) }) const results = await Promise.all(uploads) wx.hideLoading() resolve(results.map(r => r.fileID)) } catch (e) { wx.hideLoading() reject(e) } }, fail: reject, }) }) }