import { getUser } from './auth'; export interface FavoriteRecord { _id: string; userId: string; worksheetId: string; createdAt: string; worksheet?: { _id: string; title: string; subtitle: string; category: string; subcategory: string; path: string; ageMin: number; ageMax: number; difficulty: number; previewImg: string; tags: string[]; } | null; } /** * 添加收藏 */ export async function addFavorite(worksheetId: string): Promise { try { await getUser(); // 确保已登录 const res = await wx.cloud.callFunction({ name: 'userFavorites', data: { action: 'add', worksheetId }, }); const result = (res?.result as any) || {}; return result.code === 0; } catch (e) { console.error('addFavorite failed', e); return false; } } /** * 取消收藏 */ export async function removeFavorite(worksheetId: string): Promise { try { await getUser(); const res = await wx.cloud.callFunction({ name: 'userFavorites', data: { action: 'remove', worksheetId }, }); const result = (res?.result as any) || {}; return result.code === 0; } catch (e) { console.error('removeFavorite failed', e); return false; } } /** * 获取收藏列表 */ export async function getFavoriteList( page = 1, pageSize = 20, ): Promise { try { await getUser(); const res = await wx.cloud.callFunction({ name: 'userFavorites', data: { action: 'list', page, pageSize }, }); const result = (res?.result as any) || {}; return result.code === 0 ? result.data || [] : []; } catch (e) { console.error('getFavoriteList failed', e); return []; } } /** * 获取当前用户收藏总数 */ export async function getFavoriteCount(): Promise { try { await getUser(); const res = await wx.cloud.callFunction({ name: 'userFavorites', data: { action: 'count' }, }); const result = (res?.result as any) || {}; return result.code === 0 ? Number(result.data?.count || 0) : 0; } catch (e) { console.error('getFavoriteCount failed', e); return 0; } } /** * 检查是否已收藏 */ export async function checkFavorited(worksheetId: string): Promise { try { await getUser(); const res = await wx.cloud.callFunction({ name: 'userFavorites', data: { action: 'check', worksheetId }, }); const result = (res?.result as any) || {}; return result.code === 0 && result.data?.favorited; } catch (e) { console.error('checkFavorited failed', e); return false; } } /** * 批量检查是否已收藏,返回 { worksheetId: true } 的 map */ export async function batchCheckFavorited( worksheetIds: string[], ): Promise> { if (!worksheetIds.length) return {}; try { await getUser(); const res = await wx.cloud.callFunction({ name: 'userFavorites', data: { action: 'batchCheck', worksheetIds }, }); const result = (res?.result as any) || {}; return result.code === 0 ? result.data || {} : {}; } catch (e) { console.error('batchCheckFavorited failed', e); return {}; } }