import { api } from './request' import { secureGet } from '@/utils/secure-storage' type EventName = | 'page_view' | 'login' | 'bind_phone' | 'health_data_input' | 'health_trend_view' | 'appointment_create' | 'appointment_detail' | 'followup_submit' | 'report_view' | 'article_view' | 'article_share' | 'medication_add' | 'family_add' | 'profile_edit' interface AnalyticsEvent { event: EventName | string properties?: Record timestamp: number userId?: string patientId?: string } const QUEUE_KEY = 'analytics_queue' const MAX_QUEUE_SIZE = 50 function getQueue(): AnalyticsEvent[] { return uni.getStorageSync(QUEUE_KEY) || [] } function setQueue(queue: AnalyticsEvent[]): void { uni.setStorageSync(QUEUE_KEY, queue.slice(-MAX_QUEUE_SIZE)) } export function trackEvent(event: EventName | string, properties?: Record): void { let userId: string | undefined try { const raw = secureGet('user_data') userId = raw ? JSON.parse(raw).id : undefined } catch { /* ignore */ } const patientId = uni.getStorageSync('current_patient_id') const evt: AnalyticsEvent = { event, properties, timestamp: Date.now(), userId, patientId } const queue = getQueue() queue.push(evt) setQueue(queue) } export function trackPageView(pageName: string, properties?: Record): void { trackEvent('page_view', { page: pageName, ...properties }) } export async function flushEvents(): Promise { const queue = getQueue() if (queue.length === 0) return const batch = queue.slice() setQueue([]) try { await api.post('/analytics/batch', { events: batch }) } catch { const current = getQueue() setQueue([...batch.slice(-MAX_QUEUE_SIZE + current.length), ...current]) } } export function getQueueSize(): number { return getQueue().length }