import { useEffect, useState, useCallback } from 'react'; import { pointsApi, type PatientStatistics, type ConsultationStatistics, type FollowUpStatistics, type PointsStatistics, type HealthDataStats, type DialysisStatistics, } from '../../../api/health/points'; import { doctorApi } from '../../../api/health/doctors'; export interface StatsData { patientStats: PatientStatistics | null; consultationStats: ConsultationStatistics | null; followUpStats: FollowUpStatistics | null; pointsStats: PointsStatistics | null; healthDataStats: HealthDataStats | null; dialysisStats: DialysisStatistics | null; doctorCount: number; loading: boolean; error: string | null; refresh: () => void; } export function useStatsData(): StatsData { const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [patientStats, setPatientStats] = useState(null); const [consultationStats, setConsultationStats] = useState(null); const [followUpStats, setFollowUpStats] = useState(null); const [pointsStats, setPointsStats] = useState(null); const [healthDataStats, setHealthDataStats] = useState(null); const [dialysisStats, setDialysisStats] = useState(null); const [doctorCount, setDoctorCount] = useState(0); const fetchAllStats = useCallback(async () => { setLoading(true); setError(null); let hasAnyError = false; const errors: string[] = []; const tryFetch = async (fn: () => Promise, setter: (v: T) => void, label: string) => { try { const data = await fn(); setter(data); } catch { hasAnyError = true; errors.push(label); } }; await Promise.all([ tryFetch(pointsApi.getPatientStats, setPatientStats, '患者'), tryFetch(pointsApi.getConsultationStats, setConsultationStats, '咨询'), tryFetch(pointsApi.getFollowUpStats, setFollowUpStats, '随访'), tryFetch(pointsApi.getStatistics, setPointsStats, '积分'), tryFetch(pointsApi.getHealthDataStats, setHealthDataStats, '健康数据'), tryFetch(pointsApi.getDialysisStats, setDialysisStats, '透析'), tryFetch( async () => { const r = await doctorApi.list({ page: 1, page_size: 1 }); return r.total; }, setDoctorCount, '医护', ), ]); if (hasAnyError && errors.length === 7) { setError('加载统计数据失败'); } setLoading(false); }, []); useEffect(() => { fetchAllStats(); }, [fetchAllStats]); return { patientStats, consultationStats, followUpStats, pointsStats, healthDataStats, dialysisStats, doctorCount, loading, error, refresh: fetchAllStats, }; }