import { useState } from 'react'; import { useHealthStore } from '@/stores/health'; import { useAuthStore } from '@/stores/auth'; import { usePageData } from '@/hooks/usePageData'; import { getHealthThresholds, DEFAULT_THRESHOLDS, type HealthThreshold } from '@/services/health'; import { listPendingSuggestions, type AiSuggestionItem } from '@/services/ai-analysis'; import { listPatientAlerts } from '@/services/alert'; export type VitalType = 'blood_pressure' | 'heart_rate' | 'blood_sugar' | 'weight'; export const VITAL_TABS: { key: VitalType; label: string }[] = [ { key: 'blood_pressure', label: '血压' }, { key: 'heart_rate', label: '心率' }, { key: 'blood_sugar', label: '血糖' }, { key: 'weight', label: '体重' }, ]; export interface TrendPoint { date: string; value: number; } export function useHealthOverview() { const user = useAuthStore((s) => s.user); const todaySummary = useHealthStore((s) => s.todaySummary); const loading = useHealthStore((s) => s.loading); const refreshToday = useHealthStore((s) => s.refreshToday); const fetchTrend = useHealthStore((s) => s.getTrend); const [activeTab, setActiveTab] = useState('blood_pressure'); const [trendData, setTrendData] = useState([]); const [trendLoading, setTrendLoading] = useState(false); const [aiSuggestions, setAiSuggestions] = useState([]); const [thresholds, setThresholds] = useState(DEFAULT_THRESHOLDS); const [alertCount, setAlertCount] = useState(0); const loadTrend = async (type: VitalType) => { setTrendLoading(true); try { const indicatorMap: Record = { blood_pressure: 'systolic_bp_morning', heart_rate: 'heart_rate', blood_sugar: 'blood_sugar', weight: 'weight', }; const points = await fetchTrend(indicatorMap[type], '7d'); setTrendData(points); } catch (err) { console.warn('[health] 加载趋势数据失败:', err); setTrendData([]); } finally { setTrendLoading(false); } }; const loadAiSuggestions = async () => { try { const items = await listPendingSuggestions(); setAiSuggestions(items.slice(0, 3)); } catch { setAiSuggestions([]); } }; const loadAlertCount = async () => { const patientId = useAuthStore.getState().currentPatient?.id; if (!patientId) return; try { const res = await listPatientAlerts(patientId, { status: 'pending', page: 1, page_size: 1 }); setAlertCount(res.total ?? 0); } catch { setAlertCount(0); } }; const fetchData = async () => { const results = await Promise.allSettled([ refreshToday(), loadTrend(activeTab), loadAiSuggestions(), loadAlertCount(), getHealthThresholds().then((t) => { if (t.length > 0) setThresholds(t); }), ]); return results; }; usePageData(fetchData, { throttleMs: 5000, enablePullDown: true, enabled: !!user, }); const handleTabChange = (tab: VitalType) => { setActiveTab(tab); loadTrend(tab); }; return { user, todaySummary, loading, error: false, activeTab, trendData, trendLoading, aiSuggestions, thresholds, alertCount, handleTabChange, fetchData, }; }