import { CARD_VIEW_HISTORY_KEY } from '../constants/storage'; import type { CardViewRecord, Lawyer } from '../types/card'; function normalizeLawyerSnapshot(input: unknown): Lawyer | undefined { if (!input || typeof input !== 'object') { return undefined; } const lawyer = input as Partial; if (typeof lawyer.id !== 'string' || !lawyer.id) { return undefined; } return { id: lawyer.id, name: typeof lawyer.name === 'string' ? lawyer.name : '', title: typeof lawyer.title === 'string' ? lawyer.title : '', office: typeof lawyer.office === 'string' ? lawyer.office : '', phone: typeof lawyer.phone === 'string' ? lawyer.phone : '', email: typeof lawyer.email === 'string' ? lawyer.email : '', address: typeof lawyer.address === 'string' ? lawyer.address : '', avatar: typeof lawyer.avatar === 'string' ? lawyer.avatar : '', coverImage: typeof lawyer.coverImage === 'string' ? lawyer.coverImage : '', specialties: Array.isArray(lawyer.specialties) ? lawyer.specialties.filter((item): item is string => typeof item === 'string') : [], bio: typeof lawyer.bio === 'string' ? lawyer.bio : '', wechatQrImage: typeof lawyer.wechatQrImage === 'string' ? lawyer.wechatQrImage : '', }; } export function getCardViewHistory(): CardViewRecord[] { const raw = wx.getStorageSync(CARD_VIEW_HISTORY_KEY); if (!Array.isArray(raw)) { return []; } return raw .map((item) => { const record = item as { lawyerId?: unknown; viewedAt?: unknown; lawyer?: unknown }; const lawyerId = typeof record.lawyerId === 'string' ? record.lawyerId : ''; const viewedAt = typeof record.viewedAt === 'number' ? record.viewedAt : 0; const lawyer = normalizeLawyerSnapshot(record.lawyer); return { lawyerId, viewedAt, lawyer }; }) .filter((item) => Boolean(item.lawyerId) && item.viewedAt > 0) .sort((a, b) => b.viewedAt - a.viewedAt); } export function appendCardViewRecord(lawyer: Lawyer): void { if (!lawyer.id) { return; } const current = getCardViewHistory().filter((item) => item.lawyerId !== lawyer.id); current.unshift({ lawyerId: lawyer.id, viewedAt: Date.now(), lawyer, }); wx.setStorageSync(CARD_VIEW_HISTORY_KEY, current); } export function clearCardViewHistory(): void { wx.removeStorageSync(CARD_VIEW_HISTORY_KEY); }