feat: 初始化孕育无忧全栈项目基础代码结构
完成项目初始搭建,包含后端FastAPI+MongoDB服务、前端React+Vite项目的完整基础结构,添加各类配置文件与依赖清单,涵盖核心业务初始框架。
This commit is contained in:
721
frontend/src/app/pages/AIAnalysisPage.tsx
Normal file
721
frontend/src/app/pages/AIAnalysisPage.tsx
Normal file
@@ -0,0 +1,721 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Heart,
|
||||
TrendingUp,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
Info,
|
||||
Calendar,
|
||||
Share2,
|
||||
Download,
|
||||
Sparkles,
|
||||
Activity,
|
||||
Baby,
|
||||
MessageCircle,
|
||||
FileText,
|
||||
X,
|
||||
Link2,
|
||||
Check,
|
||||
AlertTriangle,
|
||||
ShieldAlert,
|
||||
Loader2,
|
||||
Image as ImageIcon,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { generateAnalysis, type AnalysisResponse } from "../services/api";
|
||||
|
||||
export function AIAnalysisPage() {
|
||||
const navigate = useNavigate();
|
||||
const { reportId } = useParams();
|
||||
const [showShareSheet, setShowShareSheet] = useState(false);
|
||||
const [linkCopied, setLinkCopied] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [analysisData, setAnalysisData] = useState<AnalysisResponse | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!reportId) return;
|
||||
setLoading(true);
|
||||
generateAnalysis(reportId)
|
||||
.then((data) => setAnalysisData(data))
|
||||
.catch((err) => setError(err instanceof Error ? err.message : "加载失败"))
|
||||
.finally(() => setLoading(false));
|
||||
}, [reportId]);
|
||||
|
||||
const handleCopyLink = async () => {
|
||||
try {
|
||||
const shareUrl = `${window.location.origin}/share/${reportId}`;
|
||||
await navigator.clipboard.writeText(shareUrl);
|
||||
setLinkCopied(true);
|
||||
setTimeout(() => setLinkCopied(false), 2000);
|
||||
} catch (error) {
|
||||
console.error('复制失败:', error);
|
||||
// 降级方案:使用旧的复制方法
|
||||
const textArea = document.createElement('textarea');
|
||||
textArea.value = `${window.location.origin}/share/${reportId}`;
|
||||
textArea.style.position = 'fixed';
|
||||
textArea.style.left = '-999999px';
|
||||
document.body.appendChild(textArea);
|
||||
textArea.select();
|
||||
try {
|
||||
document.execCommand('copy');
|
||||
setLinkCopied(true);
|
||||
setTimeout(() => setLinkCopied(false), 2000);
|
||||
} catch (err) {
|
||||
alert('复制失败,请手动复制链接');
|
||||
}
|
||||
document.body.removeChild(textArea);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-12 h-12 text-morandi-400 animate-spin mx-auto mb-4" />
|
||||
<p className="text-gray-600 font-medium">AI 正在解读您的报告...</p>
|
||||
<p className="text-gray-400 text-sm mt-2">这可能需要几秒钟</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error || !analysisData) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<div className="text-center px-8">
|
||||
<AlertCircle className="w-12 h-12 text-red-400 mx-auto mb-4" />
|
||||
<p className="text-gray-800 font-medium mb-2">解读失败</p>
|
||||
<p className="text-gray-500 text-sm mb-4">{error || "未知错误"}</p>
|
||||
<Button onClick={() => navigate("/home")} variant="outline">返回首页</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case "normal":
|
||||
return {
|
||||
bg: "bg-morandi-sage-100",
|
||||
border: "border-morandi-sage-200",
|
||||
text: "text-morandi-sage-600",
|
||||
badge: "bg-morandi-sage-100 text-morandi-sage-600",
|
||||
icon: "text-morandi-sage-400",
|
||||
};
|
||||
case "attention":
|
||||
return {
|
||||
bg: "bg-morandi-rose-100",
|
||||
border: "border-morandi-200",
|
||||
text: "text-morandi-600",
|
||||
badge: "bg-morandi-rose-100 text-morandi-600",
|
||||
icon: "text-morandi-rose-400",
|
||||
};
|
||||
case "high":
|
||||
return {
|
||||
bg: "bg-red-50",
|
||||
border: "border-red-200",
|
||||
text: "text-red-700",
|
||||
badge: "bg-red-100 text-red-700",
|
||||
icon: "text-red-500",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
bg: "bg-gray-50",
|
||||
border: "border-gray-200",
|
||||
text: "text-gray-700",
|
||||
badge: "bg-gray-100 text-gray-700",
|
||||
icon: "text-gray-500",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const statusColors = getStatusColor(analysisData.overall_status);
|
||||
|
||||
// 指标状态颜色(紫色系色温区分:冷调sage→中性purple→暖调rose)
|
||||
const getIndicatorColor = (indicatorStatus: string) => {
|
||||
switch (indicatorStatus) {
|
||||
case "normal":
|
||||
return {
|
||||
bg: "bg-morandi-sage-100",
|
||||
border: "border-morandi-sage-200",
|
||||
text: "text-morandi-sage-600",
|
||||
badge: "bg-morandi-sage-100 text-morandi-sage-600",
|
||||
barBg: "bg-morandi-sage-200",
|
||||
barFill: "bg-morandi-sage-400",
|
||||
};
|
||||
case "borderline":
|
||||
return {
|
||||
bg: "bg-morandi-100",
|
||||
border: "border-morandi-200",
|
||||
text: "text-morandi-600",
|
||||
badge: "bg-morandi-200 text-morandi-700",
|
||||
barBg: "bg-morandi-200",
|
||||
barFill: "bg-morandi-400",
|
||||
};
|
||||
case "abnormal":
|
||||
return {
|
||||
bg: "bg-morandi-rose-100",
|
||||
border: "border-morandi-rose-300",
|
||||
text: "text-morandi-700",
|
||||
badge: "bg-morandi-rose-100 text-morandi-rose-400",
|
||||
barBg: "bg-morandi-rose-100",
|
||||
barFill: "bg-morandi-rose-400",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
bg: "bg-gray-50",
|
||||
border: "border-gray-200",
|
||||
text: "text-gray-700",
|
||||
badge: "bg-gray-100 text-gray-700",
|
||||
barBg: "bg-gray-100",
|
||||
barFill: "bg-gray-400",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const getRiskLabel = (riskLevel: string) => {
|
||||
switch (riskLevel) {
|
||||
case "low":
|
||||
return { label: "低风险", color: "bg-morandi-100 text-morandi-600" };
|
||||
case "medium":
|
||||
return { label: "中风险", color: "bg-morandi-rose-100 text-morandi-rose-400" };
|
||||
case "high":
|
||||
return { label: "高风险", color: "bg-morandi-rose-100 text-morandi-700" };
|
||||
default:
|
||||
return { label: "", color: "" };
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-20">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="flex items-center text-gray-600 hover:text-gray-900"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5 mr-1" />
|
||||
返回
|
||||
</button>
|
||||
<h1 className="font-semibold text-gray-800">AI 智能解读</h1>
|
||||
<button
|
||||
onClick={() => setShowShareSheet(true)}
|
||||
className="p-2 hover:bg-gray-100 rounded-lg"
|
||||
>
|
||||
<Share2 className="w-5 h-5 text-gray-600" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6 pb-20">
|
||||
{/* AI 解读标识 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex items-center justify-center gap-2 text-morandi-500"
|
||||
>
|
||||
<Sparkles className="w-5 h-5" />
|
||||
<span className="text-sm font-medium">AI 深度解读 · 个性化定制</span>
|
||||
</motion.div>
|
||||
|
||||
{/* 整体评估卡片 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<Card
|
||||
className={`${statusColors.bg} border-2 ${statusColors.border} rounded-3xl p-6 shadow-sm`}
|
||||
>
|
||||
<div className="flex items-start gap-4 mb-4">
|
||||
<div
|
||||
className={`w-16 h-16 ${statusColors.badge} rounded-2xl flex items-center justify-center flex-shrink-0`}
|
||||
>
|
||||
<Baby className={`w-8 h-8 ${statusColors.icon}`} />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h2 className="text-xl font-semibold text-gray-800">
|
||||
整体评估
|
||||
</h2>
|
||||
<Badge className={statusColors.badge}>
|
||||
{analysisData.overall_status === "normal"
|
||||
? "一切正常"
|
||||
: analysisData.overall_status === "attention"
|
||||
? "需要关注"
|
||||
: "需要重视"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className={`text-sm ${statusColors.text} mb-3 leading-relaxed`}>
|
||||
{analysisData.emotional_summary || analysisData.overall_summary}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-3 text-xs text-gray-600">
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-3 h-3" />
|
||||
<span>{new Date(analysisData.created_at).toLocaleDateString("zh-CN")}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 风险等级指示器 */}
|
||||
<div className="bg-white/50 backdrop-blur-sm rounded-2xl p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
综合风险评级
|
||||
</span>
|
||||
<span
|
||||
className={`text-sm font-semibold ${
|
||||
analysisData.risk_level === "low"
|
||||
? "text-morandi-sage-500"
|
||||
: analysisData.risk_level === "medium"
|
||||
? "text-morandi-600"
|
||||
: "text-red-600"
|
||||
}`}
|
||||
>
|
||||
{analysisData.risk_level === "low"
|
||||
? "低风险"
|
||||
: analysisData.risk_level === "medium"
|
||||
? "中风险"
|
||||
: "高风险"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-2 bg-gray-200 rounded-full overflow-hidden">
|
||||
<motion.div
|
||||
initial={{ width: 0 }}
|
||||
animate={{
|
||||
width:
|
||||
analysisData.risk_level === "low"
|
||||
? "25%"
|
||||
: analysisData.risk_level === "medium"
|
||||
? "60%"
|
||||
: "90%",
|
||||
}}
|
||||
transition={{ delay: 0.5, duration: 0.8 }}
|
||||
className={`h-full rounded-full ${
|
||||
analysisData.risk_level === "low"
|
||||
? "bg-morandi-sage-400"
|
||||
: analysisData.risk_level === "medium"
|
||||
? "bg-morandi-rose-400"
|
||||
: "bg-red-500"
|
||||
}`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 分类详情 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">详细解读</h2>
|
||||
|
||||
<div className="space-y-4">
|
||||
{analysisData.categories.map((category, index) => {
|
||||
const colors = getStatusColor(category.status);
|
||||
return (
|
||||
<motion.div
|
||||
key={category.category}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.3 + index * 0.1 }}
|
||||
>
|
||||
<Card className="bg-white rounded-3xl shadow-sm overflow-hidden border-0">
|
||||
{/* 分类头部 */}
|
||||
<div className={`${colors.bg} border-b-2 ${colors.border} p-5`}>
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div
|
||||
className={`w-10 h-10 ${colors.badge} rounded-xl flex items-center justify-center`}
|
||||
>
|
||||
<Activity className={`w-5 h-5 ${colors.icon}`} />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold text-gray-800">
|
||||
{category.category}
|
||||
</h3>
|
||||
</div>
|
||||
<Badge className={colors.badge}>
|
||||
{category.status === "normal"
|
||||
? "正常"
|
||||
: category.status === "attention"
|
||||
? "需关注"
|
||||
: "异常"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 指标详情 */}
|
||||
<div className="p-5 space-y-4">
|
||||
{category.indicators.map((item, itemIdx) => {
|
||||
const indicatorStatus = item.status === "normal" ? "normal" : item.status === "low" || item.status === "high" ? "abnormal" : "borderline";
|
||||
const indColors = getIndicatorColor(indicatorStatus);
|
||||
return (
|
||||
<div
|
||||
key={itemIdx}
|
||||
className={`${indColors.bg} border-2 ${indColors.border} rounded-2xl p-4`}
|
||||
>
|
||||
{/* 指标名称和数值 */}
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="flex-1">
|
||||
<h4 className="font-semibold text-gray-800 mb-1">
|
||||
{item.name}
|
||||
</h4>
|
||||
{item.nickname && (
|
||||
<p className="text-xs text-gray-500 mb-2">
|
||||
{item.nickname}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span
|
||||
className={`text-2xl font-semibold ${indColors.text}`}
|
||||
>
|
||||
{item.value}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500">
|
||||
{item.unit}
|
||||
</span>
|
||||
</div>
|
||||
{item.reference_range && (
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
参考范围:{item.reference_range}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-1.5">
|
||||
<div
|
||||
className={`px-3 py-1 ${indColors.badge} rounded-full flex items-center gap-1`}
|
||||
>
|
||||
{indicatorStatus === "normal" ? (
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
) : (
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
)}
|
||||
<span className="text-xs font-medium">
|
||||
{item.status === "normal" ? "正常" : item.status === "high" ? "偏高" : "偏低"}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 状态指示条 */}
|
||||
<div className="mb-3">
|
||||
<div className={`h-1.5 ${indColors.barBg} rounded-full overflow-hidden`}>
|
||||
<div
|
||||
className={`h-full ${indColors.barFill} rounded-full transition-all`}
|
||||
style={{
|
||||
width: indicatorStatus === "normal" ? "100%" : indicatorStatus === "borderline" ? "60%" : "30%",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 白话解释 */}
|
||||
<div className="space-y-3">
|
||||
{item.what_is_it && (
|
||||
<div className="bg-white/70 rounded-xl p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<Info className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-medium text-gray-700 mb-1">这是什么?</p>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">{item.what_is_it}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.baby_impact && (
|
||||
<div className="bg-white/70 rounded-xl p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<Baby className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-medium text-gray-700 mb-1">对宝宝的影响</p>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">{item.baby_impact}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.suggestion && (
|
||||
<div className="bg-morandi-100/50 rounded-xl p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<Heart className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-medium text-gray-700 mb-1">建议措施</p>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">{item.suggestion}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.follow_up && (
|
||||
<div className="flex items-center gap-2 text-xs text-morandi-500">
|
||||
<Calendar className="w-3 h-3" />
|
||||
<span>{item.follow_up}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 行动建议 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
接下来该做什么?
|
||||
</h2>
|
||||
|
||||
<div className="space-y-3">
|
||||
{analysisData.action_items.map((rec, index) => (
|
||||
<motion.div
|
||||
key={index}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.6 + index * 0.1 }}
|
||||
>
|
||||
<Card
|
||||
className={`rounded-2xl p-4 border-2 ${
|
||||
rec.priority === "high"
|
||||
? "bg-morandi-rose-100 border-morandi-200"
|
||||
: rec.priority === "medium"
|
||||
? "bg-morandi-50 border-morandi-200"
|
||||
: "bg-gray-50 border-gray-200"
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h4 className="font-semibold text-gray-800">
|
||||
{rec.title}
|
||||
</h4>
|
||||
{rec.priority === "high" && (
|
||||
<Badge className="bg-morandi-rose-100 text-morandi-600 text-xs">
|
||||
重要
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 mb-2">
|
||||
{rec.description}
|
||||
</p>
|
||||
{rec.timeframe && (
|
||||
<div className="flex items-center gap-2 text-xs text-gray-500">
|
||||
<Calendar className="w-3 h-3" />
|
||||
<span>{rec.timeframe}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 深度服务 - 新增 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.7 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
🎯 获取更多帮助
|
||||
</h2>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Card
|
||||
onClick={() => navigate(`/chat/${reportId}`)}
|
||||
className="bg-morandi-100 rounded-2xl p-4 border-0 cursor-pointer hover:scale-105 transition-transform"
|
||||
>
|
||||
<div className="w-12 h-12 bg-morandi-400 rounded-xl flex items-center justify-center mb-3">
|
||||
<MessageCircle className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-gray-800 mb-1">AI对话追问</h3>
|
||||
<p className="text-xs text-gray-600">针对报告提问</p>
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
onClick={() => navigate(`/doctor-questions/${reportId}`)}
|
||||
className="bg-gradient-to-br from-morandi-slate-100 to-morandi-slate-50 rounded-2xl p-4 border-0 cursor-pointer hover:scale-105 transition-transform"
|
||||
>
|
||||
<div className="w-12 h-12 bg-morandi-slate-500 rounded-xl flex items-center justify-center mb-3">
|
||||
<FileText className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-gray-800 mb-1">问诊清单</h3>
|
||||
<p className="text-xs text-gray-600">就医沟通话术</p>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 温馨提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.9 }}
|
||||
>
|
||||
<Card className="bg-morandi-50 border-morandi-200 rounded-2xl p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Heart className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h4 className="font-semibold text-gray-800 mb-1">
|
||||
温馨提示
|
||||
</h4>
|
||||
<p className="text-sm text-gray-600 leading-relaxed">
|
||||
以上解读仅供参考,不能替代医生的专业诊断。如有任何疑问或不适,请及时就医咨询专业医生。保持好心情,宝宝能感受到妈妈的情绪哦 💕
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* 底部操作栏 */}
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 pb-safe z-10">
|
||||
<div className="max-w-md mx-auto flex gap-3">
|
||||
<Button
|
||||
onClick={() => navigate("/home")}
|
||||
variant="outline"
|
||||
className="flex-1 h-12 rounded-xl border-2 border-gray-300"
|
||||
>
|
||||
返回首页
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => navigate(`/report/${reportId}`)}
|
||||
className="flex-1 h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white"
|
||||
>
|
||||
查看原始报告
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 分享弹窗 */}
|
||||
<AnimatePresence>
|
||||
{showShareSheet && (
|
||||
<>
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
onClick={() => setShowShareSheet(false)}
|
||||
className="fixed inset-0 bg-black/40 z-40"
|
||||
/>
|
||||
<motion.div
|
||||
initial={{ y: "100%" }}
|
||||
animate={{ y: 0 }}
|
||||
exit={{ y: "100%" }}
|
||||
transition={{ type: "spring", damping: 25, stiffness: 300 }}
|
||||
className="fixed bottom-0 left-0 right-0 bg-white rounded-t-3xl z-50 max-h-[70vh] overflow-y-auto"
|
||||
>
|
||||
<div className="mx-auto p-5">
|
||||
{/* 拖拽指示器 */}
|
||||
<div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
|
||||
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<h3 className="font-semibold text-gray-800 text-lg">分享报告</h3>
|
||||
<button
|
||||
onClick={() => setShowShareSheet(false)}
|
||||
className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 分享方式 */}
|
||||
<div className="space-y-3 mb-6">
|
||||
{/* 生成分享长图 */}
|
||||
<button
|
||||
onClick={() => {
|
||||
setShowShareSheet(false);
|
||||
navigate(`/share/${reportId}`);
|
||||
}}
|
||||
className="w-full flex items-center gap-4 py-4 px-4 bg-gradient-to-r from-morandi-100 to-morandi-50 hover:from-morandi-200 hover:to-morandi-100 rounded-2xl transition-colors"
|
||||
>
|
||||
<div className="w-12 h-12 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-xl flex items-center justify-center flex-shrink-0">
|
||||
<ImageIcon className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-left flex-1">
|
||||
<div className="font-semibold text-gray-800">
|
||||
生成分享长图
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
生成精美报告长图,一键保存到相册
|
||||
</div>
|
||||
</div>
|
||||
<ChevronLeft className="w-5 h-5 text-gray-300 rotate-180" />
|
||||
</button>
|
||||
|
||||
{/* 复制链接 */}
|
||||
<button
|
||||
onClick={handleCopyLink}
|
||||
className="w-full flex items-center gap-4 py-4 px-4 bg-morandi-50 hover:bg-morandi-100 rounded-2xl transition-colors"
|
||||
>
|
||||
<div className="w-12 h-12 bg-morandi-400 rounded-xl flex items-center justify-center flex-shrink-0">
|
||||
{linkCopied ? (
|
||||
<Check className="w-6 h-6 text-white" />
|
||||
) : (
|
||||
<Link2 className="w-6 h-6 text-white" />
|
||||
)}
|
||||
</div>
|
||||
<div className="text-left flex-1">
|
||||
<div className="font-semibold text-gray-800">
|
||||
{linkCopied ? "链接已复制" : "复制分享链接"}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{linkCopied ? "可以分享给家人或医生" : "复制链接发送给家人或医生"}
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 分享预览卡片 */}
|
||||
<Card className="bg-morandi-50 border-morandi-100 rounded-2xl p-4 mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-12 h-12 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-xl flex items-center justify-center flex-shrink-0">
|
||||
<FileText className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium text-gray-800 text-sm truncate">
|
||||
{analysisData.categories[0]?.category || "检查报告"} · AI解读
|
||||
</h4>
|
||||
<p className="text-xs text-gray-500 mt-0.5 truncate">
|
||||
{analysisData.overall_summary}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<span className="text-xs text-gray-400">{new Date(analysisData.created_at).toLocaleDateString("zh-CN")}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 隐私提示 */}
|
||||
<div className="flex items-center gap-2 text-xs text-gray-400 mb-2">
|
||||
<Info className="w-3.5 h-3.5 flex-shrink-0" />
|
||||
<span>分享时将自动隐藏个人敏感信息,保护您的隐私</span>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
271
frontend/src/app/pages/AIChatPage.tsx
Normal file
271
frontend/src/app/pages/AIChatPage.tsx
Normal file
@@ -0,0 +1,271 @@
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Send,
|
||||
Sparkles,
|
||||
Lightbulb,
|
||||
User,
|
||||
Bot,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { sendChatMessage, getChatHistory } from "../services/api";
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export function AIChatPage() {
|
||||
const navigate = useNavigate();
|
||||
const { reportId } = useParams();
|
||||
const [messages, setMessages] = useState<Message[]>([
|
||||
{
|
||||
id: "1",
|
||||
role: "assistant",
|
||||
content:
|
||||
"您好!我是您的孕期健康助手。您可以向我询问报告中的任何指标,我会结合医学知识为您详细解答。",
|
||||
timestamp: new Date(),
|
||||
},
|
||||
]);
|
||||
const [input, setInput] = useState("");
|
||||
const [isTyping, setIsTyping] = useState(false);
|
||||
const [quickQuestions, setQuickQuestions] = useState<string[]>([
|
||||
"这个指标偏高对宝宝有影响吗?",
|
||||
"我需要补充什么营养?",
|
||||
"下次检查需要注意什么?",
|
||||
"这种情况多久会恢复正常?",
|
||||
]);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Load chat history on mount
|
||||
useEffect(() => {
|
||||
if (!reportId) return;
|
||||
getChatHistory(reportId).then((data) => {
|
||||
if (data.messages.length > 0) {
|
||||
setMessages(
|
||||
data.messages.map((m, i) => ({
|
||||
id: String(i),
|
||||
role: m.role as "user" | "assistant",
|
||||
content: m.content,
|
||||
timestamp: new Date(m.timestamp),
|
||||
}))
|
||||
);
|
||||
}
|
||||
if (data.quick_questions.length > 0) {
|
||||
setQuickQuestions(data.quick_questions);
|
||||
}
|
||||
}).catch(() => {/* keep defaults */});
|
||||
}, [reportId]);
|
||||
|
||||
const scrollToBottom = () => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [messages]);
|
||||
|
||||
const handleSend = async () => {
|
||||
if (!input.trim() || !reportId) return;
|
||||
|
||||
const userMessage: Message = {
|
||||
id: Date.now().toString(),
|
||||
role: "user",
|
||||
content: input,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
|
||||
setMessages((prev) => [...prev, userMessage]);
|
||||
const question = input;
|
||||
setInput("");
|
||||
setIsTyping(true);
|
||||
|
||||
try {
|
||||
const result = await sendChatMessage(reportId, question);
|
||||
const aiResponse: Message = {
|
||||
id: (Date.now() + 1).toString(),
|
||||
role: "assistant",
|
||||
content: result.ai_message.content,
|
||||
timestamp: new Date(result.ai_message.timestamp),
|
||||
};
|
||||
setMessages((prev) => [...prev, aiResponse]);
|
||||
} catch {
|
||||
const errorMsg: Message = {
|
||||
id: (Date.now() + 1).toString(),
|
||||
role: "assistant",
|
||||
content: "抱歉,AI 服务暂时不可用,请稍后重试。",
|
||||
timestamp: new Date(),
|
||||
};
|
||||
setMessages((prev) => [...prev, errorMsg]);
|
||||
} finally {
|
||||
setIsTyping(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleQuickQuestion = (question: string) => {
|
||||
setInput(question);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex flex-col">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
|
||||
<Sparkles className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">AI 健康顾问</h1>
|
||||
<p className="text-xs text-gray-500">智能解答,随时陪伴</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 消息列表 */}
|
||||
<div className="flex-1 overflow-y-auto">
|
||||
<div className="mx-auto px-4 py-6 space-y-4">
|
||||
<AnimatePresence>
|
||||
{messages.map((message) => (
|
||||
<motion.div
|
||||
key={message.id}
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
className={`flex gap-3 ${
|
||||
message.role === "user" ? "flex-row-reverse" : ""
|
||||
}`}
|
||||
>
|
||||
<div
|
||||
className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${
|
||||
message.role === "user"
|
||||
? "bg-morandi-100"
|
||||
: "bg-morandi-400"
|
||||
}`}
|
||||
>
|
||||
{message.role === "user" ? (
|
||||
<User className="w-5 h-5 text-morandi-500" />
|
||||
) : (
|
||||
<Bot className="w-5 h-5 text-white" />
|
||||
)}
|
||||
</div>
|
||||
<Card
|
||||
className={`max-w-[75%] p-4 rounded-2xl border-0 ${
|
||||
message.role === "user"
|
||||
? "bg-morandi-400 text-white"
|
||||
: "bg-white shadow-sm"
|
||||
}`}
|
||||
>
|
||||
<p
|
||||
className={`text-sm leading-relaxed whitespace-pre-line ${
|
||||
message.role === "user" ? "text-white" : "text-gray-700"
|
||||
}`}
|
||||
>
|
||||
{message.content}
|
||||
</p>
|
||||
<p
|
||||
className={`text-xs mt-2 ${
|
||||
message.role === "user"
|
||||
? "text-morandi-100"
|
||||
: "text-gray-400"
|
||||
}`}
|
||||
>
|
||||
{message.timestamp.toLocaleTimeString("zh-CN", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</p>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
|
||||
{isTyping && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex gap-3"
|
||||
>
|
||||
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
|
||||
<Bot className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<Card className="bg-white shadow-sm p-4 rounded-2xl">
|
||||
<div className="flex gap-1">
|
||||
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
|
||||
<div
|
||||
className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"
|
||||
style={{ animationDelay: "0.1s" }}
|
||||
></div>
|
||||
<div
|
||||
className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"
|
||||
style={{ animationDelay: "0.2s" }}
|
||||
></div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 快捷提问 */}
|
||||
{messages.length <= 1 && (
|
||||
<div className="mx-auto px-4 pb-4">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Lightbulb className="w-4 h-4 text-morandi-400" />
|
||||
<p className="text-sm text-gray-600">试试这样问:</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{quickQuestions.map((question, index) => (
|
||||
<button
|
||||
key={index}
|
||||
onClick={() => handleQuickQuestion(question)}
|
||||
className="bg-white rounded-xl p-3 text-sm text-left text-gray-600 hover:bg-morandi-50 hover:text-morandi-500 transition-colors border border-gray-100"
|
||||
>
|
||||
{question}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 输入框 */}
|
||||
<div className="bg-white border-t border-gray-100 sticky bottom-0">
|
||||
<div className="mx-auto px-4 py-4">
|
||||
<div className="flex gap-3">
|
||||
<Input
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyPress={(e) => e.key === "Enter" && handleSend()}
|
||||
placeholder="输入您的问题..."
|
||||
className="flex-1 rounded-full border-gray-200 focus:border-morandi-200"
|
||||
/>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
disabled={!input.trim() || isTyping}
|
||||
className="w-12 h-12 rounded-full bg-morandi-400 hover:from-morandi-500 hover:to-morandi-500 disabled:opacity-50"
|
||||
>
|
||||
<Send className="w-5 h-5 text-white" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
842
frontend/src/app/pages/CalendarPage.tsx
Normal file
842
frontend/src/app/pages/CalendarPage.tsx
Normal file
@@ -0,0 +1,842 @@
|
||||
import { useState, useRef, useEffect, useMemo } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Calendar as CalendarIcon,
|
||||
Bell,
|
||||
Clock,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
Plus,
|
||||
X,
|
||||
FileText,
|
||||
ChevronRight,
|
||||
Upload,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { useUser } from "../context/UserContext";
|
||||
import { checkupSchedule } from "../data/checkupSchedule";
|
||||
import {
|
||||
getCheckupPlan,
|
||||
completeCheckup,
|
||||
getReportList,
|
||||
type ReportListItem,
|
||||
} from "../services/api";
|
||||
|
||||
interface Checkup {
|
||||
id: string;
|
||||
title: string;
|
||||
week: number;
|
||||
date: string;
|
||||
items: string[];
|
||||
preparations: string[];
|
||||
notes: string;
|
||||
status: "upcoming" | "completed" | "missed";
|
||||
importance: "high" | "medium" | "low";
|
||||
report_ids: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查项目 → 报告类型 关键词映射
|
||||
* checkup.items 中的项目名 → 报告 report_type 中可能出现的关键词
|
||||
*/
|
||||
const ITEM_REPORT_KEYWORDS: Record<string, string[]> = {
|
||||
"NT检查(胎儿颈部透明带)": ["NT", "颈部透明带", "B超", "超声"],
|
||||
"血常规": ["血常规"],
|
||||
"尿常规": ["尿常规"],
|
||||
"肝肾功能": ["肝功能", "肾功能", "肝肾", "生化"],
|
||||
"血型检查": ["血型"],
|
||||
"传染病筛查": ["传染病", "乙肝", "艾滋", "梅毒", "丙肝"],
|
||||
"血清学唐氏筛查": ["唐筛", "唐氏", "唐氏筛查"],
|
||||
"B超检查": ["B超", "超声", "彩超"],
|
||||
"四维彩超": ["四维", "彩超", "大排畸", "B超", "超声"],
|
||||
"胎儿系统超声筛查": ["系统超声", "四维", "大排畸", "B超", "超声"],
|
||||
"75g OGTT(葡萄糖耐量试验)": ["糖耐", "OGTT", "葡萄糖耐量", "血糖"],
|
||||
"胎心监护": ["胎心", "胎监", "NST"],
|
||||
"骨盆测量": ["骨盆"],
|
||||
"心电图": ["心电图", "ECG"],
|
||||
"血压测量": ["血压"],
|
||||
"宫高腹围": ["宫高", "腹围"],
|
||||
};
|
||||
|
||||
/** 判断某个检查项目是否有对应的报告覆盖 */
|
||||
function isItemCoveredByReports(item: string, reports: ReportListItem[]): boolean {
|
||||
// 先查映射表
|
||||
const keywords = ITEM_REPORT_KEYWORDS[item];
|
||||
if (keywords) {
|
||||
return reports.some((r) =>
|
||||
keywords.some((kw) => r.report_type.includes(kw))
|
||||
);
|
||||
}
|
||||
// 兜底:直接用项目名中的核心关键词匹配
|
||||
// 去掉括号内容后取前几个字
|
||||
const core = item.replace(/[((].+?[))]/g, "").trim();
|
||||
return reports.some((r) => r.report_type.includes(core) || core.includes(r.report_type));
|
||||
}
|
||||
|
||||
/** 获取某次产检中缺少报告的检查项目 */
|
||||
function getMissingItems(checkup: Checkup, linkedReports: ReportListItem[]): string[] {
|
||||
if (linkedReports.length === 0) return checkup.items;
|
||||
// 血压测量、宫高腹围通常不需要独立报告,排除
|
||||
const skipItems = ["血压测量", "宫高腹围"];
|
||||
return checkup.items.filter(
|
||||
(item) => !skipItems.includes(item) && !isItemCoveredByReports(item, linkedReports)
|
||||
);
|
||||
}
|
||||
|
||||
/** 将报告匹配到产检:优先使用服务端关联的 report_ids,其次按 pregnancy_week ±2 周模糊匹配 */
|
||||
function buildCheckupReportMap(
|
||||
checkups: Checkup[],
|
||||
reports: ReportListItem[]
|
||||
): Map<string, ReportListItem[]> {
|
||||
const map = new Map<string, ReportListItem[]>();
|
||||
const assigned = new Set<string>();
|
||||
const reportById = new Map(reports.map((r) => [r.id, r]));
|
||||
const sorted = [...checkups].sort((a, b) => a.week - b.week);
|
||||
|
||||
// First pass: use server-linked report_ids
|
||||
for (const c of sorted) {
|
||||
const linked: ReportListItem[] = [];
|
||||
for (const rid of c.report_ids || []) {
|
||||
const r = reportById.get(rid);
|
||||
if (r) {
|
||||
linked.push(r);
|
||||
assigned.add(rid);
|
||||
}
|
||||
}
|
||||
map.set(c.id, linked);
|
||||
}
|
||||
|
||||
// Second pass: fuzzy match remaining reports by pregnancy_week (±2 weeks)
|
||||
for (const c of sorted) {
|
||||
const existing = map.get(c.id) || [];
|
||||
const fuzzyMatched = reports
|
||||
.filter(
|
||||
(r) =>
|
||||
!assigned.has(r.id) &&
|
||||
r.pregnancy_week != null &&
|
||||
Math.abs(r.pregnancy_week - c.week) <= 2
|
||||
)
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Math.abs(a.pregnancy_week! - c.week) -
|
||||
Math.abs(b.pregnancy_week! - c.week)
|
||||
);
|
||||
map.set(c.id, [...existing, ...fuzzyMatched]);
|
||||
fuzzyMatched.forEach((r) => assigned.add(r.id));
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
export function CalendarPage() {
|
||||
const navigate = useNavigate();
|
||||
const { user } = useUser();
|
||||
|
||||
const calcCheckupDate = (week: number): string => {
|
||||
if (!user.lastPeriodDate) return "";
|
||||
const lmp = new Date(user.lastPeriodDate);
|
||||
const date = new Date(lmp.getTime() + week * 7 * 24 * 60 * 60 * 1000);
|
||||
return date.toISOString().split("T")[0];
|
||||
};
|
||||
|
||||
const currentWeek = user.currentWeek || 0;
|
||||
|
||||
const getCheckupStatus = (week: number): "upcoming" | "completed" | "missed" => {
|
||||
if (week < currentWeek) return "completed";
|
||||
return "upcoming";
|
||||
};
|
||||
|
||||
const [checkups, setCheckups] = useState<Checkup[]>(() =>
|
||||
checkupSchedule.map((tpl, i) => ({
|
||||
id: String(i + 1),
|
||||
title: tpl.title,
|
||||
week: tpl.week,
|
||||
date: calcCheckupDate(tpl.week),
|
||||
items: tpl.items,
|
||||
preparations: tpl.preparations,
|
||||
notes: tpl.notes,
|
||||
status: getCheckupStatus(tpl.week),
|
||||
importance: tpl.importance,
|
||||
report_ids: [],
|
||||
}))
|
||||
);
|
||||
|
||||
const [reports, setReports] = useState<ReportListItem[]>([]);
|
||||
|
||||
// 获取产检计划 + 报告列表
|
||||
useEffect(() => {
|
||||
getCheckupPlan()
|
||||
.then((data) => {
|
||||
if (data.checkups && data.checkups.length > 0) {
|
||||
setCheckups(
|
||||
data.checkups.map((c, i) => ({
|
||||
id: String(i + 1),
|
||||
title: c.title,
|
||||
week: c.week,
|
||||
date: calcCheckupDate(c.week),
|
||||
items: c.items,
|
||||
preparations: c.preparations,
|
||||
notes: c.notes,
|
||||
status: (c.status as Checkup["status"]) || getCheckupStatus(c.week),
|
||||
importance: (c.importance as Checkup["importance"]) || "medium",
|
||||
report_ids: c.report_ids || [],
|
||||
}))
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(() => {});
|
||||
|
||||
getReportList(100)
|
||||
.then(setReports)
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const checkupReportMap = useMemo(
|
||||
() => buildCheckupReportMap(checkups, reports),
|
||||
[checkups, reports]
|
||||
);
|
||||
|
||||
const pastCheckups = checkups.filter((c) => c.week < currentWeek);
|
||||
const upcomingCheckups = checkups.filter((c) => c.week >= currentWeek);
|
||||
const nextCheckup = upcomingCheckups[0];
|
||||
|
||||
const detailsRefs = useRef<Record<string, HTMLDetailsElement | null>>({});
|
||||
const nextCheckupRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// 自动滚动到即将进行的产检
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
nextCheckupRef.current?.scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
const [showAddForm, setShowAddForm] = useState(false);
|
||||
const [newCheckup, setNewCheckup] = useState({
|
||||
title: "",
|
||||
week: "",
|
||||
date: "",
|
||||
items: "",
|
||||
preparations: "",
|
||||
notes: "",
|
||||
importance: "medium" as "high" | "medium" | "low",
|
||||
});
|
||||
|
||||
const handleAddCheckup = () => {
|
||||
if (!newCheckup.title || !newCheckup.date) return;
|
||||
const checkup: Checkup = {
|
||||
id: Date.now().toString(),
|
||||
title: newCheckup.title,
|
||||
week: newCheckup.week ? parseInt(newCheckup.week) : 0,
|
||||
date: newCheckup.date,
|
||||
items: newCheckup.items ? newCheckup.items.split(",").map((s) => s.trim()).filter(Boolean) : [],
|
||||
preparations: newCheckup.preparations ? newCheckup.preparations.split(",").map((s) => s.trim()).filter(Boolean) : [],
|
||||
notes: newCheckup.notes,
|
||||
status: "upcoming",
|
||||
importance: newCheckup.importance,
|
||||
report_ids: [],
|
||||
};
|
||||
setCheckups((prev) =>
|
||||
[...prev, checkup].sort((a, b) => a.week - b.week)
|
||||
);
|
||||
setNewCheckup({ title: "", week: "", date: "", items: "", preparations: "", notes: "", importance: "medium" });
|
||||
setShowAddForm(false);
|
||||
};
|
||||
|
||||
const handleComplete = (week: number) => {
|
||||
completeCheckup(week)
|
||||
.then(() => {
|
||||
setCheckups((prev) =>
|
||||
prev.map((c) =>
|
||||
c.week === week ? { ...c, status: "completed" as const } : c
|
||||
)
|
||||
);
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
/** 渲染单个产检卡片 */
|
||||
const renderCheckupCard = (checkup: Checkup, index: number, isFirstUpcoming: boolean) => {
|
||||
const isPast = checkup.week < currentWeek;
|
||||
const isCurrent = checkup.week >= currentWeek && checkup.week <= currentWeek + 4;
|
||||
const linkedReports = checkupReportMap.get(checkup.id) || [];
|
||||
const hasReports = linkedReports.length > 0;
|
||||
const showUploadPrompt = isPast && !hasReports;
|
||||
const missingItems = isPast ? getMissingItems(checkup, linkedReports) : [];
|
||||
const hasMissing = missingItems.length > 0 && hasReports; // 有报告但不全
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={checkup.id}
|
||||
ref={isFirstUpcoming ? nextCheckupRef : undefined}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.1 + index * 0.04 }}
|
||||
>
|
||||
<Card
|
||||
className={`rounded-2xl p-5 shadow-sm border-0 ${
|
||||
isCurrent
|
||||
? "bg-morandi-rose-100 border-2 border-morandi-rose-300"
|
||||
: "bg-white"
|
||||
} ${isPast ? "opacity-70" : ""}`}
|
||||
>
|
||||
<div className="flex items-start gap-4 mb-4">
|
||||
<div
|
||||
className={`w-12 h-12 rounded-xl flex items-center justify-center ${
|
||||
checkup.status === "completed"
|
||||
? "bg-morandi-sage-100"
|
||||
: checkup.status === "missed"
|
||||
? "bg-red-100"
|
||||
: checkup.importance === "high"
|
||||
? "bg-morandi-rose-100"
|
||||
: "bg-morandi-100"
|
||||
}`}
|
||||
>
|
||||
{checkup.status === "completed" ? (
|
||||
<CheckCircle2 className="w-6 h-6 text-morandi-sage-400" />
|
||||
) : checkup.status === "missed" ? (
|
||||
<AlertCircle className="w-6 h-6 text-red-500" />
|
||||
) : (
|
||||
<CalendarIcon
|
||||
className={`w-6 h-6 ${
|
||||
checkup.importance === "high"
|
||||
? "text-morandi-rose-400"
|
||||
: "text-morandi-400"
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-2 mb-2 flex-wrap">
|
||||
<h3 className="font-semibold text-gray-800 text-lg">
|
||||
{checkup.title}
|
||||
</h3>
|
||||
{checkup.importance === "high" && (
|
||||
<Badge className="bg-red-100 text-red-700 hover:bg-red-100">
|
||||
重要
|
||||
</Badge>
|
||||
)}
|
||||
{isCurrent && (
|
||||
<Badge className="bg-morandi-rose-100 text-morandi-600 hover:bg-morandi-rose-100">
|
||||
即将进行
|
||||
</Badge>
|
||||
)}
|
||||
{/* 报告状态徽章 */}
|
||||
{hasReports && (
|
||||
<Badge className="bg-morandi-sage-50 text-morandi-sage-600 hover:bg-morandi-sage-50">
|
||||
{linkedReports.length}份报告
|
||||
</Badge>
|
||||
)}
|
||||
{hasMissing && (
|
||||
<Badge className="bg-orange-50 text-orange-600 hover:bg-orange-50">
|
||||
{missingItems.length}项待补传
|
||||
</Badge>
|
||||
)}
|
||||
{showUploadPrompt && (
|
||||
<Badge className="bg-amber-50 text-amber-600 hover:bg-amber-50">
|
||||
缺少报告
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-sm text-gray-600 mb-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="w-4 h-4" />
|
||||
{checkup.date || "待确定"}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<CalendarIcon className="w-4 h-4" />
|
||||
孕{checkup.week}周
|
||||
</div>
|
||||
{checkup.status === "completed" && (
|
||||
<Badge className="bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100">
|
||||
已完成
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 卡片级操作按钮(不需要展开即可见) */}
|
||||
<div className="flex gap-2 mb-3">
|
||||
{!isPast && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
className="flex-1 bg-morandi-400 hover:bg-morandi-500 text-white"
|
||||
onClick={() => navigate("/camera")}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-1" />
|
||||
上传报告
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
onClick={() => handleComplete(checkup.week)}
|
||||
>
|
||||
<CheckCircle2 className="w-4 h-4 mr-1" />
|
||||
标记完成
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{isPast && !hasReports && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full bg-morandi-rose-400 hover:bg-morandi-rose-500 text-white"
|
||||
onClick={() => navigate("/camera")}
|
||||
>
|
||||
<Upload className="w-4 h-4 mr-1" />
|
||||
上传历史报告,解读更专业
|
||||
</Button>
|
||||
)}
|
||||
{isPast && hasReports && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="w-full"
|
||||
onClick={() => {
|
||||
if (linkedReports.length === 1) {
|
||||
navigate(`/analysis/${linkedReports[0].id}`);
|
||||
} else {
|
||||
const el = detailsRefs.current[checkup.id];
|
||||
if (el) { el.open = true; }
|
||||
}
|
||||
}}
|
||||
>
|
||||
<FileText className="w-4 h-4 mr-1" />
|
||||
{linkedReports.length === 1 ? "查看报告解读" : `查看 ${linkedReports.length} 份报告`}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 漏传报告提醒 */}
|
||||
{hasMissing && (
|
||||
<div className="mb-3 bg-orange-50 rounded-xl p-3">
|
||||
<div className="flex items-start gap-2 mb-2">
|
||||
<AlertCircle className="w-4 h-4 text-orange-500 mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1">
|
||||
<p className="text-xs font-medium text-orange-700 mb-1.5">
|
||||
以下检查项目还未上传报告,建议补充上传以获得更完整的解读
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{missingItems.map((item, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="inline-flex items-center text-[11px] bg-orange-100 text-orange-700 rounded-md px-2 py-0.5"
|
||||
>
|
||||
{item}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
className="w-full bg-orange-500 hover:bg-orange-600 text-white mt-1"
|
||||
onClick={() => navigate("/camera")}
|
||||
>
|
||||
<Upload className="w-3.5 h-3.5 mr-1" />
|
||||
补充上传报告
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<details
|
||||
ref={(el) => { detailsRefs.current[checkup.id] = el; }}
|
||||
className="group"
|
||||
>
|
||||
<summary className="cursor-pointer text-morandi-500 text-sm font-semibold hover:text-morandi-500 list-none flex items-center gap-2 mb-3">
|
||||
查看检查详情
|
||||
<span className="text-xs">▼</span>
|
||||
</summary>
|
||||
|
||||
<div className="space-y-4 pt-2">
|
||||
{/* 检查项目 */}
|
||||
<div>
|
||||
<h4 className="font-semibold text-gray-700 mb-2 text-sm">
|
||||
检查项目
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{checkup.items.map((item, i) => {
|
||||
const covered = isPast && hasReports && isItemCoveredByReports(item, linkedReports);
|
||||
const missing = isPast && hasReports && !isItemCoveredByReports(item, linkedReports) && !["血压测量", "宫高腹围"].includes(item);
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={`text-sm flex items-center gap-2 rounded-lg px-3 py-2 ${
|
||||
missing ? "bg-orange-50 text-orange-700" : covered ? "bg-morandi-sage-50 text-morandi-sage-700" : "bg-gray-50 text-gray-600"
|
||||
}`}
|
||||
>
|
||||
<div className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${
|
||||
missing ? "bg-orange-400" : covered ? "bg-morandi-sage-400" : "bg-morandi-400"
|
||||
}`} />
|
||||
{item}
|
||||
{covered && <CheckCircle2 className="w-3 h-3 text-morandi-sage-400 ml-auto flex-shrink-0" />}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 注意事项 */}
|
||||
{checkup.preparations.length > 0 && (
|
||||
<div className="bg-morandi-rose-100 rounded-xl p-3">
|
||||
<h4 className="font-semibold text-morandi-700 mb-2 text-sm flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
注意事项
|
||||
</h4>
|
||||
<ul className="space-y-1">
|
||||
{checkup.preparations.map((prep, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className="text-sm text-morandi-600 flex items-center gap-2"
|
||||
>
|
||||
<span className="w-1.5 h-1.5 bg-morandi-rose-400 rounded-full"></span>
|
||||
{prep}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 医生提示 */}
|
||||
{checkup.notes && (
|
||||
<div className="bg-morandi-slate-50 rounded-xl p-3">
|
||||
<p className="text-sm text-morandi-500 leading-relaxed">
|
||||
💡 {checkup.notes}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 关联报告 */}
|
||||
{hasReports && (
|
||||
<div>
|
||||
<h4 className="font-semibold text-gray-700 mb-2 text-sm flex items-center gap-2">
|
||||
<FileText className="w-4 h-4" />
|
||||
检查报告
|
||||
</h4>
|
||||
<div className="space-y-2">
|
||||
{linkedReports.map((report) => (
|
||||
<div
|
||||
key={report.id}
|
||||
onClick={() => navigate(`/analysis/${report.id}`)}
|
||||
className="flex items-center justify-between bg-morandi-50 rounded-xl px-3 py-2.5 cursor-pointer hover:bg-morandi-100 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<div
|
||||
className={`w-2 h-2 rounded-full flex-shrink-0 ${
|
||||
report.overall_status === "normal"
|
||||
? "bg-morandi-sage-400"
|
||||
: report.overall_status === "attention"
|
||||
? "bg-amber-400"
|
||||
: "bg-red-400"
|
||||
}`}
|
||||
/>
|
||||
<span className="text-sm text-gray-700 font-medium truncate">
|
||||
{report.report_type}
|
||||
</span>
|
||||
{report.summary && (
|
||||
<span className="text-xs text-gray-400 truncate hidden sm:inline">
|
||||
{report.summary}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 缺少报告提示 - 已在顶部显示,不再重复 */}
|
||||
</div>
|
||||
</details>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-gradient-to-br from-morandi-300 to-morandi-rose-400 rounded-full flex items-center justify-center">
|
||||
<CalendarIcon className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">产检日历</h1>
|
||||
<p className="text-xs text-gray-500">孕期检查安排与提醒</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => setShowAddForm(true)}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="rounded-full"
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-2" />
|
||||
自定义
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 下次产检提醒 */}
|
||||
{nextCheckup && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-rose-400 border-0 text-white p-6 rounded-3xl shadow-sm">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div>
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<Bell className="w-5 h-5" />
|
||||
<span className="text-sm text-white/90">下次产检</span>
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold mb-2">{nextCheckup.title}</h2>
|
||||
<div className="space-y-1 text-sm text-white/90">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="w-4 h-4" />
|
||||
{nextCheckup.date ? nextCheckup.date : "请设置末次月经日期"} (孕{nextCheckup.week}周)
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarIcon className="w-4 h-4" />
|
||||
{nextCheckup.date ? (
|
||||
<>
|
||||
距离现在还有{" "}
|
||||
{Math.max(
|
||||
0,
|
||||
Math.ceil(
|
||||
(new Date(nextCheckup.date).getTime() -
|
||||
new Date().getTime()) /
|
||||
(1000 * 60 * 60 * 24)
|
||||
)
|
||||
)}{" "}
|
||||
天
|
||||
</>
|
||||
) : (
|
||||
<>还有 {Math.max(0, nextCheckup.week - currentWeek)} 周</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="bg-white/20 backdrop-blur-sm rounded-2xl px-4 py-2">
|
||||
<div className="text-xs text-white/80">当前孕周</div>
|
||||
<div className="text-2xl font-semibold">{currentWeek}</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (nextCheckup) {
|
||||
const el = detailsRefs.current[nextCheckup.id];
|
||||
if (el) {
|
||||
el.open = true;
|
||||
el.scrollIntoView({ behavior: "smooth", block: "start" });
|
||||
}
|
||||
}
|
||||
}}
|
||||
className="w-full bg-white text-morandi-500 hover:bg-white/90"
|
||||
>
|
||||
查看详情
|
||||
</Button>
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 已过产检 */}
|
||||
{pastCheckups.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
📋 已过产检
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
{pastCheckups.map((checkup, index) =>
|
||||
renderCheckupCard(checkup, index, false)
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 即将到来的产检 */}
|
||||
{upcomingCheckups.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.15 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
📅 即将到来
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
{upcomingCheckups.map((checkup, index) =>
|
||||
renderCheckupCard(checkup, index, index === 0)
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 温馨提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.6 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-r from-morandi-50 to-morandi-50 border-morandi-200 rounded-2xl p-4">
|
||||
<h3 className="font-semibold text-gray-800 mb-2">📅 产检小贴士</h3>
|
||||
<ul className="space-y-1 text-sm text-gray-600">
|
||||
<li>• 建议提前预约,避免等待时间过长</li>
|
||||
<li>• 携带好病历本和既往检查结果</li>
|
||||
<li>• 产检当天穿宽松舒适的衣服,便于检查</li>
|
||||
<li>• 有问题记录下来,产检时向医生咨询</li>
|
||||
<li>• 孕晚期建议家人陪同产检</li>
|
||||
</ul>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* 自定义产检弹窗 */}
|
||||
{showAddForm && (
|
||||
<div className="fixed inset-0 bg-black/40 z-50 flex items-end sm:items-center justify-center">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 40 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="bg-white w-full sm:max-w-md rounded-t-3xl sm:rounded-3xl p-6 max-h-[85vh] overflow-y-auto"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<h2 className="font-semibold text-gray-800 text-lg">添加自定义产检</h2>
|
||||
<button
|
||||
onClick={() => setShowAddForm(false)}
|
||||
className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">产检名称 *</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="例如:常规产检"
|
||||
value={newCheckup.title}
|
||||
onChange={(e) => setNewCheckup({ ...newCheckup, title: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">孕周</label>
|
||||
<input
|
||||
type="number"
|
||||
placeholder="例如:20"
|
||||
value={newCheckup.week}
|
||||
onChange={(e) => setNewCheckup({ ...newCheckup, week: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">日期 *</label>
|
||||
<input
|
||||
type="date"
|
||||
value={newCheckup.date}
|
||||
onChange={(e) => setNewCheckup({ ...newCheckup, date: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">重要程度</label>
|
||||
<div className="flex gap-2">
|
||||
{([["high", "重要"], ["medium", "一般"], ["low", "普通"]] as const).map(([val, label]) => (
|
||||
<button
|
||||
key={val}
|
||||
onClick={() => setNewCheckup({ ...newCheckup, importance: val })}
|
||||
className={`flex-1 py-2 rounded-xl text-sm font-medium transition-all ${
|
||||
newCheckup.importance === val
|
||||
? "bg-morandi-400 text-white"
|
||||
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
|
||||
}`}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">检查项目</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="用中文逗号分隔,例如:血常规,尿常规"
|
||||
value={newCheckup.items}
|
||||
onChange={(e) => setNewCheckup({ ...newCheckup, items: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">注意事项</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="用中文逗号分隔,例如:需空腹,携带病历本"
|
||||
value={newCheckup.preparations}
|
||||
onChange={(e) => setNewCheckup({ ...newCheckup, preparations: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="text-sm text-gray-600 mb-1 block">备注</label>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="可选,医生提示或其他备注"
|
||||
value={newCheckup.notes}
|
||||
onChange={(e) => setNewCheckup({ ...newCheckup, notes: e.target.value })}
|
||||
className="w-full px-3 py-2.5 text-sm bg-morandi-50 border border-morandi-100 rounded-xl focus:outline-none focus:border-morandi-400 transition-colors"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 pt-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="flex-1"
|
||||
onClick={() => setShowAddForm(false)}
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1 bg-morandi-400 hover:bg-morandi-500 text-white"
|
||||
onClick={handleAddCheckup}
|
||||
>
|
||||
添加
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
511
frontend/src/app/pages/CameraCapturePage.tsx
Normal file
511
frontend/src/app/pages/CameraCapturePage.tsx
Normal file
@@ -0,0 +1,511 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
Camera,
|
||||
X,
|
||||
Check,
|
||||
RotateCw,
|
||||
Zap,
|
||||
Image as ImageIcon,
|
||||
AlertCircle,
|
||||
Loader2,
|
||||
Plus,
|
||||
ChevronRight,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
uploadReportImage,
|
||||
addImageToReport,
|
||||
type UploadReportResponse,
|
||||
type OcrDataItem,
|
||||
} from "../services/api";
|
||||
|
||||
/** 压缩图片:限制最大宽度 1200px,JPEG 质量 0.7 */
|
||||
function compressImage(file: File, maxWidth = 1200, quality = 0.7): Promise<File> {
|
||||
return new Promise((resolve) => {
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
let { width, height } = img;
|
||||
if (width > maxWidth) {
|
||||
height = Math.round((height * maxWidth) / width);
|
||||
width = maxWidth;
|
||||
}
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.drawImage(img, 0, 0, width, height);
|
||||
canvas.toBlob(
|
||||
(blob) => {
|
||||
resolve(blob ? new File([blob], "report.jpg", { type: "image/jpeg" }) : file);
|
||||
},
|
||||
"image/jpeg",
|
||||
quality
|
||||
);
|
||||
};
|
||||
img.src = URL.createObjectURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
interface ImageEntry {
|
||||
id: string;
|
||||
preview: string; // data URL for thumbnail
|
||||
status: "uploading" | "done" | "error";
|
||||
error?: string;
|
||||
ocrItems: OcrDataItem[];
|
||||
reportType: string;
|
||||
}
|
||||
|
||||
export function CameraCapturePage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Multi-image state
|
||||
const [images, setImages] = useState<ImageEntry[]>([]);
|
||||
const [reportId, setReportId] = useState<string | null>(null);
|
||||
const [notPregnancyTip, setNotPregnancyTip] = useState<string | null>(null);
|
||||
|
||||
// Camera state
|
||||
const [isCapturing, setIsCapturing] = useState(true); // show camera view
|
||||
const [showTips, setShowTips] = useState(true);
|
||||
const [cameraError, setCameraError] = useState<string | null>(null);
|
||||
const [cameraReady, setCameraReady] = useState(false);
|
||||
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// 启动摄像头
|
||||
const startCamera = useCallback(async () => {
|
||||
try {
|
||||
setCameraError(null);
|
||||
if (!window.isSecureContext) {
|
||||
setCameraError("摄像头需要 HTTPS 安全连接,请使用「从相册选择」");
|
||||
return;
|
||||
}
|
||||
if (!navigator.mediaDevices?.getUserMedia) {
|
||||
setCameraError("当前浏览器不支持摄像头,请使用相册上传");
|
||||
return;
|
||||
}
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: { facingMode: "environment", width: { ideal: 1920 }, height: { ideal: 1080 } },
|
||||
audio: false,
|
||||
});
|
||||
streamRef.current = stream;
|
||||
if (videoRef.current) {
|
||||
videoRef.current.srcObject = stream;
|
||||
videoRef.current.onloadedmetadata = () => {
|
||||
videoRef.current?.play();
|
||||
setCameraReady(true);
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
setCameraError("无法访问摄像头,请检查权限设置或使用相册上传");
|
||||
}
|
||||
}, []);
|
||||
|
||||
const stopCamera = useCallback(() => {
|
||||
if (streamRef.current) {
|
||||
streamRef.current.getTracks().forEach((track) => track.stop());
|
||||
streamRef.current = null;
|
||||
}
|
||||
setCameraReady(false);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (isCapturing) startCamera();
|
||||
return () => stopCamera();
|
||||
}, [isCapturing, startCamera, stopCamera]);
|
||||
|
||||
// 上传单张图片(自动判断是首张还是追加)
|
||||
const uploadImage = useCallback(
|
||||
async (file: File, preview: string) => {
|
||||
const entryId = Date.now().toString();
|
||||
const entry: ImageEntry = {
|
||||
id: entryId,
|
||||
preview,
|
||||
status: "uploading",
|
||||
ocrItems: [],
|
||||
reportType: "",
|
||||
};
|
||||
setImages((prev) => [...prev, entry]);
|
||||
|
||||
try {
|
||||
const compressed = await compressImage(file);
|
||||
let ocrItems: OcrDataItem[] = [];
|
||||
let reportType = "";
|
||||
|
||||
if (!reportId) {
|
||||
// First image — create report
|
||||
const result: UploadReportResponse = await uploadReportImage(compressed);
|
||||
setReportId(result.report_id);
|
||||
ocrItems = result.ocr_result.data_items;
|
||||
reportType = result.ocr_result.report_type;
|
||||
} else {
|
||||
// Additional image — add to existing report
|
||||
const result = await addImageToReport(reportId, compressed);
|
||||
ocrItems = result.ocr_result.data_items;
|
||||
reportType = result.ocr_result.report_type;
|
||||
}
|
||||
|
||||
setImages((prev) =>
|
||||
prev.map((img) =>
|
||||
img.id === entryId
|
||||
? { ...img, status: "done", ocrItems, reportType }
|
||||
: img
|
||||
)
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : "识别失败";
|
||||
// 非孕期报告提示
|
||||
if (msg.includes("请上传孕期检查报告") || msg.includes("请上传孕期")) {
|
||||
setNotPregnancyTip(msg);
|
||||
// 移除该图片
|
||||
setImages((prev) => prev.filter((img) => img.id !== entryId));
|
||||
return;
|
||||
}
|
||||
const friendlyMsg = /load failed|failed to fetch|networkerror/i.test(msg)
|
||||
? "网络连接失败"
|
||||
: msg.length > 100
|
||||
? "AI 识别服务暂时不可用"
|
||||
: msg;
|
||||
setImages((prev) =>
|
||||
prev.map((img) =>
|
||||
img.id === entryId ? { ...img, status: "error", error: friendlyMsg } : img
|
||||
)
|
||||
);
|
||||
}
|
||||
},
|
||||
[reportId]
|
||||
);
|
||||
|
||||
// 拍照
|
||||
const handleCapture = () => {
|
||||
if (!videoRef.current || !canvasRef.current) return;
|
||||
const video = videoRef.current;
|
||||
const canvas = canvasRef.current;
|
||||
canvas.width = video.videoWidth;
|
||||
canvas.height = video.videoHeight;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
ctx.drawImage(video, 0, 0);
|
||||
const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
|
||||
setShowTips(false);
|
||||
canvas.toBlob((blob) => {
|
||||
if (blob) {
|
||||
const file = new File([blob], "report.jpg", { type: "image/jpeg" });
|
||||
uploadImage(file, dataUrl);
|
||||
}
|
||||
}, "image/jpeg", 0.9);
|
||||
};
|
||||
|
||||
// 相册选择(支持多选)
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files;
|
||||
if (!files?.length) return;
|
||||
setShowTips(false);
|
||||
Array.from(files).forEach((file) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (ev) => {
|
||||
const preview = ev.target?.result as string;
|
||||
uploadImage(file, preview);
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
e.target.value = "";
|
||||
};
|
||||
|
||||
// 删除某张图片(仅从前端列表移除,不影响已上传的数据)
|
||||
const removeImage = (id: string) => {
|
||||
setImages((prev) => prev.filter((img) => img.id !== id));
|
||||
};
|
||||
|
||||
// 统计
|
||||
const doneCount = images.filter((img) => img.status === "done").length;
|
||||
const uploadingCount = images.filter((img) => img.status === "uploading").length;
|
||||
const totalOcrItems = images.reduce((sum, img) => sum + img.ocrItems.length, 0);
|
||||
const allDone = images.length > 0 && uploadingCount === 0;
|
||||
|
||||
// 进入校验页面
|
||||
const handleGoToVerify = () => {
|
||||
if (!reportId || !allDone) return;
|
||||
// Merge all OCR items for navigation state
|
||||
const mergedItems = images.flatMap((img) => img.ocrItems);
|
||||
const reportTypes = [...new Set(images.map((img) => img.reportType).filter(Boolean))];
|
||||
navigate("/verify", {
|
||||
state: {
|
||||
reportId,
|
||||
ocrResult: {
|
||||
report_type: reportTypes.join("+"),
|
||||
data_items: mergedItems,
|
||||
patient_name: "",
|
||||
},
|
||||
imageUrls: images.map((img) => img.preview),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const handleAlbumClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-black relative overflow-hidden">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
<canvas ref={canvasRef} className="hidden" />
|
||||
|
||||
{/* 顶部导航栏 */}
|
||||
<div className="absolute top-0 left-0 right-0 z-20 bg-gradient-to-b from-black/50 to-transparent">
|
||||
<div className="flex items-center justify-between p-4">
|
||||
<button
|
||||
onClick={() => { stopCamera(); navigate(-1); }}
|
||||
className="p-2 rounded-full bg-black/30 backdrop-blur-sm"
|
||||
>
|
||||
<X className="w-6 h-6 text-white" />
|
||||
</button>
|
||||
<h1 className="text-white font-medium">拍摄检查报告</h1>
|
||||
<div className="w-10" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 相机预览区域 */}
|
||||
<div className="relative w-full h-screen flex items-center justify-center">
|
||||
<video
|
||||
ref={videoRef}
|
||||
autoPlay playsInline muted
|
||||
className={`w-full h-full object-cover ${cameraReady ? "block" : "hidden"}`}
|
||||
/>
|
||||
{!cameraReady && (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
|
||||
className="w-full h-full bg-gray-900 flex items-center justify-center">
|
||||
<div className="text-center px-8">
|
||||
{cameraError ? (
|
||||
<>
|
||||
<AlertCircle className="w-12 h-12 text-gray-500 mx-auto mb-4" />
|
||||
<p className="text-gray-400 text-sm mb-4">{cameraError}</p>
|
||||
<Button onClick={handleAlbumClick} className="bg-morandi-400 hover:bg-morandi-500 text-white">
|
||||
<ImageIcon className="w-4 h-4 mr-2" />从相册选择
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<motion.div animate={{ rotate: 360 }} transition={{ duration: 2, repeat: Infinity, ease: "linear" }}>
|
||||
<Camera className="w-12 h-12 text-gray-500 mx-auto" />
|
||||
</motion.div>
|
||||
<p className="text-gray-400 mt-4">正在启动摄像头...</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 取景框辅助线 */}
|
||||
{cameraReady && (
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}
|
||||
className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
<div className="relative w-11/12 max-w-md aspect-[3/4] border-2 border-white/50 rounded-2xl">
|
||||
<div className="absolute top-0 left-0 w-8 h-8 border-l-4 border-t-4 border-morandi-500 rounded-tl-2xl" />
|
||||
<div className="absolute top-0 right-0 w-8 h-8 border-r-4 border-t-4 border-morandi-500 rounded-tr-2xl" />
|
||||
<div className="absolute bottom-0 left-0 w-8 h-8 border-l-4 border-b-4 border-morandi-500 rounded-bl-2xl" />
|
||||
<div className="absolute bottom-0 right-0 w-8 h-8 border-r-4 border-b-4 border-morandi-500 rounded-br-2xl" />
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 拍摄提示 */}
|
||||
<AnimatePresence>
|
||||
{showTips && cameraReady && images.length === 0 && (
|
||||
<motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -20 }}
|
||||
className="absolute top-24 left-0 right-0 z-10">
|
||||
<div className="mx-auto max-w-sm px-4">
|
||||
<div className="bg-morandi-400 text-white rounded-2xl p-4 shadow-sm">
|
||||
<div className="flex items-start gap-3">
|
||||
<Zap className="w-5 h-5 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<h3 className="font-semibold mb-1">支持多张报告</h3>
|
||||
<ul className="text-sm space-y-1 opacity-90">
|
||||
<li>- 可拍摄多张报告,AI 合并解读</li>
|
||||
<li>- 确保光线充足,避免反光</li>
|
||||
<li>- 将报告完整放入取景框内</li>
|
||||
</ul>
|
||||
</div>
|
||||
<button onClick={() => setShowTips(false)} className="p-1 hover:bg-white/20 rounded-lg">
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
{/* 已添加图片缩略图条 */}
|
||||
{images.length > 0 && (
|
||||
<div className="absolute top-20 left-0 right-0 z-10 px-4">
|
||||
<div className="mx-auto max-w-lg">
|
||||
<div className="bg-black/60 backdrop-blur-sm rounded-2xl p-3">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-white text-sm font-medium">
|
||||
已添加 {images.length} 张报告
|
||||
{totalOcrItems > 0 && (
|
||||
<span className="text-white/70 ml-1">· {totalOcrItems} 项指标</span>
|
||||
)}
|
||||
</span>
|
||||
{uploadingCount > 0 && (
|
||||
<span className="text-amber-300 text-xs flex items-center">
|
||||
<Loader2 className="w-3 h-3 mr-1 animate-spin" />
|
||||
识别中 {uploadingCount} 张
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2 overflow-x-auto pb-1">
|
||||
{images.map((img) => (
|
||||
<div key={img.id} className="relative flex-shrink-0 w-16 h-16 rounded-xl overflow-hidden">
|
||||
<img src={img.preview} alt="" className="w-full h-full object-cover" />
|
||||
{/* Status overlay */}
|
||||
{img.status === "uploading" && (
|
||||
<div className="absolute inset-0 bg-black/50 flex items-center justify-center">
|
||||
<Loader2 className="w-5 h-5 text-white animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
{img.status === "done" && (
|
||||
<div className="absolute top-1 right-1 w-5 h-5 bg-green-500 rounded-full flex items-center justify-center">
|
||||
<Check className="w-3 h-3 text-white" />
|
||||
</div>
|
||||
)}
|
||||
{img.status === "error" && (
|
||||
<div className="absolute inset-0 bg-red-500/50 flex items-center justify-center">
|
||||
<AlertCircle className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
)}
|
||||
{/* Remove button */}
|
||||
<button
|
||||
onClick={() => removeImage(img.id)}
|
||||
className="absolute top-1 left-1 w-5 h-5 bg-black/60 rounded-full flex items-center justify-center"
|
||||
>
|
||||
<X className="w-3 h-3 text-white" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 底部操作区 */}
|
||||
<div className="absolute bottom-0 left-0 right-0 z-20 bg-gradient-to-t from-black/80 to-transparent pb-8 pt-12">
|
||||
<div className="mx-auto px-4">
|
||||
{/* 主操作按钮行 */}
|
||||
<div className="flex items-center justify-center gap-8">
|
||||
{/* 相册 */}
|
||||
<motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className="text-center">
|
||||
<Button onClick={handleAlbumClick} variant="outline" size="lg"
|
||||
className="w-16 h-16 rounded-full bg-white/20 backdrop-blur-sm border-2 border-white/50 hover:bg-white/30">
|
||||
<ImageIcon className="w-6 h-6 text-white" />
|
||||
</Button>
|
||||
<p className="text-white text-xs text-center mt-2">相册</p>
|
||||
</motion.div>
|
||||
|
||||
{/* 拍摄 */}
|
||||
<motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ delay: 0.1 }} className="text-center">
|
||||
<Button onClick={handleCapture} disabled={!cameraReady} size="lg"
|
||||
className="w-20 h-20 rounded-full bg-white hover:bg-gray-100 shadow-sm shadow-white/50 border-4 border-gray-800 disabled:opacity-50">
|
||||
<div className="w-16 h-16 rounded-full bg-gradient-to-br from-morandi-400 to-morandi-500" />
|
||||
</Button>
|
||||
<p className="text-white text-sm text-center mt-2 font-medium">拍摄</p>
|
||||
</motion.div>
|
||||
|
||||
{/* 开始解读 / 继续添加状态 */}
|
||||
<motion.div initial={{ scale: 0.8, opacity: 0 }} animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ delay: 0.2 }} className="text-center">
|
||||
{images.length > 0 ? (
|
||||
<>
|
||||
<Button
|
||||
onClick={handleGoToVerify}
|
||||
disabled={!allDone || doneCount === 0}
|
||||
size="lg"
|
||||
className="w-16 h-16 rounded-full bg-gradient-to-br from-green-500 to-emerald-600 hover:from-green-600 hover:to-emerald-700 shadow-sm disabled:opacity-50"
|
||||
>
|
||||
<ChevronRight className="w-7 h-7 text-white" />
|
||||
</Button>
|
||||
<p className="text-white text-xs text-center mt-2">
|
||||
{uploadingCount > 0 ? "识别中..." : "开始解读"}
|
||||
</p>
|
||||
</>
|
||||
) : (
|
||||
<div className="w-16" />
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 隐私保护提示 */}
|
||||
{images.length === 0 && !notPregnancyTip && (
|
||||
<div className="absolute bottom-32 left-0 right-0 z-10">
|
||||
<div className="mx-auto max-w-sm px-4">
|
||||
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.5 }}
|
||||
className="bg-black/50 backdrop-blur-sm text-white rounded-xl p-3 flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4 flex-shrink-0" />
|
||||
<p className="text-xs opacity-90">您的隐私受到保护,个人信息将自动脱敏处理</p>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 非孕期报告提示弹窗 */}
|
||||
<AnimatePresence>
|
||||
{notPregnancyTip && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-8"
|
||||
onClick={() => setNotPregnancyTip(null)}
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.85, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.85, opacity: 0 }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-white rounded-2xl p-6 w-full max-w-sm shadow-xl"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-3 mb-5">
|
||||
<div className="w-14 h-14 bg-amber-50 rounded-full flex items-center justify-center">
|
||||
<AlertCircle className="w-7 h-7 text-amber-500" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-gray-800 text-lg">非孕期报告</h3>
|
||||
<p className="text-sm text-gray-500 text-center leading-relaxed">
|
||||
{notPregnancyTip}
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-amber-50 rounded-xl p-3 mb-5">
|
||||
<p className="text-xs text-gray-600 leading-relaxed">
|
||||
💡 支持的报告类型:B超/彩超、血常规、尿常规、唐氏筛查、糖耐量、肝肾功能、TORCH、甲功等孕期产检报告
|
||||
</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => setNotPregnancyTip(null)}
|
||||
className="w-full h-11 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
|
||||
>
|
||||
我知道了,重新上传
|
||||
</Button>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
398
frontend/src/app/pages/DataVerificationPage.tsx
Normal file
398
frontend/src/app/pages/DataVerificationPage.tsx
Normal file
@@ -0,0 +1,398 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate, useLocation } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
Check,
|
||||
X,
|
||||
Edit2,
|
||||
ChevronLeft,
|
||||
CheckCircle2,
|
||||
Info,
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Checkbox } from "../components/ui/checkbox";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { verifyReport } from "../services/api";
|
||||
|
||||
interface DataItem {
|
||||
id: string;
|
||||
name: string;
|
||||
value: string;
|
||||
unit: string;
|
||||
referenceRange: string;
|
||||
status: "normal" | "high" | "low";
|
||||
editable: boolean;
|
||||
category: string;
|
||||
}
|
||||
|
||||
export function DataVerificationPage() {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { reportId, ocrResult, imageUrls } = (location.state || {}) as {
|
||||
reportId?: string;
|
||||
ocrResult?: { report_type: string; data_items: { name: string; value: string; unit: string; reference_range: string; status: "normal" | "high" | "low"; category: string }[]; patient_name: string };
|
||||
imageUrl?: string;
|
||||
imageUrls?: string[];
|
||||
};
|
||||
const imageCount = imageUrls?.length || 1;
|
||||
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [symptoms, setSymptoms] = useState<string[]>([]);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
|
||||
// Initialize from OCR data or fallback to empty
|
||||
const initialItems: DataItem[] = ocrResult?.data_items?.map((item, i) => ({
|
||||
id: String(i),
|
||||
name: item.name,
|
||||
value: item.value,
|
||||
unit: item.unit,
|
||||
referenceRange: item.reference_range,
|
||||
status: item.status,
|
||||
editable: true,
|
||||
category: item.category || "检查项目",
|
||||
})) || [];
|
||||
|
||||
const [dataItems, setDataItems] = useState<DataItem[]>(initialItems);
|
||||
const [expandedCategories, setExpandedCategories] = useState<string[]>(
|
||||
() => {
|
||||
const cats = Array.from(new Set(initialItems.map((item) => item.category)));
|
||||
return cats.length > 0 ? [cats[0]] : [];
|
||||
}
|
||||
);
|
||||
|
||||
const symptomOptions = [
|
||||
{ id: "bleeding", label: "见红", icon: "🩸" },
|
||||
{ id: "pain", label: "腹痛", icon: "💔" },
|
||||
{ id: "vomit", label: "严重孕吐", icon: "🤢" },
|
||||
{ id: "dizzy", label: "头晕", icon: "😵" },
|
||||
{ id: "tired", label: "极度疲劳", icon: "😴" },
|
||||
];
|
||||
|
||||
const categories = Array.from(new Set(dataItems.map((item) => item.category)));
|
||||
|
||||
const handleEdit = (id: string) => {
|
||||
setEditingId(id);
|
||||
};
|
||||
|
||||
const handleSave = (id: string, newValue: string) => {
|
||||
setDataItems(
|
||||
dataItems.map((item) =>
|
||||
item.id === id ? { ...item, value: newValue } : item
|
||||
)
|
||||
);
|
||||
setEditingId(null);
|
||||
};
|
||||
|
||||
const handleSymptomToggle = (symptomId: string) => {
|
||||
setSymptoms(
|
||||
symptoms.includes(symptomId)
|
||||
? symptoms.filter((s) => s !== symptomId)
|
||||
: [...symptoms, symptomId]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleCategory = (category: string) => {
|
||||
setExpandedCategories(
|
||||
expandedCategories.includes(category)
|
||||
? expandedCategories.filter((c) => c !== category)
|
||||
: [...expandedCategories, category]
|
||||
);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!reportId) {
|
||||
navigate("/camera");
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
setSubmitError(null);
|
||||
try {
|
||||
await verifyReport(reportId, {
|
||||
data_items: dataItems.map((item) => ({
|
||||
name: item.name,
|
||||
value: item.value,
|
||||
unit: item.unit,
|
||||
reference_range: item.referenceRange,
|
||||
status: item.status,
|
||||
category: item.category,
|
||||
})),
|
||||
symptoms,
|
||||
notes: "",
|
||||
report_type: ocrResult?.report_type,
|
||||
});
|
||||
navigate(`/analysis/${reportId}`);
|
||||
} catch (err: unknown) {
|
||||
setSubmitError(err instanceof Error ? err.message : "提交失败,请重试");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const totalCount = dataItems.length;
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="flex items-center text-gray-600 hover:text-gray-900"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5 mr-1" />
|
||||
返回
|
||||
</button>
|
||||
<h1 className="font-semibold text-gray-800">数据核对</h1>
|
||||
<div className="w-16"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 识别状态卡片 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="bg-white rounded-3xl shadow-sm p-6"
|
||||
>
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 bg-morandi-sage-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
<CheckCircle2 className="w-6 h-6 text-morandi-sage-400" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h2 className="font-semibold text-gray-800 mb-1">
|
||||
识别完成!
|
||||
</h2>
|
||||
<p className="text-sm text-gray-600 mb-3">
|
||||
{imageCount > 1 ? `已从 ${imageCount} 张报告中` : "已"}识别 {totalCount} 项指标,请核对数据是否准确
|
||||
</p>
|
||||
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100">
|
||||
共 {totalCount} 项
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 快速操作提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
className="bg-morandi-50 border border-morandi-200 rounded-2xl p-4"
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<Info className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="flex-1">
|
||||
<p className="text-sm text-morandi-500 font-medium mb-1">
|
||||
快速校对指南
|
||||
</p>
|
||||
<p className="text-xs text-morandi-600 leading-relaxed">
|
||||
• 点击数值可快速编辑 • 请仔细核对识别结果 • 确认无误后生成AI解读
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 数据列表 - 按分类展示 */}
|
||||
<div className="space-y-4">
|
||||
{categories.map((category, categoryIndex) => {
|
||||
const categoryItems = dataItems.filter((item) => item.category === category);
|
||||
const isExpanded = expandedCategories.includes(category);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
key={category}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 + categoryIndex * 0.1 }}
|
||||
className="bg-white rounded-3xl shadow-sm overflow-hidden"
|
||||
>
|
||||
{/* 分类标题 */}
|
||||
<button
|
||||
onClick={() => toggleCategory(category)}
|
||||
className="w-full px-6 py-4 flex items-center justify-between hover:bg-gray-50 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<h3 className="font-semibold text-gray-800">{category}</h3>
|
||||
<Badge variant="secondary" className="bg-gray-100 text-gray-600">
|
||||
{categoryItems.length} 项
|
||||
</Badge>
|
||||
</div>
|
||||
{isExpanded ? (
|
||||
<ChevronUp className="w-5 h-5 text-gray-400" />
|
||||
) : (
|
||||
<ChevronDown className="w-5 h-5 text-gray-400" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* 分类项目列表 */}
|
||||
<AnimatePresence>
|
||||
{isExpanded && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: "auto", opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
transition={{ duration: 0.3 }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="px-4 pb-4 space-y-2">
|
||||
{categoryItems.map((item, index) => (
|
||||
<motion.div
|
||||
key={item.id}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: index * 0.05 }}
|
||||
className="rounded-2xl p-4 border-2 transition-all bg-white border-gray-100 hover:border-gray-200"
|
||||
>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<h4 className="font-medium text-gray-800">
|
||||
{item.name}
|
||||
</h4>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => handleEdit(item.id)}
|
||||
className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
|
||||
>
|
||||
<Edit2 className="w-4 h-4 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="flex items-end gap-4">
|
||||
{editingId === item.id ? (
|
||||
<div className="flex-1 flex items-center gap-2">
|
||||
<Input
|
||||
type="text"
|
||||
defaultValue={item.value}
|
||||
autoFocus
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") {
|
||||
handleSave(
|
||||
item.id,
|
||||
e.currentTarget.value
|
||||
);
|
||||
}
|
||||
}}
|
||||
className="h-10 rounded-xl border-2 border-morandi-200 focus:border-morandi-500"
|
||||
/>
|
||||
<Button
|
||||
onClick={() =>
|
||||
handleSave(
|
||||
item.id,
|
||||
(document.querySelector(`input`) as HTMLInputElement)?.value || item.value
|
||||
)
|
||||
}
|
||||
size="sm"
|
||||
className="h-10 bg-morandi-sage-400 hover:bg-morandi-sage-500"
|
||||
>
|
||||
<Check className="w-4 h-4" />
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => setEditingId(null)}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-10"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex-1">
|
||||
<div className="flex items-baseline gap-2 mb-1">
|
||||
<span className="text-2xl font-semibold text-gray-800">
|
||||
{item.value}
|
||||
</span>
|
||||
<span className="text-sm text-gray-500">
|
||||
{item.unit}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">
|
||||
参考范围:{item.referenceRange}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* 症状勾选 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
className="bg-white rounded-3xl shadow-sm p-6"
|
||||
>
|
||||
<h3 className="font-semibold text-gray-800 mb-4">
|
||||
当前身体状况(可选)
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600 mb-4">
|
||||
勾选您目前的症状,帮助 AI 进行更准确的健康评估
|
||||
</p>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{symptomOptions.map((symptom) => (
|
||||
<label
|
||||
key={symptom.id}
|
||||
className={`flex items-center gap-3 p-4 rounded-2xl border-2 cursor-pointer transition-all ${
|
||||
symptoms.includes(symptom.id)
|
||||
? "border-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
<Checkbox
|
||||
checked={symptoms.includes(symptom.id)}
|
||||
onCheckedChange={() => handleSymptomToggle(symptom.id)}
|
||||
className="w-5 h-5"
|
||||
/>
|
||||
<div className="flex-1">
|
||||
<span className="text-2xl mr-2">{symptom.icon}</span>
|
||||
<span className="text-sm font-medium text-gray-700">
|
||||
{symptom.label}
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 提交按钮 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.6 }}
|
||||
className="sticky bottom-4"
|
||||
>
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={submitting}
|
||||
className="w-full h-14 rounded-2xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium shadow-sm"
|
||||
>
|
||||
{submitting ? (
|
||||
<Loader2 className="w-5 h-5 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Check className="w-5 h-5 mr-2" />
|
||||
)}
|
||||
{submitting ? "提交中..." : "确认并生成 AI 解读"}
|
||||
</Button>
|
||||
{submitError && (
|
||||
<p className="text-red-500 text-sm text-center mt-2">{submitError}</p>
|
||||
)}
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
225
frontend/src/app/pages/DevNavigationPage.tsx
Normal file
225
frontend/src/app/pages/DevNavigationPage.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
import { useNavigate } from "react-router";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
LogIn,
|
||||
UserPlus,
|
||||
Home,
|
||||
Camera,
|
||||
FileCheck,
|
||||
Sparkles,
|
||||
FileText,
|
||||
MessageCircle,
|
||||
Mic,
|
||||
HeartPulse,
|
||||
TrendingUp,
|
||||
Clock,
|
||||
CalendarDays,
|
||||
Stethoscope,
|
||||
Share2,
|
||||
Users,
|
||||
Bell,
|
||||
User,
|
||||
} from "lucide-react";
|
||||
|
||||
export function DevNavigationPage() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const modules = [
|
||||
{
|
||||
title: "模块一:登录与初始化",
|
||||
pages: [
|
||||
{
|
||||
name: "登录页面",
|
||||
path: "/",
|
||||
icon: LogIn,
|
||||
description: "支持微信、手机号、Apple ID登录",
|
||||
},
|
||||
{
|
||||
name: "用户画像页面",
|
||||
path: "/onboarding",
|
||||
icon: UserPlus,
|
||||
description: "收集孕周信息和个人资料",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "模块二:报告采集与录入",
|
||||
pages: [
|
||||
{
|
||||
name: "首页",
|
||||
path: "/home",
|
||||
icon: Home,
|
||||
description: "报告管理中心,查看孕周信息",
|
||||
},
|
||||
{
|
||||
name: "OCR 拍照页面",
|
||||
path: "/camera",
|
||||
icon: Camera,
|
||||
description: "智能拍照识别检查报告",
|
||||
},
|
||||
{
|
||||
name: "数据校对页面",
|
||||
path: "/review",
|
||||
icon: FileCheck,
|
||||
description: "校对OCR识别结果,补充信息",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "模块三:AI 解读与互动",
|
||||
pages: [
|
||||
{
|
||||
name: "AI 智能解读",
|
||||
path: "/analysis/1",
|
||||
icon: Sparkles,
|
||||
description: "查看AI生成的报告解读",
|
||||
},
|
||||
{
|
||||
name: "报告详情",
|
||||
path: "/report/1",
|
||||
icon: FileText,
|
||||
description: "查看原始报告完整数据",
|
||||
},
|
||||
{
|
||||
name: "AI 追问对话",
|
||||
path: "/chat/1",
|
||||
icon: MessageCircle,
|
||||
description: "针对报告结果AI追问",
|
||||
},
|
||||
{
|
||||
name: "问诊清单",
|
||||
path: "/doctor-questions/1",
|
||||
icon: Stethoscope,
|
||||
description: "AI生成看医生时的问题清单",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "模块四:健康建议",
|
||||
pages: [
|
||||
{
|
||||
name: "语音记录",
|
||||
path: "/voice-record",
|
||||
icon: Mic,
|
||||
description: "语音记录症状和感受",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "模块五:健康档案",
|
||||
pages: [
|
||||
{
|
||||
name: "健康档案",
|
||||
path: "/health-records",
|
||||
icon: HeartPulse,
|
||||
description: "健康数据概览",
|
||||
},
|
||||
{
|
||||
name: "生长曲线",
|
||||
path: "/growth-curve",
|
||||
icon: TrendingUp,
|
||||
description: "胎儿生长发育曲线",
|
||||
},
|
||||
{
|
||||
name: "报告时间轴",
|
||||
path: "/timeline",
|
||||
icon: Clock,
|
||||
description: "检查报告历史时间轴",
|
||||
},
|
||||
{
|
||||
name: "产检日历",
|
||||
path: "/calendar",
|
||||
icon: CalendarDays,
|
||||
description: "产检计划与提醒",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "模块六:个人中心",
|
||||
pages: [
|
||||
{
|
||||
name: "个人主页",
|
||||
path: "/profile",
|
||||
icon: User,
|
||||
description: "用户资料与设置",
|
||||
},
|
||||
{
|
||||
name: "消息中心",
|
||||
path: "/notifications",
|
||||
icon: Bell,
|
||||
description: "产检提醒与消息通知",
|
||||
},
|
||||
{
|
||||
name: "分享报告",
|
||||
path: "/share/1",
|
||||
icon: Share2,
|
||||
description: "隐私脱敏分享解读结果",
|
||||
},
|
||||
{
|
||||
name: "专家咨询",
|
||||
path: "/expert-consultation",
|
||||
icon: Users,
|
||||
description: "在线问诊专家列表",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-morandi-50 p-8">
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<div className="text-center mb-8">
|
||||
<h1 className="text-3xl font-semibold text-gray-800 mb-2">
|
||||
孕育无忧 - 孕期健康检查报告解读
|
||||
</h1>
|
||||
<p className="text-gray-600">开发者导航 - 快速访问所有页面</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{modules.map((module, moduleIndex) => (
|
||||
<Card
|
||||
key={moduleIndex}
|
||||
className="bg-white rounded-2xl p-6 shadow-sm border-0"
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4 pb-3 border-b-2 border-gray-100">
|
||||
{module.title}
|
||||
</h2>
|
||||
<div className="space-y-3">
|
||||
{module.pages.map((page, pageIndex) => (
|
||||
<Button
|
||||
key={pageIndex}
|
||||
onClick={() => navigate(page.path)}
|
||||
variant="outline"
|
||||
className="w-full justify-start h-auto p-4 hover:bg-morandi-50 hover:border-morandi-200 transition-all group"
|
||||
>
|
||||
<div className="flex items-start gap-3 w-full">
|
||||
<div className="mt-1">
|
||||
<page.icon className="w-5 h-5 text-morandi-400 group-hover:text-morandi-500" />
|
||||
</div>
|
||||
<div className="flex-1 text-left">
|
||||
<div className="font-semibold text-gray-800 mb-1">
|
||||
{page.name}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">
|
||||
{page.description}
|
||||
</div>
|
||||
<div className="text-xs text-morandi-400 mt-1 font-mono">
|
||||
{page.path}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-center text-sm text-gray-500">
|
||||
<p>共 {modules.reduce((sum, m) => sum + m.pages.length, 0)} 个页面 | React + TypeScript + Tailwind CSS</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
284
frontend/src/app/pages/DoctorQuestionsPage.tsx
Normal file
284
frontend/src/app/pages/DoctorQuestionsPage.tsx
Normal file
@@ -0,0 +1,284 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Copy,
|
||||
Check,
|
||||
MessageCircle,
|
||||
Clipboard,
|
||||
Share2,
|
||||
Download,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { getDoctorQuestions } from "../services/api";
|
||||
|
||||
interface Question {
|
||||
id: string;
|
||||
category: string;
|
||||
question: string;
|
||||
reason: string;
|
||||
priority: "high" | "medium" | "low";
|
||||
}
|
||||
|
||||
export function DoctorQuestionsPage() {
|
||||
const navigate = useNavigate();
|
||||
const { reportId } = useParams();
|
||||
const [copiedId, setCopiedId] = useState(null);
|
||||
const [questions, setQuestions] = useState<Question[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!reportId) return;
|
||||
getDoctorQuestions(reportId)
|
||||
.then((data) => {
|
||||
setQuestions(
|
||||
data.questions.map((q, i) => ({
|
||||
id: String(i),
|
||||
category: q.category,
|
||||
question: q.question,
|
||||
reason: q.reason,
|
||||
priority: (i < 2 ? "high" : i < 4 ? "medium" : "low") as Question["priority"],
|
||||
}))
|
||||
);
|
||||
})
|
||||
.catch(() => {/* keep empty */})
|
||||
.finally(() => setLoading(false));
|
||||
}, [reportId]);
|
||||
|
||||
const handleCopy = (text: string, id: string) => {
|
||||
navigator.clipboard.writeText(text);
|
||||
setCopiedId(id);
|
||||
setTimeout(() => setCopiedId(null), 2000);
|
||||
};
|
||||
|
||||
const handleCopyAll = () => {
|
||||
const allQuestions = questions
|
||||
.map((q, index) => `${index + 1}. ${q.question}`)
|
||||
.join("\n\n");
|
||||
navigator.clipboard.writeText(allQuestions);
|
||||
setCopiedId("all");
|
||||
setTimeout(() => setCopiedId(null), 2000);
|
||||
};
|
||||
|
||||
const priorityLabels = {
|
||||
high: { text: "重要", color: "bg-red-100 text-red-700" },
|
||||
medium: { text: "建议", color: "bg-morandi-rose-100 text-morandi-rose-400" },
|
||||
low: { text: "了解", color: "bg-morandi-50 text-morandi-500" },
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin mx-auto mb-3" />
|
||||
<p className="text-sm text-gray-500">正在生成问诊清单...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
|
||||
<MessageCircle className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">问诊清单</h1>
|
||||
<p className="text-xs text-gray-500">
|
||||
智能生成{questions.length}个问题
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handleCopyAll}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="rounded-full"
|
||||
>
|
||||
{copiedId === "all" ? (
|
||||
<>
|
||||
<Check className="w-4 h-4 mr-2" />
|
||||
已复制
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Clipboard className="w-4 h-4 mr-2" />
|
||||
全部复制
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 使用说明 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-500 border-0 text-white p-6 rounded-3xl shadow-sm">
|
||||
<h2 className="text-xl font-semibold mb-3">💬 如何使用问诊清单</h2>
|
||||
<div className="space-y-2 text-sm text-white/90">
|
||||
<p>✓ 基于您的报告异常项,AI智能生成针对性问题</p>
|
||||
<p>✓ 点击单个问题可复制,方便向医生提问</p>
|
||||
<p>✓ 可一键复制全部问题,就诊时查看</p>
|
||||
<p>✓ 按优先级排序,重要问题优先询问</p>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 问题列表 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
📋 建议咨询的问题
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
{questions.map((question, index) => (
|
||||
<motion.div
|
||||
key={question.id}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.2 + index * 0.05 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0 hover:shadow-md transition-shadow">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="flex-shrink-0 w-8 h-8 bg-morandi-100 text-morandi-500 rounded-full flex items-center justify-center font-semibold text-sm">
|
||||
{index + 1}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-3">
|
||||
<Badge
|
||||
className={`${
|
||||
priorityLabels[question.priority].color
|
||||
} hover:bg-current`}
|
||||
>
|
||||
{priorityLabels[question.priority].text}
|
||||
</Badge>
|
||||
<span className="text-xs text-gray-500">
|
||||
{question.category}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p className="text-gray-800 leading-relaxed mb-3 font-medium">
|
||||
{question.question}
|
||||
</p>
|
||||
|
||||
<div className="bg-morandi-slate-50 rounded-xl p-3 mb-3">
|
||||
<p className="text-sm text-morandi-500">
|
||||
💡 <strong>为什么问:</strong>
|
||||
{question.reason}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() =>
|
||||
handleCopy(question.question, question.id)
|
||||
}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
>
|
||||
{copiedId === question.id ? (
|
||||
<>
|
||||
<Check className="w-4 h-4 mr-2" />
|
||||
已复制
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="w-4 h-4 mr-2" />
|
||||
复制此问题
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 其他建议 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<h3 className="font-semibold text-gray-800 mb-3 flex items-center gap-2">
|
||||
<MessageCircle className="w-5 h-5 text-morandi-400" />
|
||||
💡 就诊小贴士
|
||||
</h3>
|
||||
<ul className="space-y-2 text-sm text-gray-600">
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
|
||||
<span>
|
||||
问诊时可以拿出手机查看问题清单,避免紧张时忘记要问的内容
|
||||
</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
|
||||
<span>听从医生建议,记录重要的用药和注意事项</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
|
||||
<span>如医生时间有限,优先询问标记为"重要"的问题</span>
|
||||
</li>
|
||||
<li className="flex items-start gap-2">
|
||||
<span className="flex-shrink-0 w-1.5 h-1.5 bg-morandi-400 rounded-full mt-2"></span>
|
||||
<span>
|
||||
就诊后可返回APP查看AI建议,结合医生意见调整生活方式
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 底部操作 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.6 }}
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-12"
|
||||
onClick={() => navigate(`/share/${reportId}`)}
|
||||
>
|
||||
<Share2 className="w-4 h-4 mr-2" />
|
||||
分享清单
|
||||
</Button>
|
||||
<Button className="h-12 bg-morandi-400">
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
导出PDF
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
334
frontend/src/app/pages/ExpertConsultationPage.tsx
Normal file
334
frontend/src/app/pages/ExpertConsultationPage.tsx
Normal file
@@ -0,0 +1,334 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
UserCheck,
|
||||
Star,
|
||||
Clock,
|
||||
MessageCircle,
|
||||
Video,
|
||||
FileText,
|
||||
Award,
|
||||
ThumbsUp,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { getExperts, type Doctor as DoctorDTO } from "../services/api";
|
||||
|
||||
interface Doctor {
|
||||
id: string;
|
||||
name: string;
|
||||
title: string;
|
||||
hospital: string;
|
||||
specialty: string;
|
||||
experience: string;
|
||||
rating: number;
|
||||
reviewCount: number;
|
||||
consultCount: number;
|
||||
responseTime: string;
|
||||
price: number;
|
||||
avatar: string;
|
||||
tags: string[];
|
||||
}
|
||||
|
||||
export function ExpertConsultationPage() {
|
||||
const navigate = useNavigate();
|
||||
const [selectedService, setSelectedService] = useState("text");
|
||||
const [doctors, setDoctors] = useState<Doctor[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
getExperts()
|
||||
.then((data) => {
|
||||
setDoctors(
|
||||
data.doctors.map((d) => ({
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
title: d.title,
|
||||
hospital: d.hospital,
|
||||
specialty: d.specialty,
|
||||
experience: d.experience,
|
||||
rating: d.rating,
|
||||
reviewCount: d.review_count,
|
||||
consultCount: d.consult_count,
|
||||
responseTime: d.response_time,
|
||||
price: d.price?.text || 50,
|
||||
avatar: "",
|
||||
tags: d.tags,
|
||||
}))
|
||||
);
|
||||
})
|
||||
.catch(() => {/* keep empty */})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const services = [
|
||||
{
|
||||
id: "text",
|
||||
name: "图文咨询",
|
||||
icon: MessageCircle,
|
||||
price: 50,
|
||||
time: "24小时内回复",
|
||||
description: "上传报告,医生详细解读",
|
||||
},
|
||||
{
|
||||
id: "video",
|
||||
name: "视频问诊",
|
||||
icon: Video,
|
||||
price: 200,
|
||||
time: "预约时间",
|
||||
description: "面对面沟通,更加详细",
|
||||
},
|
||||
{
|
||||
id: "urgent",
|
||||
name: "加急咨询",
|
||||
icon: Clock,
|
||||
price: 100,
|
||||
time: "2小时内回复",
|
||||
description: "紧急情况,优先处理",
|
||||
},
|
||||
];
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
|
||||
<UserCheck className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">专家复核</h1>
|
||||
<p className="text-xs text-gray-500">专业医生在线解答</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 服务介绍 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-500 border-0 text-white p-6 rounded-3xl shadow-sm">
|
||||
<h2 className="text-xl font-semibold mb-3">👨⚕️ 为什么需要专家复核</h2>
|
||||
<div className="space-y-2 text-sm text-white/90">
|
||||
<p>✓ AI解读仅供参考,复杂情况需专业医生判断</p>
|
||||
<p>✓ 三甲医院主任医师,20年+临床经验</p>
|
||||
<p>✓ 一对一解答,针对您的具体情况给出建议</p>
|
||||
<p>✓ 支持图文、视频多种咨询方式</p>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 咨询方式选择 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
选择咨询方式
|
||||
</h2>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
{services.map((service) => (
|
||||
<button
|
||||
key={service.id}
|
||||
onClick={() => setSelectedService(service.id as any)}
|
||||
className={`p-4 rounded-2xl transition-all ${
|
||||
selectedService === service.id
|
||||
? "bg-morandi-400 text-white shadow-sm scale-105"
|
||||
: "bg-white text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<service.icon
|
||||
className={`w-8 h-8 mx-auto mb-2 ${
|
||||
selectedService === service.id
|
||||
? "text-white"
|
||||
: "text-morandi-400"
|
||||
}`}
|
||||
/>
|
||||
<div className="font-semibold text-sm mb-1">
|
||||
{service.name}
|
||||
</div>
|
||||
<div
|
||||
className={`text-xs mb-2 ${
|
||||
selectedService === service.id
|
||||
? "text-white/80"
|
||||
: "text-gray-500"
|
||||
}`}
|
||||
>
|
||||
{service.time}
|
||||
</div>
|
||||
<div className="font-semibold">¥{service.price}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 推荐医生 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4">
|
||||
🏥 推荐专家
|
||||
</h2>
|
||||
<div className="space-y-4">
|
||||
{doctors.map((doctor, index) => (
|
||||
<motion.div
|
||||
key={doctor.id}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.3 + index * 0.05 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm hover:shadow-md transition-all border-0">
|
||||
<div className="flex items-start gap-4 mb-4">
|
||||
{/* 医生头像 */}
|
||||
<div className="w-16 h-16 bg-morandi-400 rounded-full flex items-center justify-center text-white text-2xl font-semibold flex-shrink-0">
|
||||
{doctor.name.charAt(0)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-2">
|
||||
<h3 className="font-semibold text-gray-800 text-lg">
|
||||
{doctor.name}
|
||||
</h3>
|
||||
<Badge className="bg-morandi-50 text-morandi-500 hover:bg-morandi-50">
|
||||
{doctor.title}
|
||||
</Badge>
|
||||
{doctor.rating >= 4.9 && (
|
||||
<Award className="w-4 h-4 text-yellow-500" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-1 text-sm text-gray-600 mb-3">
|
||||
<p>{doctor.hospital} · {doctor.specialty}</p>
|
||||
<p>{doctor.experience}</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 text-sm text-gray-500 mb-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<Star className="w-4 h-4 text-yellow-500 fill-yellow-500" />
|
||||
<span className="font-semibold text-gray-800">
|
||||
{doctor.rating}
|
||||
</span>
|
||||
<span>({doctor.reviewCount}评价)</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<ThumbsUp className="w-4 h-4" />
|
||||
<span>{doctor.consultCount}次咨询</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2 mb-3">
|
||||
{doctor.tags.map((tag, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="px-3 py-1 bg-morandi-50 text-morandi-500 text-xs rounded-full"
|
||||
>
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Clock className="w-4 h-4 text-gray-400" />
|
||||
<span className="text-gray-600">
|
||||
响应时间:{doctor.responseTime}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-4 border-t border-gray-100">
|
||||
<div>
|
||||
<span className="text-gray-500 text-sm mr-2">
|
||||
咨询费用
|
||||
</span>
|
||||
<span className="text-2xl font-semibold text-morandi-500">
|
||||
¥{doctor.price}
|
||||
</span>
|
||||
<span className="text-gray-500 text-sm">/次</span>
|
||||
</div>
|
||||
<Button className="bg-morandi-400 hover:bg-morandi-500">
|
||||
立即咨询
|
||||
<ChevronRight className="w-4 h-4 ml-1" />
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 咨询流程 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<h3 className="font-semibold text-gray-800 mb-4">📋 咨询流程</h3>
|
||||
<div className="space-y-3">
|
||||
{[
|
||||
{ step: 1, text: "选择医生和咨询方式" },
|
||||
{ step: 2, text: "上传检查报告和问题描述" },
|
||||
{ step: 3, text: "支付咨询费用" },
|
||||
{ step: 4, text: "医生接单并给出专业建议" },
|
||||
{ step: 5, text: "可追问3次,获得满意答复" },
|
||||
].map((item) => (
|
||||
<div key={item.step} className="flex items-start gap-3">
|
||||
<div className="flex-shrink-0 w-6 h-6 bg-morandi-100 text-morandi-500 rounded-full flex items-center justify-center text-sm font-semibold">
|
||||
{item.step}
|
||||
</div>
|
||||
<p className="text-gray-700 pt-0.5">{item.text}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 温馨提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.6 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-r from-morandi-rose-100 to-red-50 border-morandi-rose-300 rounded-2xl p-4">
|
||||
<h3 className="font-semibold text-gray-800 mb-2">⚠️ 重要提示</h3>
|
||||
<ul className="space-y-1 text-sm text-gray-600">
|
||||
<li>• 在线咨询仅供参考,不能替代线下就诊</li>
|
||||
<li>• 如有紧急情况,请立即前往医院就诊</li>
|
||||
<li>• 咨询记录会保存,可随时查看</li>
|
||||
<li>• 医生回复后24小时内可免费追问</li>
|
||||
</ul>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
624
frontend/src/app/pages/GrowthCurvePage.tsx
Normal file
624
frontend/src/app/pages/GrowthCurvePage.tsx
Normal file
@@ -0,0 +1,624 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
TrendingUp,
|
||||
Info,
|
||||
Download,
|
||||
Share2,
|
||||
Loader2,
|
||||
Heart,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
Legend,
|
||||
ResponsiveContainer,
|
||||
Area,
|
||||
AreaChart,
|
||||
} from "recharts";
|
||||
import { getGrowthCurve } from "../services/api";
|
||||
import { useUser } from "../context/UserContext";
|
||||
|
||||
// 宝宝预期大小数据(按孕周,基于WHO标准)
|
||||
// 4-19周:身长为头臀长(CRL);20周起:身长为头到脚全身长
|
||||
const BABY_EXPECTED_DATA: Record<number, { emoji: string; fruit: string; length: string; weight: string; highlight: string }> = {
|
||||
4: { emoji: "🫘", fruit: "罂粟种子", length: "0.1cm", weight: "<1g", highlight: "心脏开始跳动" },
|
||||
5: { emoji: "🫘", fruit: "芝麻粒", length: "0.2cm", weight: "<1g", highlight: "神经管开始发育" },
|
||||
6: { emoji: "🫘", fruit: "小扁豆", length: "0.6cm", weight: "<1g", highlight: "小手小脚在萌芽" },
|
||||
7: { emoji: "🫐", fruit: "蓝莓", length: "1.3cm", weight: "<1g", highlight: "五官开始形成" },
|
||||
8: { emoji: "🫐", fruit: "覆盆子", length: "1.6cm", weight: "1g", highlight: "手指脚趾开始分化" },
|
||||
9: { emoji: "🍇", fruit: "葡萄", length: "2.3cm", weight: "2g", highlight: "可以微微活动了" },
|
||||
10: { emoji: "🍊", fruit: "金橘", length: "3.1cm", weight: "4g", highlight: "所有器官已初步形成" },
|
||||
11: { emoji: "🫒", fruit: "无花果", length: "4.1cm", weight: "7g", highlight: "能做出吞咽动作" },
|
||||
12: { emoji: "🍋", fruit: "青柠", length: "5.4cm", weight: "14g", highlight: "进入稳定的孕中期" },
|
||||
13: { emoji: "🍋", fruit: "柠檬", length: "7.4cm", weight: "23g", highlight: "指纹开始形成" },
|
||||
14: { emoji: "🍑", fruit: "桃子", length: "8.7cm", weight: "43g", highlight: "能做出表情了" },
|
||||
16: { emoji: "🥑", fruit: "牛油果", length: "11.6cm", weight: "100g", highlight: "开始能听到声音" },
|
||||
18: { emoji: "🫑", fruit: "甜椒", length: "14.2cm", weight: "190g", highlight: "妈妈可能感到胎动了" },
|
||||
20: { emoji: "🍌", fruit: "香蕉", length: "25.6cm", weight: "300g", highlight: "味觉开始发育" },
|
||||
22: { emoji: "🥭", fruit: "木瓜", length: "27.8cm", weight: "430g", highlight: "眉毛和眼睫毛长出" },
|
||||
24: { emoji: "🌽", fruit: "玉米", length: "30cm", weight: "600g", highlight: "肺部开始发育" },
|
||||
26: { emoji: "🥦", fruit: "菜花", length: "35.6cm", weight: "760g", highlight: "能睁开眼睛了" },
|
||||
28: { emoji: "🍆", fruit: "茄子", length: "37.6cm", weight: "1000g", highlight: "开始有规律的作息" },
|
||||
30: { emoji: "🥬", fruit: "卷心菜", length: "39.9cm", weight: "1320g", highlight: "大脑快速发育中" },
|
||||
32: { emoji: "🥥", fruit: "椰子", length: "42.4cm", weight: "1700g", highlight: "皮下脂肪增多" },
|
||||
34: { emoji: "🍈", fruit: "哈密瓜", length: "45cm", weight: "2150g", highlight: "肺部接近成熟" },
|
||||
36: { emoji: "🍈", fruit: "蜜瓜", length: "47.4cm", weight: "2620g", highlight: "头部开始入盆" },
|
||||
38: { emoji: "🎃", fruit: "南瓜", length: "49.8cm", weight: "3080g", highlight: "各器官发育成熟" },
|
||||
40: { emoji: "🍉", fruit: "小西瓜", length: "51.2cm", weight: "3460g", highlight: "随时准备来到这个世界" },
|
||||
};
|
||||
|
||||
function getBabyExpectedData(week: number) {
|
||||
const weeks = Object.keys(BABY_EXPECTED_DATA).map(Number).sort((a, b) => a - b);
|
||||
let closest = weeks[0];
|
||||
for (const w of weeks) {
|
||||
if (w <= week) closest = w;
|
||||
else break;
|
||||
}
|
||||
return BABY_EXPECTED_DATA[closest];
|
||||
}
|
||||
|
||||
// 生成孕周里程碑时间线数据
|
||||
function getGrowthMilestones(currentWeek: number) {
|
||||
const milestones = [
|
||||
{ week: 8, label: "心跳可检测", emoji: "💓" },
|
||||
{ week: 12, label: "首次B超", emoji: "🔍" },
|
||||
{ week: 16, label: "开始感知声音", emoji: "👂" },
|
||||
{ week: 20, label: "大排畸检查", emoji: "🏥" },
|
||||
{ week: 24, label: "肺部发育", emoji: "🫁" },
|
||||
{ week: 28, label: "眼睛能睁开", emoji: "👀" },
|
||||
{ week: 32, label: "快速增重", emoji: "📈" },
|
||||
{ week: 36, label: "接近足月", emoji: "🎯" },
|
||||
{ week: 40, label: "预产期到来", emoji: "🎉" },
|
||||
];
|
||||
return milestones.map(m => ({ ...m, passed: currentWeek >= m.week }));
|
||||
}
|
||||
|
||||
export function GrowthCurvePage() {
|
||||
const navigate = useNavigate();
|
||||
const { user } = useUser();
|
||||
const currentWeek = user.currentWeek || 0;
|
||||
const [selectedMetric, setSelectedMetric] = useState("bpd");
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Standard reference data (no fake values)
|
||||
const standardData: Record<string, { name: string; unit: string; description: string; data: { week: number; value?: number; standard: number; lower: number; upper: number }[] }> = {
|
||||
bpd: {
|
||||
name: "双顶径 (BPD)",
|
||||
unit: "mm",
|
||||
description: "胎儿头部左右两侧之间最宽部位的长度",
|
||||
data: [
|
||||
{ week: 12, standard: 20, lower: 18, upper: 22 },
|
||||
{ week: 16, standard: 35, lower: 32, upper: 38 },
|
||||
{ week: 20, standard: 47, lower: 43, upper: 51 },
|
||||
{ week: 24, standard: 60, lower: 56, upper: 64 },
|
||||
{ week: 28, standard: 71, lower: 67, upper: 75 },
|
||||
{ week: 32, standard: 81, lower: 77, upper: 85 },
|
||||
{ week: 36, standard: 89, lower: 85, upper: 93 },
|
||||
],
|
||||
},
|
||||
ac: {
|
||||
name: "腹围 (AC)",
|
||||
unit: "mm",
|
||||
description: "胎儿腹部一周的长度",
|
||||
data: [
|
||||
{ week: 12, standard: 60, lower: 54, upper: 66 },
|
||||
{ week: 16, standard: 102, lower: 94, upper: 110 },
|
||||
{ week: 20, standard: 148, lower: 138, upper: 158 },
|
||||
{ week: 24, standard: 192, lower: 180, upper: 204 },
|
||||
{ week: 28, standard: 235, lower: 221, upper: 249 },
|
||||
{ week: 32, standard: 279, lower: 263, upper: 295 },
|
||||
{ week: 36, standard: 318, lower: 300, upper: 336 },
|
||||
],
|
||||
},
|
||||
fl: {
|
||||
name: "股骨长 (FL)",
|
||||
unit: "mm",
|
||||
description: "胎儿大腿骨的长度",
|
||||
data: [
|
||||
{ week: 12, standard: 8, lower: 7, upper: 9 },
|
||||
{ week: 16, standard: 22, lower: 20, upper: 24 },
|
||||
{ week: 20, standard: 34, lower: 31, upper: 37 },
|
||||
{ week: 24, standard: 45, lower: 42, upper: 48 },
|
||||
{ week: 28, standard: 54, lower: 51, upper: 57 },
|
||||
{ week: 32, standard: 63, lower: 60, upper: 66 },
|
||||
{ week: 36, standard: 70, lower: 67, upper: 73 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const [growthData, setGrowthData] = useState(standardData);
|
||||
|
||||
useEffect(() => {
|
||||
getGrowthCurve()
|
||||
.then((data) => {
|
||||
if (data.data_points && data.data_points.length > 0) {
|
||||
// Merge API data points into standard data
|
||||
const updated = { ...standardData };
|
||||
for (const metric of ["bpd", "ac", "fl"] as const) {
|
||||
const apiPoints = data.data_points.filter((p) => p[metric] != null);
|
||||
if (apiPoints.length > 0) {
|
||||
updated[metric] = {
|
||||
...updated[metric],
|
||||
data: updated[metric].data.map((d) => {
|
||||
const match = apiPoints.find((p) => p.week === d.week);
|
||||
return match && match[metric] != null
|
||||
? { ...d, value: match[metric]! }
|
||||
: d;
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
setGrowthData(updated);
|
||||
}
|
||||
})
|
||||
.catch(() => {/* keep standard data */})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const currentData = growthData[selectedMetric];
|
||||
|
||||
// 检查是否有真实数据
|
||||
const hasRealData = currentData.data.some(d => d.value != null);
|
||||
|
||||
// 生成动态评估结果
|
||||
const generateAssessment = () => {
|
||||
if (!hasRealData) {
|
||||
return "暂无生长数据。上传B超报告后,系统会自动记录宝宝的生长数据并生成评估结果。";
|
||||
}
|
||||
|
||||
const realDataPoints = currentData.data.filter(d => d.value != null);
|
||||
const latestPoint = realDataPoints[realDataPoints.length - 1];
|
||||
|
||||
if (!latestPoint) {
|
||||
return "暂无生长数据。上传B超报告后,系统会自动记录宝宝的生长数据并生成评估结果。";
|
||||
}
|
||||
|
||||
const { value, lower, upper, week, standard } = latestPoint;
|
||||
const metricName = currentData.name.split(" ")[0];
|
||||
|
||||
if (value! >= lower && value! <= upper) {
|
||||
const deviation = Math.abs(value! - standard);
|
||||
const deviationPercent = ((deviation / standard) * 100).toFixed(1);
|
||||
|
||||
if (deviation < standard * 0.05) {
|
||||
return `宝宝的${metricName}发育非常好!孕${week}周的测量值为${value}${currentData.unit},与标准值${standard}${currentData.unit}非常接近,在正常范围内(${lower}-${upper}${currentData.unit})。继续保持健康的生活方式,按时产检。`;
|
||||
} else {
|
||||
return `宝宝的${metricName}发育良好!孕${week}周的测量值为${value}${currentData.unit},在正常范围内(${lower}-${upper}${currentData.unit}),与标准值${standard}${currentData.unit}相差约${deviationPercent}%。继续保持健康的生活方式,按时产检。`;
|
||||
}
|
||||
} else if (value! < lower) {
|
||||
const gap = lower - value!;
|
||||
return `宝宝的${metricName}略偏小。孕${week}周的测量值为${value}${currentData.unit},低于正常范围下限(${lower}${currentData.unit})约${gap}${currentData.unit}。建议加强营养摄入,多吃富含蛋白质的食物,并及时咨询产科医生,进行进一步评估。`;
|
||||
} else {
|
||||
const gap = value! - upper;
|
||||
return `宝宝的${metricName}略偏大。孕${week}周的测量值为${value}${currentData.unit},高于正常范围上限(${upper}${currentData.unit})约${gap}${currentData.unit}。建议控制饮食,避免高糖高脂食物,并及时咨询产科医生,进行进一步评估。`;
|
||||
}
|
||||
};
|
||||
|
||||
const CustomTooltip = ({ active, payload }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="bg-white p-3 rounded-xl shadow-sm border border-gray-100">
|
||||
<p className="font-semibold text-gray-800 mb-2">
|
||||
孕{payload[0].payload.week}周
|
||||
</p>
|
||||
<p className="text-sm text-gray-500">
|
||||
标准值: {payload[0].payload.standard} {currentData.unit}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
正常范围: {payload[0].payload.lower}-{payload[0].payload.upper}{" "}
|
||||
{currentData.unit}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-gradient-to-br from-morandi-400 to-morandi-400 rounded-full flex items-center justify-center">
|
||||
<TrendingUp className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">胎儿生长曲线</h1>
|
||||
<p className="text-xs text-gray-500">基于B超数据自动生成</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 无B超数据时展示宝宝预期大小 */}
|
||||
{!hasRealData && currentWeek > 0 && (() => {
|
||||
const babyData = getBabyExpectedData(currentWeek);
|
||||
const milestones = getGrowthMilestones(currentWeek);
|
||||
const progress = Math.min(100, Math.max(0, ((currentWeek - 4) / 36) * 100));
|
||||
if (!babyData) return null;
|
||||
return (
|
||||
<>
|
||||
{/* 宝宝当前大小 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0 overflow-hidden relative">
|
||||
<div className="absolute top-0 right-0 w-32 h-32 bg-gradient-to-bl from-morandi-100 to-transparent rounded-bl-full opacity-60" />
|
||||
<div className="relative">
|
||||
<h2 className="font-semibold text-gray-800 mb-4 flex items-center gap-2">
|
||||
<Heart className="w-5 h-5 text-morandi-rose-400" />
|
||||
宝宝现在有多大?
|
||||
</h2>
|
||||
<div className="text-center py-4">
|
||||
<motion.div
|
||||
initial={{ scale: 0.5, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ type: "spring", duration: 0.8 }}
|
||||
className="text-7xl mb-4"
|
||||
>
|
||||
{babyData.emoji}
|
||||
</motion.div>
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.3 }}
|
||||
className="text-lg text-gray-700 font-medium mb-1"
|
||||
>
|
||||
孕{currentWeek}周,宝宝像一个<span className="text-morandi-500 font-semibold">{babyData.fruit}</span>
|
||||
</motion.p>
|
||||
<p className="text-sm text-gray-400">{babyData.highlight}</p>
|
||||
</div>
|
||||
|
||||
{/* 预期数据 */}
|
||||
<div className="grid grid-cols-2 gap-3 mt-4">
|
||||
<div className="bg-morandi-50 rounded-xl p-4 text-center">
|
||||
<p className="text-xs text-gray-400 mb-1">预期身长</p>
|
||||
<p className="text-xl font-semibold text-morandi-600">{babyData.length}</p>
|
||||
</div>
|
||||
<div className="bg-morandi-50 rounded-xl p-4 text-center">
|
||||
<p className="text-xs text-gray-400 mb-1">预期体重</p>
|
||||
<p className="text-xl font-semibold text-morandi-600">{babyData.weight}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 孕期进度 */}
|
||||
<div className="mt-5">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-xs text-gray-400">孕期进度</span>
|
||||
<span className="text-xs text-morandi-500 font-medium">{Math.round(progress)}%</span>
|
||||
</div>
|
||||
<div className="h-2.5 bg-morandi-50 rounded-full overflow-hidden">
|
||||
<motion.div
|
||||
className="h-full bg-gradient-to-r from-morandi-300 to-morandi-500 rounded-full"
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${progress}%` }}
|
||||
transition={{ duration: 1.2, ease: "easeOut" }}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between mt-1">
|
||||
<span className="text-[10px] text-gray-300">4周</span>
|
||||
<span className="text-[10px] text-gray-300">40周</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 成长里程碑时间线 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.15 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0">
|
||||
<h3 className="font-semibold text-gray-800 mb-4">成长里程碑</h3>
|
||||
<div className="space-y-0">
|
||||
{milestones.map((m, i) => (
|
||||
<div key={m.week} className="flex items-start gap-3">
|
||||
{/* 时间线连接线 */}
|
||||
<div className="flex flex-col items-center">
|
||||
<div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm flex-shrink-0 ${
|
||||
m.passed
|
||||
? "bg-morandi-400 text-white"
|
||||
: currentWeek >= m.week - 2
|
||||
? "bg-morandi-100 text-morandi-500 ring-2 ring-morandi-300"
|
||||
: "bg-gray-100 text-gray-400"
|
||||
}`}>
|
||||
{m.emoji}
|
||||
</div>
|
||||
{i < milestones.length - 1 && (
|
||||
<div className={`w-0.5 h-6 ${m.passed ? "bg-morandi-300" : "bg-gray-200"}`} />
|
||||
)}
|
||||
</div>
|
||||
<div className="pt-1.5">
|
||||
<p className={`text-sm font-medium ${m.passed ? "text-gray-700" : "text-gray-400"}`}>
|
||||
{m.label}
|
||||
</p>
|
||||
<p className={`text-xs ${m.passed ? "text-morandi-500" : "text-gray-300"}`}>
|
||||
孕{m.week}周
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 上传B超提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.25 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-r from-morandi-sage-50 to-morandi-50 border-morandi-200 rounded-2xl p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Info className="w-5 h-5 text-morandi-sage-500 mt-0.5 flex-shrink-0" />
|
||||
<div>
|
||||
<h3 className="font-semibold text-gray-700 text-sm mb-1">查看精准发育数据</h3>
|
||||
<p className="text-xs text-gray-500 leading-relaxed mb-3">
|
||||
上传B超报告后,系统会自动提取胎儿双顶径、腹围、股骨长等数据,生成个性化的生长曲线,让你更直观地了解宝宝发育情况。
|
||||
</p>
|
||||
<Button
|
||||
onClick={() => navigate("/camera")}
|
||||
className="bg-gradient-to-r from-morandi-400 to-morandi-500"
|
||||
size="sm"
|
||||
>
|
||||
上传B超报告
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* 指标选择 - 只在有B超数据时显示 */}
|
||||
{hasRealData && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<div className="flex gap-3 overflow-x-auto pb-2">
|
||||
<button
|
||||
onClick={() => setSelectedMetric("bpd")}
|
||||
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
|
||||
selectedMetric === "bpd"
|
||||
? "bg-gradient-to-r from-morandi-400 to-morandi-400 text-white shadow-sm"
|
||||
: "bg-white text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
双顶径
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSelectedMetric("ac")}
|
||||
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
|
||||
selectedMetric === "ac"
|
||||
? "bg-gradient-to-r from-morandi-400 to-morandi-400 text-white shadow-sm"
|
||||
: "bg-white text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
腹围
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSelectedMetric("fl")}
|
||||
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
|
||||
selectedMetric === "fl"
|
||||
? "bg-gradient-to-r from-morandi-rose-400 to-morandi-rose-300 text-white shadow-sm"
|
||||
: "bg-white text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
股骨长
|
||||
</button>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 有B超数据时显示指标详情、曲线图、数据表格 */}
|
||||
{hasRealData && (
|
||||
<>
|
||||
{/* 指标说明 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<Card className="bg-morandi-slate-50 border-morandi-200 rounded-2xl p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Info className="w-5 h-5 text-morandi-slate-500 mt-0.5 flex-shrink-0" />
|
||||
<div>
|
||||
<h3 className="font-semibold text-gray-800 mb-1">
|
||||
{currentData.name}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-600">
|
||||
{currentData.description}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 生长曲线图 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h2 className="font-semibold text-gray-800">生长趋势</h2>
|
||||
<div className="flex items-center gap-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-3 bg-gray-300 rounded-full"></div>
|
||||
<span className="text-gray-600">标准值</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-3 h-3 bg-morandi-slate-200 rounded-full"></div>
|
||||
<span className="text-gray-600">正常范围</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<AreaChart data={currentData.data}>
|
||||
<defs>
|
||||
<linearGradient id="colorRange" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#93c5fd" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="#93c5fd" stopOpacity={0.1} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
|
||||
<XAxis
|
||||
dataKey="week"
|
||||
label={{ value: "孕周", position: "insideBottom", offset: -5 }}
|
||||
stroke="#9ca3af"
|
||||
/>
|
||||
<YAxis
|
||||
label={{
|
||||
value: `${currentData.unit}`,
|
||||
angle: -90,
|
||||
position: "insideLeft",
|
||||
}}
|
||||
stroke="#9ca3af"
|
||||
/>
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="upper"
|
||||
stroke="none"
|
||||
fill="url(#colorRange)"
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="lower"
|
||||
stroke="none"
|
||||
fill="#ffffff"
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="standard"
|
||||
stroke="#d1d5db"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
strokeDasharray="5 5"
|
||||
/>
|
||||
{/* 完全移除实际值线条 */}
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 数据表格 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.3 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-6 shadow-sm border-0">
|
||||
<h3 className="font-semibold text-gray-800 mb-4">详细数据</h3>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full">
|
||||
<thead>
|
||||
<tr className="border-b border-gray-200">
|
||||
<th className="text-left py-3 text-sm font-semibold text-gray-600">
|
||||
孕周
|
||||
</th>
|
||||
<th className="text-center py-3 text-sm font-semibold text-gray-600">
|
||||
实际值
|
||||
</th>
|
||||
<th className="text-center py-3 text-sm font-semibold text-gray-600">
|
||||
标准值
|
||||
</th>
|
||||
<th className="text-center py-3 text-sm font-semibold text-gray-600">
|
||||
正常范围
|
||||
</th>
|
||||
<th className="text-center py-3 text-sm font-semibold text-gray-600">
|
||||
状态
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentData.data.map((row, index) => {
|
||||
const isNormal =
|
||||
row.value != null && row.value >= row.lower && row.value <= row.upper;
|
||||
return (
|
||||
<tr key={index} className="border-b border-gray-100">
|
||||
<td className="py-3 text-sm text-gray-700">
|
||||
{row.week}周
|
||||
</td>
|
||||
<td className="text-center py-3 text-sm font-semibold text-morandi-500">
|
||||
{row.value != null ? `${row.value} ${currentData.unit}` : '-'}
|
||||
</td>
|
||||
<td className="text-center py-3 text-sm text-gray-600">
|
||||
{row.standard} {currentData.unit}
|
||||
</td>
|
||||
<td className="text-center py-3 text-sm text-gray-500">
|
||||
{row.lower}-{row.upper} {currentData.unit}
|
||||
</td>
|
||||
<td className="text-center py-3">
|
||||
{row.value != null ? (
|
||||
<Badge
|
||||
className={`${
|
||||
isNormal
|
||||
? "bg-morandi-sage-100 text-morandi-sage-600"
|
||||
: "bg-morandi-rose-100 text-morandi-600"
|
||||
} hover:bg-current`}
|
||||
>
|
||||
{isNormal ? "正常" : "关注"}
|
||||
</Badge>
|
||||
) : (
|
||||
<span className="text-gray-400 text-xs">-</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 医生建议 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.4 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-r from-morandi-sage-100 to-morandi-sage-100 border-morandi-sage-200 rounded-2xl p-4">
|
||||
<h3 className="font-semibold text-gray-800 mb-2 flex items-center gap-2">
|
||||
<TrendingUp className="w-5 h-5 text-morandi-sage-500" />
|
||||
评估结果
|
||||
</h3>
|
||||
<p className="text-sm text-gray-700 leading-relaxed">
|
||||
{generateAssessment()}
|
||||
</p>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
733
frontend/src/app/pages/HealthRecordsPage.tsx
Normal file
733
frontend/src/app/pages/HealthRecordsPage.tsx
Normal file
@@ -0,0 +1,733 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
TrendingUp,
|
||||
Activity,
|
||||
Search,
|
||||
FileText,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
FolderOpen,
|
||||
Camera,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Area,
|
||||
ComposedChart,
|
||||
} from "recharts";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import {
|
||||
getReportList,
|
||||
getReportTypeTrends,
|
||||
type ReportTypeTrend,
|
||||
} from "../services/api";
|
||||
|
||||
interface Report {
|
||||
id: string;
|
||||
type: string;
|
||||
date: string;
|
||||
status: "normal" | "attention" | "warning";
|
||||
summary: string;
|
||||
period: "early" | "mid" | "late";
|
||||
week: number;
|
||||
}
|
||||
|
||||
export function HealthRecordsPage() {
|
||||
const navigate = useNavigate();
|
||||
const [activeTab, setActiveTab] = useState<"trends" | "records">("trends");
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [reports, setReports] = useState<Report[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
getReportList()
|
||||
.then((data) => {
|
||||
setReports(
|
||||
data.map((item) => {
|
||||
const week = item.pregnancy_week || 0;
|
||||
const period = week <= 12 ? "early" : week <= 27 ? "mid" : "late";
|
||||
const statusMap: Record<string, Report["status"]> = {
|
||||
normal: "normal",
|
||||
attention: "attention",
|
||||
warning: "warning",
|
||||
};
|
||||
return {
|
||||
id: item.id,
|
||||
type: item.report_type,
|
||||
date: item.created_at.split("T")[0],
|
||||
status: statusMap[item.overall_status] || "normal",
|
||||
summary: item.summary || `共${item.item_count}项指标`,
|
||||
period: period as Report["period"],
|
||||
week,
|
||||
};
|
||||
})
|
||||
);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
// ─── 按报告类型分组的指标趋势 ───
|
||||
const [reportTypeTrends, setReportTypeTrends] = useState<ReportTypeTrend[]>([]);
|
||||
const [trendsLoading, setTrendsLoading] = useState(true);
|
||||
const [selectedTypeIdx, setSelectedTypeIdx] = useState(0);
|
||||
const [selectedIndIdx, setSelectedIndIdx] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
getReportTypeTrends()
|
||||
.then((data) => {
|
||||
setReportTypeTrends(data.report_types);
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => setTrendsLoading(false));
|
||||
}, []);
|
||||
|
||||
const currentType = reportTypeTrends[selectedTypeIdx] || null;
|
||||
const currentInd = currentType?.indicators[selectedIndIdx] || null;
|
||||
|
||||
const trendChartData = useMemo(() => {
|
||||
if (!currentInd) return [];
|
||||
return currentInd.points.map((p) => ({
|
||||
label: p.week > 0 ? `${p.week}周` : p.date.split("T")[0]?.slice(5) || "",
|
||||
value: p.value,
|
||||
refLower: currentInd.ref_lower,
|
||||
refUpper: currentInd.ref_upper,
|
||||
}));
|
||||
}, [currentInd]);
|
||||
|
||||
// ─── 综合健康摘要:只分析最新一次产检的指标 ───
|
||||
const healthSummary = useMemo(() => {
|
||||
// 找到最新产检周数(所有指标中最大的 week)
|
||||
let latestWeek = 0;
|
||||
for (const rt of reportTypeTrends) {
|
||||
for (const ind of rt.indicators) {
|
||||
for (const p of ind.points) {
|
||||
if (p.week > latestWeek) latestWeek = p.week;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const stable: string[] = [];
|
||||
const improving: string[] = [];
|
||||
const attention: string[] = [];
|
||||
let latestReportCount = 0;
|
||||
const countedTypes = new Set<string>();
|
||||
|
||||
for (const rt of reportTypeTrends) {
|
||||
let typeHasLatest = false;
|
||||
for (const ind of rt.indicators) {
|
||||
// 只看最新周数的数据点
|
||||
const latestPt = ind.points.find(p => p.week === latestWeek);
|
||||
if (!latestPt) continue;
|
||||
typeHasLatest = true;
|
||||
|
||||
const prevPt = ind.points.filter(p => p.week < latestWeek).pop();
|
||||
const hasRef = ind.ref_lower != null && ind.ref_upper != null;
|
||||
|
||||
if (latestPt.status !== "normal") {
|
||||
attention.push(ind.name);
|
||||
} else if (prevPt && prevPt.status !== "normal") {
|
||||
improving.push(ind.name);
|
||||
} else if (hasRef) {
|
||||
const range = ind.ref_upper! - ind.ref_lower!;
|
||||
const margin = range * 0.15;
|
||||
if (latestPt.value < ind.ref_lower! + margin || latestPt.value > ind.ref_upper! - margin) {
|
||||
attention.push(ind.name);
|
||||
} else {
|
||||
stable.push(ind.name);
|
||||
}
|
||||
} else {
|
||||
stable.push(ind.name);
|
||||
}
|
||||
}
|
||||
if (typeHasLatest && !countedTypes.has(rt.report_type)) {
|
||||
countedTypes.add(rt.report_type);
|
||||
latestReportCount++;
|
||||
}
|
||||
}
|
||||
|
||||
const uniqueStable = [...new Set(stable)];
|
||||
const uniqueImproving = [...new Set(improving)];
|
||||
const uniqueAttention = [...new Set(attention)];
|
||||
const filteredStable = uniqueStable.filter(n => !uniqueAttention.includes(n) && !uniqueImproving.includes(n));
|
||||
const filteredImproving = uniqueImproving.filter(n => !uniqueAttention.includes(n));
|
||||
const totalIndicators = filteredStable.length + filteredImproving.length + uniqueAttention.length;
|
||||
|
||||
let overallText = "";
|
||||
let overallLevel: "good" | "ok" | "warn" = "good";
|
||||
const hasMultipleReports = latestReportCount > 1 || filteredStable.length + filteredImproving.length + uniqueAttention.length > 3;
|
||||
const prefix = hasMultipleReports ? "本次产检" : "报告显示";
|
||||
if (uniqueAttention.length === 0) {
|
||||
overallText = `${prefix}各项指标均在正常范围,整体状况良好`;
|
||||
overallLevel = "good";
|
||||
} else if (uniqueAttention.length <= 2) {
|
||||
overallText = `大部分指标正常,有${uniqueAttention.length}项需要留意`;
|
||||
overallLevel = "ok";
|
||||
} else {
|
||||
overallText = `有${uniqueAttention.length}项指标需要关注,建议咨询医生`;
|
||||
overallLevel = "warn";
|
||||
}
|
||||
|
||||
return {
|
||||
stable: filteredStable,
|
||||
improving: filteredImproving,
|
||||
attention: uniqueAttention,
|
||||
overallText,
|
||||
overallLevel,
|
||||
latestWeek,
|
||||
latestReportCount,
|
||||
totalIndicators,
|
||||
};
|
||||
}, [reportTypeTrends]);
|
||||
|
||||
const filteredReports = reports.filter((report) => {
|
||||
const matchesSearch =
|
||||
report.type.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
report.summary.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
return matchesSearch;
|
||||
});
|
||||
|
||||
const groupedReports = filteredReports.reduce((acc, report) => {
|
||||
const month = report.date.substring(0, 7);
|
||||
if (!acc[month]) acc[month] = [];
|
||||
acc[month].push(report);
|
||||
return acc;
|
||||
}, {} as Record<string, Report[]>);
|
||||
|
||||
const monthNames: Record<string, string> = {};
|
||||
Object.keys(groupedReports).forEach((month) => {
|
||||
const [y, m] = month.split("-");
|
||||
monthNames[month] = `${y}年${parseInt(m)}月`;
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center flex-shrink-0"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
<div className="w-10 h-10 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full flex items-center justify-center">
|
||||
<Activity className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">健康档案</h1>
|
||||
<p className="text-xs text-gray-500">共{reports.length}份报告</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<div className="mx-auto px-4 pt-3">
|
||||
{/* Tab 切换 */}
|
||||
<div className="flex bg-white rounded-2xl p-1.5 shadow-sm">
|
||||
<button
|
||||
onClick={() => setActiveTab("trends")}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium transition-all ${
|
||||
activeTab === "trends"
|
||||
? "bg-morandi-400 text-white shadow-sm"
|
||||
: "text-gray-500 hover:text-gray-700"
|
||||
}`}
|
||||
>
|
||||
<TrendingUp className="w-4 h-4" />
|
||||
趋势分析
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab("records")}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium transition-all ${
|
||||
activeTab === "records"
|
||||
? "bg-morandi-400 text-white shadow-sm"
|
||||
: "text-gray-500 hover:text-gray-700"
|
||||
}`}
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
档案记录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-4">
|
||||
{/* ═══════════ Tab 1: 趋势分析 ═══════════ */}
|
||||
{activeTab === "trends" && (
|
||||
<>
|
||||
{/* 综合健康摘要 */}
|
||||
{reportTypeTrends.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
{/* 标题 + 产检信息 */}
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
|
||||
<Activity className="w-5 h-5 text-morandi-400" />
|
||||
健康概览
|
||||
</h2>
|
||||
<span className="text-xs text-gray-400 bg-morandi-50 px-2.5 py-1 rounded-full">
|
||||
{healthSummary.latestWeek > 0 ? `第${healthSummary.latestWeek}周产检 · ` : ""}{healthSummary.latestReportCount}份报告
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 整体评语 */}
|
||||
<div className={`rounded-xl px-4 py-3 mb-4 ${
|
||||
healthSummary.overallLevel === "good"
|
||||
? "bg-morandi-sage-50"
|
||||
: healthSummary.overallLevel === "ok"
|
||||
? "bg-amber-50"
|
||||
: "bg-red-50"
|
||||
}`}>
|
||||
<p className={`text-sm font-medium ${
|
||||
healthSummary.overallLevel === "good"
|
||||
? "text-morandi-sage-600"
|
||||
: healthSummary.overallLevel === "ok"
|
||||
? "text-amber-600"
|
||||
: "text-red-600"
|
||||
}`}>
|
||||
{healthSummary.overallText}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 分类指标 */}
|
||||
<div className="space-y-2">
|
||||
{healthSummary.stable.length > 0 && (
|
||||
<div className="flex items-start gap-2.5 px-1">
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-morandi-sage-400 mt-1.5 flex-shrink-0" />
|
||||
<div>
|
||||
<span className="text-xs font-medium text-gray-600">平稳正常</span>
|
||||
<span className="text-xs text-gray-400 ml-1.5">{healthSummary.stable.join("、")}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{healthSummary.improving.length > 0 && (
|
||||
<div className="flex items-start gap-2.5 px-1">
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-blue-400 mt-1.5 flex-shrink-0" />
|
||||
<div>
|
||||
<span className="text-xs font-medium text-gray-600">好转向好</span>
|
||||
<span className="text-xs text-gray-400 ml-1.5">{healthSummary.improving.join("、")}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{healthSummary.attention.length > 0 && (
|
||||
<div className="flex items-start gap-2.5 px-1">
|
||||
<div className="w-1.5 h-1.5 rounded-full bg-amber-400 mt-1.5 flex-shrink-0" />
|
||||
<div>
|
||||
<span className="text-xs font-medium text-gray-600">需要留意</span>
|
||||
<span className="text-xs text-gray-400 ml-1.5">{healthSummary.attention.join("、")}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 详细指标趋势 */}
|
||||
{reportTypeTrends.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.05 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
|
||||
<TrendingUp className="w-5 h-5 text-morandi-sage-400" />
|
||||
指标详情
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{/* 第一级:报告类型切换 */}
|
||||
<div className="flex gap-2 mb-3 overflow-x-auto pb-1 -mx-1 px-1">
|
||||
{reportTypeTrends.map((rt, idx) => (
|
||||
<button
|
||||
key={rt.report_type}
|
||||
onClick={() => { setSelectedTypeIdx(idx); setSelectedIndIdx(0); }}
|
||||
className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all flex-shrink-0 ${
|
||||
selectedTypeIdx === idx
|
||||
? "bg-morandi-400 text-white"
|
||||
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
|
||||
}`}
|
||||
>
|
||||
{rt.report_type}
|
||||
<span className="ml-1 opacity-70">({rt.report_count}份)</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{currentType && (
|
||||
<>
|
||||
{/* 第二级:指标切换 */}
|
||||
<div className="flex gap-2 mb-4 overflow-x-auto pb-1 -mx-1 px-1">
|
||||
{currentType.indicators.map((ind, idx) => (
|
||||
<button
|
||||
key={ind.name}
|
||||
onClick={() => setSelectedIndIdx(idx)}
|
||||
className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all flex-shrink-0 ${
|
||||
selectedIndIdx === idx
|
||||
? "bg-morandi-sage-400 text-white"
|
||||
: "bg-morandi-sage-50 text-gray-500 hover:bg-morandi-sage-100"
|
||||
}`}
|
||||
>
|
||||
{ind.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{currentInd && (
|
||||
<>
|
||||
{/* 图表 */}
|
||||
<div className="mb-3">
|
||||
<ResponsiveContainer width="100%" height={200}>
|
||||
<ComposedChart data={trendChartData}>
|
||||
<defs>
|
||||
<linearGradient id="healthTrendRef" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#A8C5A0" stopOpacity={0.2} />
|
||||
<stop offset="95%" stopColor="#A8C5A0" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#EDE6F2" />
|
||||
<XAxis dataKey="label" stroke="#B0A8B8" tick={{ fontSize: 11 }} />
|
||||
<YAxis stroke="#B0A8B8" tick={{ fontSize: 11 }} />
|
||||
<Tooltip
|
||||
content={({ active, payload }: any) => {
|
||||
if (active && payload?.[0]) {
|
||||
const d = payload[0].payload;
|
||||
return (
|
||||
<div className="bg-white p-3 rounded-xl shadow-lg border border-morandi-100">
|
||||
<p className="font-semibold text-gray-700 text-xs mb-1">{d.label}</p>
|
||||
<p className="text-xs text-morandi-sage-500">
|
||||
{currentInd.name}: {d.value} {currentInd.unit}
|
||||
</p>
|
||||
{d.refLower != null && d.refUpper != null && (
|
||||
<p className="text-xs text-gray-400">
|
||||
参考: {d.refLower}-{d.refUpper} {currentInd.unit}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
{currentInd.ref_upper != null && (
|
||||
<Area type="monotone" dataKey="refUpper" stroke="none" fill="url(#healthTrendRef)" />
|
||||
)}
|
||||
{currentInd.ref_lower != null && (
|
||||
<Area type="monotone" dataKey="refLower" stroke="none" fill="#ffffff" />
|
||||
)}
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke="#7BA37A"
|
||||
strokeWidth={2.5}
|
||||
dot={{ fill: "#7BA37A", r: trendChartData.length === 1 ? 6 : 4, strokeWidth: 2, stroke: "#fff" }}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
{/* 图例 */}
|
||||
<div className="flex items-center gap-4 mb-3 text-xs flex-wrap">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 rounded-full bg-[#7BA37A]" />
|
||||
<span className="text-gray-500">实际值</span>
|
||||
</div>
|
||||
{currentInd.ref_lower != null && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 bg-morandi-sage-100 rounded-full" />
|
||||
<span className="text-gray-500">
|
||||
参考 {currentInd.ref_lower}-{currentInd.ref_upper} {currentInd.unit}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 数据明细 */}
|
||||
<div className="bg-morandi-50 rounded-xl p-3">
|
||||
<div className={`grid gap-1 text-xs text-gray-400 mb-2 px-1 ${currentInd.ref_lower != null ? "grid-cols-4" : "grid-cols-3"}`}>
|
||||
<span>时间</span>
|
||||
<span className="text-center">实际值</span>
|
||||
{currentInd.ref_lower != null && (
|
||||
<span className="text-center">参考值</span>
|
||||
)}
|
||||
<span className="text-right">状态</span>
|
||||
</div>
|
||||
{currentInd.points.map((p, i) => (
|
||||
<div key={i} className={`grid gap-1 text-xs px-1 py-1.5 border-t border-morandi-100 ${currentInd.ref_lower != null ? "grid-cols-4" : "grid-cols-3"}`}>
|
||||
<span className="text-gray-600">
|
||||
{p.week > 0 ? `第${p.week}周` : p.date.split("T")[0]?.slice(5)}
|
||||
</span>
|
||||
<span className={`text-center font-medium ${
|
||||
p.status === "normal"
|
||||
? "text-gray-700"
|
||||
: p.status === "high"
|
||||
? "text-morandi-rose-500"
|
||||
: "text-amber-500"
|
||||
}`}>
|
||||
{p.value}
|
||||
</span>
|
||||
{currentInd.ref_lower != null && (
|
||||
<span className="text-center text-gray-400">
|
||||
{currentInd.ref_lower}-{currentInd.ref_upper}
|
||||
</span>
|
||||
)}
|
||||
<span
|
||||
className={`text-right ${
|
||||
p.status === "normal"
|
||||
? "text-morandi-sage-500"
|
||||
: p.status === "high"
|
||||
? "text-morandi-rose-500"
|
||||
: "text-amber-500"
|
||||
}`}
|
||||
>
|
||||
{p.status === "normal" ? "正常" : p.status === "high" ? "偏高" : "偏低"}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{trendsLoading && reportTypeTrends.length === 0 && (
|
||||
<div className="flex justify-center py-12">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!trendsLoading && reportTypeTrends.length === 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="text-center py-12"
|
||||
>
|
||||
<div className="w-16 h-16 bg-morandi-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<TrendingUp className="w-8 h-8 text-morandi-400" />
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mb-1">暂无分析数据</p>
|
||||
<p className="text-xs text-gray-400 mb-4">上传产检报告后,自动生成健康分析和指标趋势</p>
|
||||
<button
|
||||
onClick={() => navigate("/camera")}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-morandi-400 to-morandi-500 text-white text-sm font-medium rounded-full hover:shadow-md transition-all"
|
||||
>
|
||||
<Camera className="w-4 h-4" />
|
||||
去上传报告
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ═══════════ Tab 2: 档案记录 ═══════════ */}
|
||||
{activeTab === "records" && (
|
||||
<>
|
||||
{/* 搜索框 */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="搜索报告..."
|
||||
className="pl-9 rounded-full border-morandi-100 h-9 text-sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-4 shadow-sm border-0">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-semibold text-morandi-sage-500 mb-1">
|
||||
{filteredReports.filter((r) => r.status === "normal").length}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">正常</div>
|
||||
</div>
|
||||
<div className="text-center border-l border-r border-gray-100">
|
||||
<div className="text-2xl font-semibold text-morandi-600 mb-1">
|
||||
{filteredReports.filter((r) => r.status === "attention").length}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">需关注</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-semibold text-red-600 mb-1">
|
||||
{filteredReports.filter((r) => r.status === "warning").length}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">异常</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 时间轴 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
className="space-y-5"
|
||||
>
|
||||
{Object.keys(groupedReports)
|
||||
.sort()
|
||||
.reverse()
|
||||
.map((month) => (
|
||||
<div key={month}>
|
||||
<h2 className="text-sm font-semibold text-gray-700 mb-3 flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-morandi-400 rounded-full" />
|
||||
{monthNames[month] || month}
|
||||
</h2>
|
||||
<div className="relative pl-6 space-y-3">
|
||||
<div className="absolute left-1 top-0 bottom-0 w-0.5 bg-morandi-200" />
|
||||
|
||||
{groupedReports[month].map((report, index) => (
|
||||
<motion.div
|
||||
key={report.id}
|
||||
initial={{ opacity: 0, x: -16 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.15 + index * 0.04 }}
|
||||
className="relative"
|
||||
>
|
||||
<div
|
||||
className={`absolute -left-6 top-4 w-3 h-3 rounded-full border-2 border-white ${
|
||||
report.status === "normal"
|
||||
? "bg-morandi-sage-400"
|
||||
: report.status === "attention"
|
||||
? "bg-morandi-rose-400"
|
||||
: "bg-red-500"
|
||||
}`}
|
||||
/>
|
||||
|
||||
<Card
|
||||
onClick={() => navigate(`/analysis/${report.id}`)}
|
||||
className="bg-white rounded-2xl p-4 shadow-sm hover:shadow-md transition-all cursor-pointer border-0"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
|
||||
report.status === "normal"
|
||||
? "bg-morandi-sage-100"
|
||||
: report.status === "attention"
|
||||
? "bg-morandi-rose-100"
|
||||
: "bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{report.status === "normal" ? (
|
||||
<CheckCircle2 className="w-5 h-5 text-morandi-sage-400" />
|
||||
) : (
|
||||
<AlertCircle
|
||||
className={`w-5 h-5 ${
|
||||
report.status === "attention"
|
||||
? "text-morandi-rose-400"
|
||||
: "text-red-500"
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-0.5">
|
||||
<h3 className="font-medium text-gray-800 text-sm">
|
||||
{report.type}
|
||||
</h3>
|
||||
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100 text-xs">
|
||||
孕{report.week}周
|
||||
</Badge>
|
||||
<Badge
|
||||
className={`text-xs ${
|
||||
report.status === "normal"
|
||||
? "bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100"
|
||||
: report.status === "attention"
|
||||
? "bg-morandi-rose-100 text-morandi-600 hover:bg-morandi-rose-100"
|
||||
: "bg-red-100 text-red-700 hover:bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{report.status === "normal"
|
||||
? "正常"
|
||||
: report.status === "attention"
|
||||
? "关注"
|
||||
: "异常"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 truncate">
|
||||
{report.summary}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ChevronRight className="w-4 h-4 text-gray-400 flex-shrink-0" />
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</motion.div>
|
||||
|
||||
{reports.length === 0 && !searchQuery && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="text-center py-12"
|
||||
>
|
||||
<div className="w-16 h-16 bg-morandi-100 rounded-full flex items-center justify-center mx-auto mb-4">
|
||||
<FileText className="w-8 h-8 text-morandi-400" />
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mb-1">暂无检查报告</p>
|
||||
<p className="text-xs text-gray-400 mb-4">上传产检报告后,这里会自动归档</p>
|
||||
<button
|
||||
onClick={() => navigate("/camera")}
|
||||
className="inline-flex items-center gap-2 px-5 py-2.5 bg-gradient-to-r from-morandi-400 to-morandi-500 text-white text-sm font-medium rounded-full hover:shadow-md transition-all"
|
||||
>
|
||||
<Camera className="w-4 h-4" />
|
||||
去上传报告
|
||||
</button>
|
||||
</motion.div>
|
||||
)}
|
||||
{filteredReports.length === 0 && searchQuery && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="text-center py-6"
|
||||
>
|
||||
<FileText className="w-12 h-12 text-gray-300 mx-auto mb-3" />
|
||||
<p className="text-sm text-gray-400">暂无相关报告</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="h-8" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
766
frontend/src/app/pages/HomePage.tsx
Normal file
766
frontend/src/app/pages/HomePage.tsx
Normal file
@@ -0,0 +1,766 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
Plus,
|
||||
FileText,
|
||||
Calendar,
|
||||
TrendingUp,
|
||||
ChevronRight,
|
||||
Heart,
|
||||
Bell,
|
||||
User,
|
||||
Camera,
|
||||
Info,
|
||||
Mic,
|
||||
ListChecks,
|
||||
Circle,
|
||||
CheckCircle2,
|
||||
X,
|
||||
} from "lucide-react";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Button } from "../components/ui/button";
|
||||
import {
|
||||
LineChart,
|
||||
Line,
|
||||
XAxis,
|
||||
YAxis,
|
||||
CartesianGrid,
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
Area,
|
||||
AreaChart,
|
||||
ComposedChart,
|
||||
} from "recharts";
|
||||
import { useUser, getBabySize } from "../context/UserContext";
|
||||
import { getGrowthCurve, getIndicatorTrends, type IndicatorTrend } from "../services/api";
|
||||
import { checkupSchedule } from "../data/checkupSchedule";
|
||||
|
||||
// 宝宝预期大小数据(按孕周,基于WHO标准)
|
||||
// 4-19周:身长为头臀长(CRL);20周起:身长为头到脚全身长
|
||||
const BABY_EXPECTED_DATA: Record<number, { emoji: string; fruit: string; length: string; weight: string; highlight: string }> = {
|
||||
4: { emoji: "🫘", fruit: "罂粟种子", length: "0.1cm", weight: "<1g", highlight: "心脏开始跳动" },
|
||||
5: { emoji: "🫘", fruit: "芝麻粒", length: "0.2cm", weight: "<1g", highlight: "神经管开始发育" },
|
||||
6: { emoji: "🫘", fruit: "小扁豆", length: "0.6cm", weight: "<1g", highlight: "小手小脚在萌芽" },
|
||||
7: { emoji: "🫐", fruit: "蓝莓", length: "1.3cm", weight: "<1g", highlight: "五官开始形成" },
|
||||
8: { emoji: "🫐", fruit: "覆盆子", length: "1.6cm", weight: "1g", highlight: "手指脚趾开始分化" },
|
||||
9: { emoji: "🍇", fruit: "葡萄", length: "2.3cm", weight: "2g", highlight: "可以微微活动了" },
|
||||
10: { emoji: "🍊", fruit: "金橘", length: "3.1cm", weight: "4g", highlight: "所有器官已初步形成" },
|
||||
11: { emoji: "🫒", fruit: "无花果", length: "4.1cm", weight: "7g", highlight: "能做出吞咽动作" },
|
||||
12: { emoji: "🍋", fruit: "青柠", length: "5.4cm", weight: "14g", highlight: "进入稳定的孕中期" },
|
||||
13: { emoji: "🍋", fruit: "柠檬", length: "7.4cm", weight: "23g", highlight: "指纹开始形成" },
|
||||
14: { emoji: "🍑", fruit: "桃子", length: "8.7cm", weight: "43g", highlight: "能做出表情了" },
|
||||
16: { emoji: "🥑", fruit: "牛油果", length: "11.6cm", weight: "100g", highlight: "开始能听到声音" },
|
||||
18: { emoji: "🫑", fruit: "甜椒", length: "14.2cm", weight: "190g", highlight: "妈妈可能感到胎动了" },
|
||||
20: { emoji: "🍌", fruit: "香蕉", length: "25.6cm", weight: "300g", highlight: "味觉开始发育" },
|
||||
22: { emoji: "🥭", fruit: "木瓜", length: "27.8cm", weight: "430g", highlight: "眉毛和眼睫毛长出" },
|
||||
24: { emoji: "🌽", fruit: "玉米", length: "30cm", weight: "600g", highlight: "肺部开始发育" },
|
||||
26: { emoji: "🥦", fruit: "菜花", length: "35.6cm", weight: "760g", highlight: "能睁开眼睛了" },
|
||||
28: { emoji: "🍆", fruit: "茄子", length: "37.6cm", weight: "1000g", highlight: "开始有规律的作息" },
|
||||
30: { emoji: "🥬", fruit: "卷心菜", length: "39.9cm", weight: "1320g", highlight: "大脑快速发育中" },
|
||||
32: { emoji: "🥥", fruit: "椰子", length: "42.4cm", weight: "1700g", highlight: "皮下脂肪增多" },
|
||||
34: { emoji: "🍈", fruit: "哈密瓜", length: "45cm", weight: "2150g", highlight: "肺部接近成熟" },
|
||||
36: { emoji: "🍈", fruit: "蜜瓜", length: "47.4cm", weight: "2620g", highlight: "头部开始入盆" },
|
||||
38: { emoji: "🎃", fruit: "南瓜", length: "49.8cm", weight: "3080g", highlight: "各器官发育成熟" },
|
||||
40: { emoji: "🍉", fruit: "小西瓜", length: "51.2cm", weight: "3460g", highlight: "随时准备来到这个世界" },
|
||||
};
|
||||
|
||||
function getBabyExpectedData(week: number) {
|
||||
const weeks = Object.keys(BABY_EXPECTED_DATA).map(Number).sort((a, b) => a - b);
|
||||
let closest = weeks[0];
|
||||
for (const w of weeks) {
|
||||
if (w <= week) closest = w;
|
||||
else break;
|
||||
}
|
||||
return BABY_EXPECTED_DATA[closest];
|
||||
}
|
||||
|
||||
// 宝宝预期大小卡片 - 无B超数据时展示
|
||||
function BabyExpectedSizeCard({ week, onUpload }: { week: number; onUpload: () => void }) {
|
||||
const data = getBabyExpectedData(week);
|
||||
if (!data) return null;
|
||||
|
||||
// 计算进度百分比 (4-40周)
|
||||
const progress = Math.min(100, Math.max(0, ((week - 4) / 36) * 100));
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* 宝宝大小展示 */}
|
||||
<div className="bg-gradient-to-br from-morandi-50 to-morandi-100 rounded-2xl p-5 text-center">
|
||||
<motion.div
|
||||
initial={{ scale: 0.8, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
transition={{ type: "spring", duration: 0.6 }}
|
||||
className="text-5xl mb-3"
|
||||
>
|
||||
{data.emoji}
|
||||
</motion.div>
|
||||
<p className="text-sm text-gray-700 font-medium mb-1">
|
||||
宝宝现在像一个<span className="text-morandi-500 font-semibold">{data.fruit}</span>
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">{data.highlight}</p>
|
||||
</div>
|
||||
|
||||
{/* 预期数据 */}
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="bg-morandi-50 rounded-xl p-3 text-center">
|
||||
<p className="text-[10px] text-gray-400 mb-1">预期身长</p>
|
||||
<p className="text-base font-semibold text-morandi-600">{data.length}</p>
|
||||
</div>
|
||||
<div className="bg-morandi-50 rounded-xl p-3 text-center">
|
||||
<p className="text-[10px] text-gray-400 mb-1">预期体重</p>
|
||||
<p className="text-base font-semibold text-morandi-600">{data.weight}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 成长进度条 */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-1.5">
|
||||
<span className="text-[10px] text-gray-400">孕期进度</span>
|
||||
<span className="text-[10px] text-morandi-500 font-medium">{week}周 / 40周</span>
|
||||
</div>
|
||||
<div className="h-2 bg-morandi-50 rounded-full overflow-hidden">
|
||||
<motion.div
|
||||
className="h-full bg-gradient-to-r from-morandi-300 to-morandi-400 rounded-full"
|
||||
initial={{ width: 0 }}
|
||||
animate={{ width: `${progress}%` }}
|
||||
transition={{ duration: 1, ease: "easeOut" }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 提示 */}
|
||||
<div className="bg-morandi-sage-50 rounded-xl p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<Info className="w-4 h-4 text-morandi-sage-400 mt-0.5 flex-shrink-0" />
|
||||
<div>
|
||||
<p className="text-xs text-gray-500 leading-relaxed">
|
||||
上传B超报告后,可查看宝宝实际发育数据与标准值的对比曲线
|
||||
</p>
|
||||
<button
|
||||
onClick={onUpload}
|
||||
className="text-xs text-morandi-500 font-medium mt-1.5 hover:text-morandi-600"
|
||||
>
|
||||
去上传报告 →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function HomePage() {
|
||||
const navigate = useNavigate();
|
||||
const { user } = useUser();
|
||||
const [selectedMetric, setSelectedMetric] = useState("bpd");
|
||||
|
||||
const weekInfo = {
|
||||
week: user.currentWeek,
|
||||
day: user.currentDay,
|
||||
dueDate: user.dueDate || "未设置",
|
||||
babySize: getBabySize(user.currentWeek),
|
||||
};
|
||||
|
||||
// 计算下次产检信息
|
||||
const nextCheckup = useMemo(() => {
|
||||
const currentWeek = user.currentWeek;
|
||||
if (currentWeek <= 0) return null;
|
||||
|
||||
const upcoming = checkupSchedule.find((c) => c.week > currentWeek);
|
||||
if (!upcoming) return null;
|
||||
|
||||
// 通过 lastPeriodDate 或 dueDate 反推末次月经日期
|
||||
let lmpTime: number | null = null;
|
||||
if (user.lastPeriodDate) {
|
||||
lmpTime = new Date(user.lastPeriodDate).getTime();
|
||||
} else if (user.dueDate) {
|
||||
// 预产期 = 末次月经 + 280天,反推
|
||||
lmpTime = new Date(user.dueDate).getTime() - 280 * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
if (!lmpTime) {
|
||||
// 兜底:用当前日期和当前孕周反推
|
||||
const now = new Date();
|
||||
const totalDays = currentWeek * 7 + (user.currentDay || 0);
|
||||
lmpTime = now.getTime() - totalDays * 24 * 60 * 60 * 1000;
|
||||
}
|
||||
|
||||
const checkupDate = new Date(lmpTime + upcoming.week * 7 * 24 * 60 * 60 * 1000);
|
||||
const now = new Date();
|
||||
const diffDays = Math.max(0, Math.ceil((checkupDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000)));
|
||||
|
||||
return {
|
||||
title: upcoming.title,
|
||||
date: `${checkupDate.getFullYear()}-${String(checkupDate.getMonth() + 1).padStart(2, "0")}-${String(checkupDate.getDate()).padStart(2, "0")}`,
|
||||
daysLeft: diffDays,
|
||||
};
|
||||
}, [user.currentWeek, user.currentDay, user.lastPeriodDate, user.dueDate]);
|
||||
|
||||
// 生长曲线数据 - 只包含标准参考范围,不包含假的实际值
|
||||
const defaultGrowthData: Record<string, { name: string; unit: string; color: string; data: any[] }> = {
|
||||
bpd: {
|
||||
name: "双顶径",
|
||||
unit: "mm",
|
||||
color: "#8562AB",
|
||||
data: [
|
||||
{ week: 12, standard: 20, lower: 18, upper: 22 },
|
||||
{ week: 16, standard: 35, lower: 32, upper: 38 },
|
||||
{ week: 20, standard: 47, lower: 43, upper: 51 },
|
||||
{ week: 24, standard: 60, lower: 56, upper: 64 },
|
||||
{ week: 28, standard: 71, lower: 67, upper: 75 },
|
||||
{ week: 32, standard: 81, lower: 77, upper: 85 },
|
||||
{ week: 36, standard: 89, lower: 85, upper: 93 },
|
||||
],
|
||||
},
|
||||
ac: {
|
||||
name: "腹围",
|
||||
unit: "mm",
|
||||
color: "#A07CC5",
|
||||
data: [
|
||||
{ week: 12, standard: 60, lower: 54, upper: 66 },
|
||||
{ week: 16, standard: 102, lower: 94, upper: 110 },
|
||||
{ week: 20, standard: 148, lower: 138, upper: 158 },
|
||||
{ week: 24, standard: 192, lower: 180, upper: 204 },
|
||||
{ week: 28, standard: 235, lower: 221, upper: 249 },
|
||||
{ week: 32, standard: 279, lower: 263, upper: 295 },
|
||||
{ week: 36, standard: 318, lower: 300, upper: 336 },
|
||||
],
|
||||
},
|
||||
fl: {
|
||||
name: "股骨长",
|
||||
unit: "mm",
|
||||
color: "#C48BB0",
|
||||
data: [
|
||||
{ week: 12, standard: 8, lower: 7, upper: 9 },
|
||||
{ week: 16, standard: 22, lower: 20, upper: 24 },
|
||||
{ week: 20, standard: 34, lower: 31, upper: 37 },
|
||||
{ week: 24, standard: 45, lower: 42, upper: 48 },
|
||||
{ week: 28, standard: 54, lower: 51, upper: 57 },
|
||||
{ week: 32, standard: 63, lower: 60, upper: 66 },
|
||||
{ week: 36, standard: 70, lower: 67, upper: 73 },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const [growthData, setGrowthData] = useState(defaultGrowthData);
|
||||
|
||||
useEffect(() => {
|
||||
getGrowthCurve()
|
||||
.then((data) => {
|
||||
if (data.data_points && data.data_points.length > 0) {
|
||||
const updated = { ...defaultGrowthData };
|
||||
|
||||
// 只添加有真实数据的点
|
||||
for (const metric of ["bpd", "ac", "fl"] as const) {
|
||||
const apiPoints = data.data_points.filter((p) => p[metric] != null);
|
||||
|
||||
if (apiPoints.length > 0) {
|
||||
// 合并真实数据点和标准参考范围
|
||||
const allWeeks = new Set([
|
||||
...updated[metric].data.map(d => d.week),
|
||||
...apiPoints.map(p => p.week)
|
||||
]);
|
||||
|
||||
updated[metric] = {
|
||||
...updated[metric],
|
||||
data: Array.from(allWeeks)
|
||||
.sort((a, b) => a - b)
|
||||
.map((week) => {
|
||||
const standardPoint = updated[metric].data.find(d => d.week === week);
|
||||
const realPoint = apiPoints.find(p => p.week === week);
|
||||
|
||||
return {
|
||||
week,
|
||||
value: realPoint?.[metric] ?? null, // 只有真实数据才有 value
|
||||
standard: standardPoint?.standard ?? null,
|
||||
lower: standardPoint?.lower ?? null,
|
||||
upper: standardPoint?.upper ?? null,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
setGrowthData(updated);
|
||||
}
|
||||
// 如果没有数据,保持 defaultGrowthData(只有标准范围,没有实际值)
|
||||
})
|
||||
.catch(() => {/* keep defaults */});
|
||||
}, []);
|
||||
|
||||
const currentData = growthData[selectedMetric];
|
||||
|
||||
// 检查是否有真实数据
|
||||
const hasRealData = currentData.data.some(d => d.value != null);
|
||||
|
||||
// ─── 指标趋势分析 ───
|
||||
const [trendIndicators, setTrendIndicators] = useState<IndicatorTrend[]>([]);
|
||||
const [selectedTrend, setSelectedTrend] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
getIndicatorTrends()
|
||||
.then((data) => setTrendIndicators(data.indicators))
|
||||
.catch(() => {});
|
||||
}, []);
|
||||
|
||||
const currentTrend = trendIndicators[selectedTrend] || null;
|
||||
const trendChartData = useMemo(() => {
|
||||
if (!currentTrend) return [];
|
||||
return currentTrend.points.map((p) => ({
|
||||
week: p.week > 0 ? `${p.week}周` : p.date.split("T")[0]?.slice(5) || "",
|
||||
value: p.value,
|
||||
refLower: currentTrend.ref_lower,
|
||||
refUpper: currentTrend.ref_upper,
|
||||
}));
|
||||
}, [currentTrend]);
|
||||
|
||||
const CustomTooltip = ({ active, payload }: any) => {
|
||||
if (active && payload && payload.length) {
|
||||
return (
|
||||
<div className="bg-white p-3 rounded-xl shadow-lg border border-morandi-100">
|
||||
<p className="font-semibold text-gray-700 mb-1 text-xs">
|
||||
孕{payload[0].payload.week}周
|
||||
</p>
|
||||
<p className="text-xs text-morandi-500">
|
||||
实际: {payload[0].value} {currentData.unit}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400">
|
||||
标准: {payload[0].payload.standard} {currentData.unit}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white/80 backdrop-blur-sm border-b border-morandi-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-3 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 bg-gradient-to-br from-morandi-300 to-morandi-400 rounded-full flex items-center justify-center">
|
||||
<Heart className="w-4 h-4 text-white fill-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-700 text-sm">孕育无忧</h1>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
onClick={() => navigate("/notifications")}
|
||||
className="w-9 h-9 rounded-full hover:bg-morandi-50 flex items-center justify-center relative"
|
||||
>
|
||||
<Bell className="w-4.5 h-4.5 text-gray-400" />
|
||||
<span className="absolute top-1.5 right-1.5 w-1.5 h-1.5 bg-morandi-rose-400 rounded-full" />
|
||||
</button>
|
||||
<button
|
||||
onClick={() => navigate("/profile")}
|
||||
className="w-9 h-9 rounded-full hover:bg-morandi-50 flex items-center justify-center"
|
||||
>
|
||||
<User className="w-4.5 h-4.5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-4">
|
||||
{/* 孕周卡片 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-br from-morandi-400 via-morandi-300 to-morandi-rose-300 border-0 text-white px-4 py-3 rounded-2xl shadow-sm">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-baseline gap-1">
|
||||
<span className="text-xl font-bold">{weekInfo.week}</span>
|
||||
<span className="text-xs font-medium text-white/80">周</span>
|
||||
<span className="text-xl font-bold">{weekInfo.day}</span>
|
||||
<span className="text-xs font-medium text-white/80">天</span>
|
||||
</div>
|
||||
<div className="text-xs text-white/80">
|
||||
预产期 <span className="font-medium text-white">{weekInfo.dueDate}</span>
|
||||
</div>
|
||||
</div>
|
||||
{nextCheckup && (
|
||||
<div
|
||||
className="mt-2 bg-white/15 rounded-lg px-3 py-1.5 flex items-center justify-between cursor-pointer"
|
||||
onClick={() => navigate("/calendar")}
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Calendar className="w-3.5 h-3.5 text-white/70" />
|
||||
<span className="text-[11px] text-white/90">{nextCheckup.title}</span>
|
||||
<span className="text-[11px] text-white/50">{nextCheckup.date}</span>
|
||||
</div>
|
||||
<span className="text-[11px] font-medium text-white/80">{nextCheckup.daysLeft}天后</span>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 快捷操作 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.05 }}
|
||||
>
|
||||
<div className="grid grid-cols-[1.05fr_0.95fr] gap-3">
|
||||
<button
|
||||
onClick={() => navigate("/camera")}
|
||||
className="bg-white rounded-2xl p-4 shadow-sm hover:shadow-md transition-all group text-left min-h-[182px]"
|
||||
>
|
||||
<div className="h-full flex flex-col justify-between">
|
||||
<div className="w-12 h-12 bg-morandi-rose-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform">
|
||||
<Camera className="w-5 h-5 text-morandi-rose-400" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="font-medium text-gray-700 text-base">AI报告解读</div>
|
||||
<div className="text-xs text-gray-400 mt-1 leading-relaxed">
|
||||
拍照上传<br />快速查看解读结果
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<div className="space-y-2.5">
|
||||
<button
|
||||
onClick={() => navigate("/calendar")}
|
||||
className="w-full bg-white rounded-2xl p-3.5 shadow-sm hover:shadow-md transition-all group text-left"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 bg-morandi-sage-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform flex-shrink-0">
|
||||
<Calendar className="w-4.5 h-4.5 text-morandi-sage-400" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-gray-700 text-sm">产检日历</div>
|
||||
<div className="text-[11px] text-gray-400 mt-0.5">产检计划·提醒</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate("/health-records")}
|
||||
className="w-full bg-white rounded-2xl p-3.5 shadow-sm hover:shadow-md transition-all group text-left"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 bg-morandi-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform flex-shrink-0">
|
||||
<FileText className="w-4.5 h-4.5 text-morandi-500" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-gray-700 text-sm">健康报告</div>
|
||||
<div className="text-[11px] text-gray-400 mt-0.5">数据分析</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => navigate("/voice-record")}
|
||||
className="w-full bg-white rounded-2xl p-3.5 shadow-sm hover:shadow-md transition-all group text-left"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 bg-morandi-100 rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform flex-shrink-0">
|
||||
<Mic className="w-4.5 h-4.5 text-morandi-500" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="font-medium text-gray-700 text-sm">语音记录</div>
|
||||
<div className="text-[11px] text-gray-400 mt-0.5">就诊记录·孕期日记</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 宝宝生长趋势 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.15 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
|
||||
<TrendingUp className="w-5 h-5 text-morandi-400" />
|
||||
宝宝生长趋势
|
||||
</h2>
|
||||
<button
|
||||
onClick={() => navigate("/growth-curve")}
|
||||
className="text-xs text-morandi-500 hover:text-morandi-600 flex items-center"
|
||||
>
|
||||
查看详情
|
||||
<ChevronRight className="w-3.5 h-3.5 ml-0.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{hasRealData ? (
|
||||
<>
|
||||
{/* 指标选择 */}
|
||||
<div className="flex gap-2 mb-4">
|
||||
{[
|
||||
{ key: "bpd", label: "双顶径" },
|
||||
{ key: "ac", label: "腹围" },
|
||||
{ key: "fl", label: "股骨长" },
|
||||
].map((m) => (
|
||||
<button
|
||||
key={m.key}
|
||||
onClick={() => setSelectedMetric(m.key)}
|
||||
className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all ${
|
||||
selectedMetric === m.key
|
||||
? "bg-morandi-400 text-white"
|
||||
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
|
||||
}`}
|
||||
>
|
||||
{m.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 图表 */}
|
||||
<div className="mb-4">
|
||||
<ResponsiveContainer width="100%" height={180}>
|
||||
<ComposedChart data={currentData.data}>
|
||||
<defs>
|
||||
<linearGradient id="colorRange" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#C4A8DC" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="#C4A8DC" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#EDE6F2" />
|
||||
<XAxis
|
||||
dataKey="week"
|
||||
stroke="#B0A8B8"
|
||||
tick={{ fontSize: 11 }}
|
||||
/>
|
||||
<YAxis stroke="#B0A8B8" tick={{ fontSize: 11 }} />
|
||||
<Tooltip content={<CustomTooltip />} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="upper"
|
||||
stroke="none"
|
||||
fill="url(#colorRange)"
|
||||
/>
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="lower"
|
||||
stroke="none"
|
||||
fill="#ffffff"
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="standard"
|
||||
stroke="#C4A8DC"
|
||||
strokeWidth={2}
|
||||
dot={false}
|
||||
strokeDasharray="5 5"
|
||||
/>
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke={currentData.color}
|
||||
strokeWidth={2.5}
|
||||
dot={{ fill: currentData.color, r: 3.5 }}
|
||||
connectNulls={false}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
{/* 图例 */}
|
||||
<div className="flex items-center gap-4 mb-3 text-xs">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div
|
||||
className="w-2 h-2 rounded-full"
|
||||
style={{ backgroundColor: currentData.color }}
|
||||
/>
|
||||
<span className="text-gray-500">实际值</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 bg-morandi-200 rounded-full" />
|
||||
<span className="text-gray-500">标准值</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 bg-morandi-100 rounded-full" />
|
||||
<span className="text-gray-500">正常范围</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 评估 */}
|
||||
{(() => {
|
||||
const realPoints = currentData.data.filter((d: any) => d.value != null);
|
||||
if (realPoints.length === 0) return null;
|
||||
const latest = realPoints[realPoints.length - 1];
|
||||
const val = latest.value!;
|
||||
const inRange = val >= latest.lower && val <= latest.upper;
|
||||
const isHigh = val > latest.upper;
|
||||
const assessBg = inRange ? "bg-morandi-50" : "bg-amber-50";
|
||||
const assessIcon = inRange ? "text-morandi-sage-400" : "text-amber-500";
|
||||
const assessText = inRange
|
||||
? `宝宝的${currentData.name}发育良好,孕${latest.week}周实测${val}${currentData.unit},在正常范围内`
|
||||
: isHigh
|
||||
? `宝宝的${currentData.name}孕${latest.week}周实测${val}${currentData.unit},略高于参考上限${latest.upper}${currentData.unit},建议关注`
|
||||
: `宝宝的${currentData.name}孕${latest.week}周实测${val}${currentData.unit},略低于参考下限${latest.lower}${currentData.unit},建议关注`;
|
||||
return (
|
||||
<div className={`${assessBg} rounded-xl p-3`}>
|
||||
<div className="flex items-start gap-2">
|
||||
<Info className={`w-4 h-4 ${assessIcon} mt-0.5 flex-shrink-0`} />
|
||||
<p className="text-xs text-gray-500 leading-relaxed">{assessText}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</>
|
||||
) : (
|
||||
<BabyExpectedSizeCard week={weekInfo.week} onUpload={() => navigate("/camera")} />
|
||||
)}
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 孕检报告趋势分析 */}
|
||||
{trendIndicators.length > 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 16 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="font-semibold text-gray-700 flex items-center gap-2 text-base">
|
||||
<TrendingUp className="w-5 h-5 text-morandi-sage-400" />
|
||||
报告趋势分析
|
||||
</h2>
|
||||
<span className="text-xs text-gray-400">{trendIndicators.length}项可对比指标</span>
|
||||
</div>
|
||||
|
||||
{/* 指标选择 - 横向滚动 */}
|
||||
<div className="flex gap-2 mb-4 overflow-x-auto pb-1 -mx-1 px-1 scrollbar-hide">
|
||||
{trendIndicators.map((ind, idx) => (
|
||||
<button
|
||||
key={ind.name}
|
||||
onClick={() => setSelectedTrend(idx)}
|
||||
className={`px-3 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition-all flex-shrink-0 ${
|
||||
selectedTrend === idx
|
||||
? "bg-morandi-sage-400 text-white"
|
||||
: "bg-morandi-50 text-gray-500 hover:bg-morandi-100"
|
||||
}`}
|
||||
>
|
||||
{ind.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{currentTrend && (
|
||||
<>
|
||||
{/* 趋势图表 */}
|
||||
<div className="mb-4">
|
||||
<ResponsiveContainer width="100%" height={180}>
|
||||
<ComposedChart data={trendChartData}>
|
||||
<defs>
|
||||
<linearGradient id="trendRefRange" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="#A8C5A0" stopOpacity={0.2} />
|
||||
<stop offset="95%" stopColor="#A8C5A0" stopOpacity={0.05} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" stroke="#EDE6F2" />
|
||||
<XAxis dataKey="week" stroke="#B0A8B8" tick={{ fontSize: 11 }} />
|
||||
<YAxis stroke="#B0A8B8" tick={{ fontSize: 11 }} />
|
||||
<Tooltip
|
||||
content={({ active, payload }: any) => {
|
||||
if (active && payload?.[0]) {
|
||||
const d = payload[0].payload;
|
||||
return (
|
||||
<div className="bg-white p-3 rounded-xl shadow-lg border border-morandi-100">
|
||||
<p className="font-semibold text-gray-700 text-xs mb-1">{d.week}</p>
|
||||
<p className="text-xs text-morandi-sage-500">
|
||||
{currentTrend.name}: {d.value} {currentTrend.unit}
|
||||
</p>
|
||||
{d.refLower != null && d.refUpper != null && (
|
||||
<p className="text-xs text-gray-400">
|
||||
参考: {d.refLower}-{d.refUpper} {currentTrend.unit}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}}
|
||||
/>
|
||||
{currentTrend.ref_upper != null && (
|
||||
<Area type="monotone" dataKey="refUpper" stroke="none" fill="url(#trendRefRange)" />
|
||||
)}
|
||||
{currentTrend.ref_lower != null && (
|
||||
<Area type="monotone" dataKey="refLower" stroke="none" fill="#ffffff" />
|
||||
)}
|
||||
<Line
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke="#7BA37A"
|
||||
strokeWidth={2.5}
|
||||
dot={{ fill: "#7BA37A", r: 4 }}
|
||||
/>
|
||||
</ComposedChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
|
||||
{/* 图例 */}
|
||||
<div className="flex items-center gap-4 mb-3 text-xs">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 rounded-full bg-[#7BA37A]" />
|
||||
<span className="text-gray-500">实际值</span>
|
||||
</div>
|
||||
{currentTrend.ref_lower != null && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className="w-2 h-2 bg-morandi-sage-100 rounded-full" />
|
||||
<span className="text-gray-500">
|
||||
参考范围 {currentTrend.ref_lower}-{currentTrend.ref_upper} {currentTrend.unit}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 数据表格 */}
|
||||
<div className="bg-morandi-50 rounded-xl p-3">
|
||||
<div className="grid grid-cols-3 gap-1 text-xs text-gray-400 mb-2 px-1">
|
||||
<span>时间</span>
|
||||
<span className="text-center">数值</span>
|
||||
<span className="text-right">状态</span>
|
||||
</div>
|
||||
{currentTrend.points.map((p, i) => (
|
||||
<div key={i} className="grid grid-cols-3 gap-1 text-xs px-1 py-1.5 border-t border-morandi-100">
|
||||
<span className="text-gray-600">{p.week > 0 ? `第${p.week}周` : p.date.split("T")[0]?.slice(5)}</span>
|
||||
<span className="text-center font-medium text-gray-700">
|
||||
{p.value} {currentTrend.unit}
|
||||
</span>
|
||||
<span className={`text-right ${
|
||||
p.status === "normal" ? "text-morandi-sage-500" :
|
||||
p.status === "high" ? "text-morandi-rose-500" :
|
||||
"text-amber-500"
|
||||
}`}>
|
||||
{p.status === "normal" ? "正常" : p.status === "high" ? "偏高" : "偏低"}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Card>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 底部留白 */}
|
||||
<div className="h-16" />
|
||||
</div>
|
||||
|
||||
{/* 浮动按钮 */}
|
||||
<motion.button
|
||||
onClick={() => navigate("/camera")}
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ delay: 0.3, type: "spring" }}
|
||||
className="fixed bottom-8 right-8 w-14 h-14 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full shadow-lg flex items-center justify-center hover:scale-105 transition-transform"
|
||||
>
|
||||
<Plus className="w-7 h-7 text-white" />
|
||||
</motion.button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
365
frontend/src/app/pages/LoginPage.tsx
Normal file
365
frontend/src/app/pages/LoginPage.tsx
Normal file
@@ -0,0 +1,365 @@
|
||||
import { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import { Heart, Loader2, Phone, ArrowRight, ChevronLeft } from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { useUser } from "../context/UserContext";
|
||||
import { loginByWechat, loginByDemo, loginByPhone, getToken } from "../services/api";
|
||||
|
||||
/** 判断是否在微信小程序 webview 环境 */
|
||||
function isWechatMiniProgram(): boolean {
|
||||
const ua = navigator.userAgent.toLowerCase();
|
||||
return ua.includes("micromessenger") && ua.includes("miniprogram");
|
||||
}
|
||||
|
||||
/** 调用 wx.miniProgram.login 获取 code */
|
||||
function wxLogin(): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const wx = (window as any).wx;
|
||||
if (!wx?.miniProgram) {
|
||||
reject(new Error("非小程序环境"));
|
||||
return;
|
||||
}
|
||||
wx.miniProgram.login({
|
||||
success: (res: any) => {
|
||||
if (res.code) {
|
||||
resolve(res.code);
|
||||
} else {
|
||||
reject(new Error("获取登录凭证失败"));
|
||||
}
|
||||
},
|
||||
fail: () => reject(new Error("微信登录失败")),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { setToken, fetchProfile, user } = useUser();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [autoLoginTried, setAutoLoginTried] = useState(false);
|
||||
|
||||
// 手机号登录状态
|
||||
const [showPhoneLogin, setShowPhoneLogin] = useState(false);
|
||||
const [phoneNumber, setPhoneNumber] = useState("");
|
||||
const [smsCode, setSmsCode] = useState("");
|
||||
const [smsSent, setSmsSent] = useState(false);
|
||||
const [countdown, setCountdown] = useState(0);
|
||||
const countdownRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
|
||||
// 已有 token 且已完成 onboarding,直接跳首页
|
||||
useEffect(() => {
|
||||
if (getToken() && user.isOnboarded) {
|
||||
navigate("/home", { replace: true });
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 倒计时
|
||||
useEffect(() => {
|
||||
if (countdown > 0) {
|
||||
countdownRef.current = setInterval(() => {
|
||||
setCountdown((prev) => {
|
||||
if (prev <= 1) {
|
||||
if (countdownRef.current) clearInterval(countdownRef.current);
|
||||
return 0;
|
||||
}
|
||||
return prev - 1;
|
||||
});
|
||||
}, 1000);
|
||||
}
|
||||
return () => {
|
||||
if (countdownRef.current) clearInterval(countdownRef.current);
|
||||
};
|
||||
}, [countdown > 0]);
|
||||
|
||||
const handleLoginSuccess = useCallback(
|
||||
async (res: { access_token: string; is_new_user: boolean }) => {
|
||||
setToken(res.access_token);
|
||||
if (res.is_new_user) {
|
||||
// 新用户 → 走 onboarding 流程
|
||||
navigate("/onboarding");
|
||||
} else {
|
||||
// 老用户 → 拉取资料后直接进首页
|
||||
await fetchProfile();
|
||||
navigate("/home", { replace: true });
|
||||
}
|
||||
},
|
||||
[setToken, fetchProfile, navigate]
|
||||
);
|
||||
|
||||
// 小程序环境自动登录
|
||||
useEffect(() => {
|
||||
if (autoLoginTried) return;
|
||||
if (getToken() && user.isOnboarded) return;
|
||||
|
||||
if (isWechatMiniProgram()) {
|
||||
setAutoLoginTried(true);
|
||||
setIsLoading(true);
|
||||
wxLogin()
|
||||
.then((code) => loginByWechat(code))
|
||||
.then(handleLoginSuccess)
|
||||
.catch((err) => {
|
||||
setError(err.message || "自动登录失败");
|
||||
})
|
||||
.finally(() => setIsLoading(false));
|
||||
}
|
||||
}, [autoLoginTried, user.isOnboarded, handleLoginSuccess]);
|
||||
|
||||
// 一键体验(demo)
|
||||
const handleDemoLogin = async () => {
|
||||
setError("");
|
||||
setIsLoading(true);
|
||||
try {
|
||||
if (isWechatMiniProgram()) {
|
||||
const code = await wxLogin();
|
||||
const res = await loginByWechat(code);
|
||||
await handleLoginSuccess(res);
|
||||
} else {
|
||||
const res = await loginByDemo();
|
||||
await handleLoginSuccess(res);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "登录失败,请重试";
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 发送验证码
|
||||
const handleSendSms = () => {
|
||||
if (phoneNumber.length !== 11) {
|
||||
setError("请输入正确的11位手机号");
|
||||
return;
|
||||
}
|
||||
setError("");
|
||||
setSmsSent(true);
|
||||
setCountdown(60);
|
||||
};
|
||||
|
||||
// 手机号登录
|
||||
const handlePhoneLogin = async () => {
|
||||
if (phoneNumber.length !== 11) {
|
||||
setError("请输入正确的11位手机号");
|
||||
return;
|
||||
}
|
||||
if (smsCode.length < 4) {
|
||||
setError("请输入验证码");
|
||||
return;
|
||||
}
|
||||
setError("");
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const res = await loginByPhone(phoneNumber, smsCode);
|
||||
await handleLoginSuccess(res);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "登录失败,请重试";
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center p-4">
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="w-full"
|
||||
>
|
||||
<div className="text-center mb-8">
|
||||
<motion.div
|
||||
initial={{ scale: 0 }}
|
||||
animate={{ scale: 1 }}
|
||||
transition={{ delay: 0.2, type: "spring" }}
|
||||
className="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-morandi-300 to-morandi-400 rounded-full mb-4"
|
||||
>
|
||||
<Heart className="w-10 h-10 text-white fill-white" />
|
||||
</motion.div>
|
||||
<h1 className="text-3xl font-semibold bg-gradient-to-r from-morandi-400 to-morandi-500 bg-clip-text text-transparent mb-2">
|
||||
孕育无忧
|
||||
</h1>
|
||||
<p className="text-gray-600">您的专属孕期健康助手</p>
|
||||
</div>
|
||||
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ delay: 0.3 }}
|
||||
className="bg-white rounded-3xl shadow-md p-8"
|
||||
>
|
||||
<AnimatePresence mode="wait">
|
||||
{!showPhoneLogin ? (
|
||||
/* ─── 主登录页 ─── */
|
||||
<motion.div
|
||||
key="main"
|
||||
initial={{ opacity: 0, x: 0 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
className="space-y-4"
|
||||
>
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -5 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="text-sm text-red-500 bg-red-50 px-4 py-2 rounded-xl"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
{/* 手机号登录按钮 */}
|
||||
<Button
|
||||
onClick={() => { setError(""); setShowPhoneLogin(true); }}
|
||||
disabled={isLoading}
|
||||
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
|
||||
>
|
||||
<Phone className="w-4 h-4 mr-2" />
|
||||
手机号登录
|
||||
</Button>
|
||||
|
||||
{/* 分隔线 */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-1 h-px bg-gray-200" />
|
||||
<span className="text-xs text-gray-400">或</span>
|
||||
<div className="flex-1 h-px bg-gray-200" />
|
||||
</div>
|
||||
|
||||
{/* 一键体验 */}
|
||||
<Button
|
||||
onClick={handleDemoLogin}
|
||||
disabled={isLoading}
|
||||
variant="outline"
|
||||
className="w-full h-12 rounded-xl border-2 border-morandi-200 text-morandi-500 font-medium hover:bg-morandi-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
登录中...
|
||||
</>
|
||||
) : isWechatMiniProgram() ? (
|
||||
"微信一键授权登录"
|
||||
) : (
|
||||
"游客体验"
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-gray-400 text-center">
|
||||
游客模式数据不保留,建议使用手机号登录
|
||||
</p>
|
||||
</motion.div>
|
||||
) : (
|
||||
/* ─── 手机号登录表单 ─── */
|
||||
<motion.div
|
||||
key="phone"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: 20 }}
|
||||
className="space-y-4"
|
||||
>
|
||||
{/* 返回 */}
|
||||
<button
|
||||
onClick={() => { setShowPhoneLogin(false); setError(""); setSmsSent(false); setSmsCode(""); }}
|
||||
className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 -ml-1 mb-1"
|
||||
>
|
||||
<ChevronLeft className="w-4 h-4" />
|
||||
返回
|
||||
</button>
|
||||
|
||||
<h2 className="text-lg font-semibold text-gray-800">手机号登录</h2>
|
||||
<p className="text-sm text-gray-500 -mt-2">登录后数据将绑定到您的手机号</p>
|
||||
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<motion.p
|
||||
initial={{ opacity: 0, y: -5 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="text-sm text-red-500 bg-red-50 px-4 py-2 rounded-xl"
|
||||
>
|
||||
{error}
|
||||
</motion.p>
|
||||
)}
|
||||
|
||||
{/* 手机号输入 */}
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm text-gray-600 font-medium">手机号</label>
|
||||
<input
|
||||
type="tel"
|
||||
maxLength={11}
|
||||
value={phoneNumber}
|
||||
onChange={(e) => setPhoneNumber(e.target.value.replace(/\D/g, ""))}
|
||||
placeholder="请输入11位手机号"
|
||||
className="w-full h-12 px-4 rounded-xl border-2 border-gray-200 focus:border-morandi-400 outline-none transition-colors text-base"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 验证码输入 */}
|
||||
<div className="space-y-1">
|
||||
<label className="text-sm text-gray-600 font-medium">验证码</label>
|
||||
<div className="flex gap-3">
|
||||
<input
|
||||
type="text"
|
||||
maxLength={6}
|
||||
value={smsCode}
|
||||
onChange={(e) => setSmsCode(e.target.value.replace(/\D/g, ""))}
|
||||
placeholder="请输入验证码"
|
||||
className="flex-1 h-12 px-4 rounded-xl border-2 border-gray-200 focus:border-morandi-400 outline-none transition-colors text-base"
|
||||
/>
|
||||
<button
|
||||
onClick={handleSendSms}
|
||||
disabled={countdown > 0 || phoneNumber.length !== 11}
|
||||
className={`px-4 h-12 rounded-xl text-sm font-medium whitespace-nowrap transition-all ${
|
||||
countdown > 0 || phoneNumber.length !== 11
|
||||
? "bg-gray-100 text-gray-400"
|
||||
: "bg-morandi-100 text-morandi-500 hover:bg-morandi-200"
|
||||
}`}
|
||||
>
|
||||
{countdown > 0 ? `${countdown}s` : smsSent ? "重新发送" : "获取验证码"}
|
||||
</button>
|
||||
</div>
|
||||
{smsSent && (
|
||||
<p className="text-xs text-morandi-400 mt-1">
|
||||
验证码已发送,请输入 123456
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 登录按钮 */}
|
||||
<Button
|
||||
onClick={handlePhoneLogin}
|
||||
disabled={isLoading || phoneNumber.length !== 11 || smsCode.length < 4}
|
||||
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
登录中...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
登录
|
||||
<ArrowRight className="w-4 h-4 ml-2" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
|
||||
<p className="text-xs text-gray-500 text-center mt-6">
|
||||
登录即表示同意
|
||||
<a href="#" className="text-morandi-400 hover:underline">
|
||||
用户协议
|
||||
</a>
|
||||
和
|
||||
<a href="#" className="text-morandi-400 hover:underline">
|
||||
隐私政策
|
||||
</a>
|
||||
</p>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
462
frontend/src/app/pages/NotificationPage.tsx
Normal file
462
frontend/src/app/pages/NotificationPage.tsx
Normal file
@@ -0,0 +1,462 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Bell,
|
||||
Clock,
|
||||
CheckCircle2,
|
||||
ChevronRight,
|
||||
Stethoscope,
|
||||
Baby,
|
||||
CircleDot,
|
||||
AlertCircle,
|
||||
Calendar,
|
||||
} from "lucide-react";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { useUser, calcPregnancyWeek } from "../context/UserContext";
|
||||
import { checkupSchedule } from "../data/checkupSchedule";
|
||||
|
||||
interface Notification {
|
||||
id: string;
|
||||
type: "checkup_reminder" | "preparation" | "weekly_tip" | "milestone";
|
||||
title: string;
|
||||
content: string;
|
||||
time: string;
|
||||
read: boolean;
|
||||
tags?: string[];
|
||||
link?: string;
|
||||
checkupItems?: string[];
|
||||
checkupPreparations?: string[];
|
||||
}
|
||||
|
||||
function generateNotifications(currentWeek: number, lastPeriodDate: string): Notification[] {
|
||||
const notifications: Notification[] = [];
|
||||
|
||||
// 下次产检提醒(来源于产检日历)
|
||||
const nextCheckup = checkupSchedule.find((c) => c.week > currentWeek);
|
||||
if (nextCheckup) {
|
||||
let dateStr = "";
|
||||
let daysInfo = "";
|
||||
if (lastPeriodDate) {
|
||||
const lmp = new Date(lastPeriodDate);
|
||||
const checkupDate = new Date(lmp.getTime() + nextCheckup.week * 7 * 24 * 60 * 60 * 1000);
|
||||
dateStr = checkupDate.toISOString().split("T")[0];
|
||||
const daysUntil = Math.max(0, Math.ceil((checkupDate.getTime() - Date.now()) / (1000 * 60 * 60 * 24)));
|
||||
daysInfo = `${dateStr} · 距今${daysUntil}天`;
|
||||
} else {
|
||||
daysInfo = `还有${nextCheckup.week - currentWeek}周`;
|
||||
}
|
||||
|
||||
notifications.push({
|
||||
id: "next-checkup",
|
||||
type: "checkup_reminder",
|
||||
title: `下次产检:${nextCheckup.title}`,
|
||||
content: `孕${nextCheckup.week}周 · ${daysInfo}`,
|
||||
time: "今天",
|
||||
read: false,
|
||||
tags: nextCheckup.preparations.filter(
|
||||
(p) => p.includes("空腹") || p.includes("憋尿") || p.startsWith("需")
|
||||
),
|
||||
checkupItems: nextCheckup.items,
|
||||
checkupPreparations: nextCheckup.preparations,
|
||||
});
|
||||
|
||||
// 产检项目提醒
|
||||
notifications.push({
|
||||
id: "checkup-items",
|
||||
type: "preparation",
|
||||
title: `${nextCheckup.title}检查项目`,
|
||||
content: `共${nextCheckup.items.length}项:${nextCheckup.items.slice(0, 3).join("、")}${nextCheckup.items.length > 3 ? "等" : ""}`,
|
||||
time: "今天",
|
||||
read: false,
|
||||
link: "/calendar",
|
||||
});
|
||||
|
||||
// 特殊注意事项
|
||||
const specialPreps = nextCheckup.preparations.filter(
|
||||
(p) => p.includes("空腹") || p.includes("憋尿") || p.includes("携带") || p.includes("预约")
|
||||
);
|
||||
if (specialPreps.length > 0) {
|
||||
notifications.push({
|
||||
id: "prep-reminder",
|
||||
type: "preparation",
|
||||
title: "产检准备提醒",
|
||||
content: specialPreps.join(";"),
|
||||
time: "今天",
|
||||
read: false,
|
||||
tags: specialPreps.filter((p) => p.includes("空腹") || p.includes("憋尿")),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 孕周知识推送
|
||||
notifications.push({
|
||||
id: "weekly-tip",
|
||||
type: "weekly_tip",
|
||||
title: `孕${currentWeek}周知识`,
|
||||
content: `本周宝宝正在快速发育,请注意补充营养,避免剧烈运动,保持充足睡眠。`,
|
||||
time: "今天",
|
||||
read: false,
|
||||
});
|
||||
|
||||
// 孕期里程碑
|
||||
const milestones: Record<number, string> = {
|
||||
8: "宝宝的心脏已经开始跳动,四肢也开始发育。记得按时服用叶酸哦~",
|
||||
12: "宝宝已经有了人的模样,可以做NT检查了。进入相对稳定的孕中期!",
|
||||
16: "宝宝开始有了听觉,可以和宝宝说说话啦~",
|
||||
20: "宝宝可以感受到外界的光线了,是做大排畸检查的好时机!",
|
||||
24: "宝宝体重快速增长,记得做糖耐量检查哦~",
|
||||
28: "进入孕晚期啦!产检频率要增加了,注意数胎动~",
|
||||
32: "宝宝头部朝下准备入盆,可以开始准备待产包了!",
|
||||
36: "宝宝随时可能发动,做好迎接宝宝的准备吧~",
|
||||
};
|
||||
const milestoneWeek = Object.keys(milestones).map(Number).find((w) => w === currentWeek);
|
||||
if (milestoneWeek) {
|
||||
notifications.push({
|
||||
id: `milestone-${milestoneWeek}`,
|
||||
type: "milestone",
|
||||
title: `孕${milestoneWeek}周里程碑`,
|
||||
content: `恭喜进入孕${milestoneWeek}周!${milestones[milestoneWeek]}`,
|
||||
time: "昨天",
|
||||
read: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 下下次产检预告
|
||||
const secondCheckup = checkupSchedule.find((c) => nextCheckup && c.week > nextCheckup.week);
|
||||
if (secondCheckup) {
|
||||
notifications.push({
|
||||
id: "future-checkup",
|
||||
type: "checkup_reminder",
|
||||
title: `产检预告:${secondCheckup.title}`,
|
||||
content: `孕${secondCheckup.week}周 · ${secondCheckup.items.slice(0, 2).join("、")}等`,
|
||||
time: "3天前",
|
||||
read: true,
|
||||
link: "/calendar",
|
||||
});
|
||||
}
|
||||
|
||||
// 上周知识回顾
|
||||
if (currentWeek > 1) {
|
||||
notifications.push({
|
||||
id: "last-week-tip",
|
||||
type: "weekly_tip",
|
||||
title: `孕${currentWeek - 1}周回顾`,
|
||||
content: "上周的营养建议:多摄入富含蛋白质和铁元素的食物,每日补充0.4mg叶酸。",
|
||||
time: "一周前",
|
||||
read: true,
|
||||
});
|
||||
}
|
||||
|
||||
return notifications;
|
||||
}
|
||||
|
||||
export function NotificationPage() {
|
||||
const navigate = useNavigate();
|
||||
const { user } = useUser();
|
||||
const currentWeek = user.currentWeek || 0;
|
||||
const [notifications, setNotifications] = useState<Notification[]>(() =>
|
||||
generateNotifications(currentWeek, user.lastPeriodDate)
|
||||
);
|
||||
const [filter, setFilter] = useState<"all" | "unread">("all");
|
||||
const [expandedId, setExpandedId] = useState<string | null>(null);
|
||||
|
||||
const unreadCount = notifications.filter((n) => !n.read && n.type !== "preparation").length;
|
||||
const filteredNotifications =
|
||||
filter === "unread"
|
||||
? notifications.filter((n) => !n.read && n.type !== "preparation")
|
||||
: notifications.filter((n) => n.type !== "preparation");
|
||||
|
||||
const markAsRead = (id: string) => {
|
||||
setNotifications((prev) =>
|
||||
prev.map((n) => (n.id === id ? { ...n, read: true } : n))
|
||||
);
|
||||
};
|
||||
|
||||
const markAllRead = () => {
|
||||
setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
|
||||
};
|
||||
|
||||
const getIcon = (type: Notification["type"]) => {
|
||||
switch (type) {
|
||||
case "checkup_reminder":
|
||||
return <Stethoscope className="w-5 h-5 text-morandi-500" />;
|
||||
case "preparation":
|
||||
return <AlertCircle className="w-5 h-5 text-morandi-rose-400" />;
|
||||
case "weekly_tip":
|
||||
return <Baby className="w-5 h-5 text-morandi-400" />;
|
||||
case "milestone":
|
||||
return <CircleDot className="w-5 h-5 text-morandi-sage-400" />;
|
||||
}
|
||||
};
|
||||
|
||||
const getIconBg = (type: Notification["type"]) => {
|
||||
switch (type) {
|
||||
case "checkup_reminder":
|
||||
return "bg-morandi-100";
|
||||
case "preparation":
|
||||
return "bg-morandi-rose-100";
|
||||
case "weekly_tip":
|
||||
return "bg-morandi-50";
|
||||
case "milestone":
|
||||
return "bg-morandi-sage-100";
|
||||
}
|
||||
};
|
||||
|
||||
const getTypeLabel = (type: Notification["type"]) => {
|
||||
switch (type) {
|
||||
case "checkup_reminder":
|
||||
return "产检提醒";
|
||||
case "preparation":
|
||||
return "注意事项";
|
||||
case "weekly_tip":
|
||||
return "孕周知识";
|
||||
case "milestone":
|
||||
return "孕期里程碑";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-gradient-to-br from-morandi-300 to-morandi-400 rounded-full flex items-center justify-center">
|
||||
<Bell className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">消息中心</h1>
|
||||
<p className="text-xs text-gray-500">
|
||||
{unreadCount > 0 ? `${unreadCount}条未读消息` : "暂无未读消息"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{unreadCount > 0 && (
|
||||
<button
|
||||
onClick={markAllRead}
|
||||
className="text-xs text-morandi-500 hover:text-morandi-600 font-medium"
|
||||
>
|
||||
全部已读
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-5">
|
||||
{/* 筛选按钮 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<h2 className="font-semibold text-gray-800 flex-1">全部消息</h2>
|
||||
<div className="flex gap-1.5 bg-white rounded-full p-1 shadow-sm">
|
||||
{(["all", "unread"] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
onClick={() => setFilter(f)}
|
||||
className={`px-4 py-1.5 rounded-full text-xs font-medium transition-all ${
|
||||
filter === f
|
||||
? "bg-morandi-400 text-white"
|
||||
: "text-gray-500 hover:bg-morandi-50"
|
||||
}`}
|
||||
>
|
||||
{f === "all" ? "全部" : `未读 (${unreadCount})`}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 消息列表 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.05 }}
|
||||
className="space-y-3"
|
||||
>
|
||||
<AnimatePresence mode="popLayout">
|
||||
{filteredNotifications.length === 0 ? (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="text-center py-12"
|
||||
>
|
||||
<CheckCircle2 className="w-12 h-12 text-morandi-200 mx-auto mb-3" />
|
||||
<p className="text-gray-400 text-sm">暂无未读消息</p>
|
||||
</motion.div>
|
||||
) : (
|
||||
filteredNotifications.map((notification, index) => (
|
||||
<motion.div
|
||||
key={notification.id}
|
||||
layout
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: 20 }}
|
||||
transition={{ delay: index * 0.03 }}
|
||||
>
|
||||
<Card
|
||||
className={`rounded-2xl p-4 shadow-sm border-0 cursor-pointer transition-all hover:shadow-md ${
|
||||
!notification.read
|
||||
? "bg-white border-l-4 border-l-morandi-400"
|
||||
: "bg-white opacity-80"
|
||||
}`}
|
||||
onClick={() => {
|
||||
markAsRead(notification.id);
|
||||
if (expandedId === notification.id) {
|
||||
setExpandedId(null);
|
||||
} else {
|
||||
setExpandedId(notification.id);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start gap-3">
|
||||
<div
|
||||
className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${getIconBg(
|
||||
notification.type
|
||||
)}`}
|
||||
>
|
||||
{getIcon(notification.type)}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<Badge
|
||||
className={`text-[10px] px-1.5 py-0 ${
|
||||
notification.type === "checkup_reminder"
|
||||
? "bg-morandi-100 text-morandi-600"
|
||||
: notification.type === "preparation"
|
||||
? "bg-morandi-rose-100 text-morandi-rose-400"
|
||||
: notification.type === "milestone"
|
||||
? "bg-morandi-sage-100 text-morandi-sage-500"
|
||||
: "bg-morandi-50 text-morandi-400"
|
||||
} hover:bg-current`}
|
||||
>
|
||||
{getTypeLabel(notification.type)}
|
||||
</Badge>
|
||||
<span className="text-[10px] text-gray-400 ml-auto flex-shrink-0">
|
||||
{notification.time}
|
||||
</span>
|
||||
{!notification.read && (
|
||||
<span className="w-2 h-2 bg-morandi-rose-400 rounded-full flex-shrink-0" />
|
||||
)}
|
||||
</div>
|
||||
<h4 className="font-medium text-gray-800 text-sm mb-1 truncate">
|
||||
{notification.title}
|
||||
</h4>
|
||||
<p className="text-xs text-gray-500 leading-relaxed line-clamp-2">
|
||||
{notification.content}
|
||||
</p>
|
||||
|
||||
{/* 特殊标签 */}
|
||||
{notification.tags && notification.tags.length > 0 && (
|
||||
<div className="flex gap-1.5 mt-2 flex-wrap">
|
||||
{notification.tags.map((tag, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="inline-flex items-center gap-1 px-2 py-0.5 bg-morandi-rose-100 text-morandi-rose-400 rounded-full text-[10px] font-medium"
|
||||
>
|
||||
<AlertCircle className="w-2.5 h-2.5" />
|
||||
{tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 展开的详情 */}
|
||||
<AnimatePresence>
|
||||
{expandedId === notification.id && (
|
||||
<motion.div
|
||||
initial={{ height: 0, opacity: 0 }}
|
||||
animate={{ height: "auto", opacity: 1 }}
|
||||
exit={{ height: 0, opacity: 0 }}
|
||||
className="overflow-hidden"
|
||||
>
|
||||
<div className="mt-3 pt-3 border-t border-gray-100 space-y-3">
|
||||
{/* 检查项目 */}
|
||||
{notification.checkupItems && notification.checkupItems.length > 0 && (
|
||||
<div>
|
||||
<h5 className="font-semibold text-gray-700 mb-2 text-xs">
|
||||
检查项目
|
||||
</h5>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{notification.checkupItems.map((item, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="text-xs text-gray-600 flex items-center gap-2 bg-gray-50 rounded-lg px-2.5 py-1.5"
|
||||
>
|
||||
<div className="w-1 h-1 bg-morandi-400 rounded-full flex-shrink-0"></div>
|
||||
{item}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 注意事项 */}
|
||||
{notification.checkupPreparations && notification.checkupPreparations.length > 0 && (
|
||||
<div className="bg-morandi-rose-50 rounded-xl p-3">
|
||||
<h5 className="font-semibold text-morandi-700 mb-2 text-xs flex items-center gap-1.5">
|
||||
<AlertCircle className="w-3.5 h-3.5" />
|
||||
注意事项
|
||||
</h5>
|
||||
<ul className="space-y-1">
|
||||
{notification.checkupPreparations.map((prep, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className="text-xs text-morandi-600 flex items-start gap-2"
|
||||
>
|
||||
<span className="w-1 h-1 bg-morandi-rose-400 rounded-full flex-shrink-0 mt-1.5"></span>
|
||||
<span>{prep}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</motion.div>
|
||||
|
||||
{/* 温馨提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.15 }}
|
||||
>
|
||||
<Card className="bg-morandi-50 border-morandi-100 rounded-2xl p-4">
|
||||
<div className="flex items-start gap-2.5">
|
||||
<Bell className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="font-medium text-gray-700 text-sm mb-1">消息说明</h4>
|
||||
<p className="text-xs text-gray-500 leading-relaxed">
|
||||
系统会根据您的孕周和产检计划自动推送提醒,包括产检时间、检查项目和注意事项。产检内容与产检日历同步。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
<div className="h-4" />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
413
frontend/src/app/pages/OnboardingPage.tsx
Normal file
413
frontend/src/app/pages/OnboardingPage.tsx
Normal file
@@ -0,0 +1,413 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import { ChevronUp, ChevronDown, Loader2 } from "lucide-react";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { useUser, calcPregnancyWeek, calcDueDate } from "../context/UserContext";
|
||||
import { submitOnboarding } from "../services/api";
|
||||
|
||||
type DateMode = "due_date" | "last_period";
|
||||
type MultiplePregnancy = "单胎" | "双胎" | "三胎+";
|
||||
type PregnancyCount = 1 | 2 | 3;
|
||||
|
||||
const MEDICAL_CONDITIONS = [
|
||||
"糖尿病 / 妊娠糖尿病史",
|
||||
"高血压 / 妊娠高血压史",
|
||||
"甲状腺疾病",
|
||||
];
|
||||
|
||||
export function OnboardingPage() {
|
||||
const navigate = useNavigate();
|
||||
const { updateUser } = useUser();
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
// 基本信息
|
||||
const [dateMode, setDateMode] = useState<DateMode>("due_date");
|
||||
const [dueDate, setDueDate] = useState("");
|
||||
const [lastPeriodDate, setLastPeriodDate] = useState("");
|
||||
|
||||
// 特殊情况
|
||||
const [showSpecial, setShowSpecial] = useState(false);
|
||||
const [age, setAge] = useState("");
|
||||
const [multiplePregnancy, setMultiplePregnancy] = useState<MultiplePregnancy>("单胎");
|
||||
const [medicalHistory, setMedicalHistory] = useState<string[]>([]);
|
||||
const [noMedicalHistory, setNoMedicalHistory] = useState(false);
|
||||
|
||||
// 补充信息
|
||||
const [showExtra, setShowExtra] = useState(false);
|
||||
const [preWeight, setPreWeight] = useState("");
|
||||
const [height, setHeight] = useState("");
|
||||
const [pregnancyCount, setPregnancyCount] = useState<PregnancyCount>(1);
|
||||
|
||||
// 计算孕周和预产期(用于显示)
|
||||
const computedInfo = (() => {
|
||||
if (dateMode === "last_period" && lastPeriodDate) {
|
||||
const { weeks, days } = calcPregnancyWeek(lastPeriodDate);
|
||||
const due = calcDueDate(lastPeriodDate);
|
||||
if (weeks >= 0 && weeks <= 42) {
|
||||
return { weeks, days, dueDate: due, valid: true };
|
||||
}
|
||||
}
|
||||
if (dateMode === "due_date" && dueDate) {
|
||||
// 从预产期反推末次月经:预产期 - 280天
|
||||
const dueDateObj = new Date(dueDate);
|
||||
const lmpDate = new Date(dueDateObj.getTime() - 280 * 24 * 60 * 60 * 1000);
|
||||
const lmpStr = lmpDate.toISOString().split("T")[0];
|
||||
const { weeks, days } = calcPregnancyWeek(lmpStr);
|
||||
if (weeks >= 0 && weeks <= 42) {
|
||||
return { weeks, days, dueDate, lmpDate: lmpStr, valid: true };
|
||||
}
|
||||
}
|
||||
return { weeks: 0, days: 0, dueDate: "", valid: false };
|
||||
})();
|
||||
|
||||
const canSubmit = dateMode === "due_date" ? !!dueDate : !!lastPeriodDate;
|
||||
|
||||
const toggleMedicalCondition = (condition: string) => {
|
||||
setNoMedicalHistory(false);
|
||||
setMedicalHistory((prev) =>
|
||||
prev.includes(condition) ? prev.filter((c) => c !== condition) : [...prev, condition]
|
||||
);
|
||||
};
|
||||
|
||||
const toggleNoMedicalHistory = () => {
|
||||
setNoMedicalHistory(!noMedicalHistory);
|
||||
if (!noMedicalHistory) {
|
||||
setMedicalHistory([]);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
setError("");
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
// 确定末次月经日期
|
||||
let lmpDate = lastPeriodDate;
|
||||
let dueDateStr = dueDate;
|
||||
if (dateMode === "due_date" && dueDate) {
|
||||
const dueDateObj = new Date(dueDate);
|
||||
lmpDate = new Date(dueDateObj.getTime() - 280 * 24 * 60 * 60 * 1000).toISOString().split("T")[0];
|
||||
dueDateStr = dueDate;
|
||||
} else if (dateMode === "last_period" && lastPeriodDate) {
|
||||
dueDateStr = calcDueDate(lastPeriodDate);
|
||||
lmpDate = lastPeriodDate;
|
||||
}
|
||||
|
||||
const { weeks, days } = calcPregnancyWeek(lmpDate);
|
||||
|
||||
const payload: Record<string, unknown> = {
|
||||
last_period_date: lmpDate,
|
||||
due_date: dueDateStr,
|
||||
pregnancy_week: weeks,
|
||||
pregnancy_day: days,
|
||||
multiple_pregnancy: multiplePregnancy,
|
||||
pregnancy_count: pregnancyCount,
|
||||
};
|
||||
|
||||
if (age) payload.age = parseInt(age);
|
||||
if (medicalHistory.length > 0) payload.medical_history = medicalHistory;
|
||||
if (preWeight) payload.pre_pregnancy_weight = parseFloat(preWeight);
|
||||
if (height) payload.height = parseFloat(height);
|
||||
|
||||
await submitOnboarding(payload as Parameters<typeof submitOnboarding>[0]);
|
||||
|
||||
updateUser({
|
||||
lastPeriodDate: lmpDate,
|
||||
dueDate: dueDateStr,
|
||||
currentWeek: weeks,
|
||||
currentDay: days,
|
||||
age: age ? parseInt(age) : null,
|
||||
prePregnancyWeight: preWeight ? parseFloat(preWeight) : null,
|
||||
height: height ? parseFloat(height) : null,
|
||||
medicalHistory,
|
||||
isOnboarded: true,
|
||||
});
|
||||
navigate("/home");
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : "保存失败,请重试";
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
<div className="px-4 pt-6 pb-32">
|
||||
{/* 页面标题 */}
|
||||
<h1 className="text-xl font-bold text-gray-800 mb-1">完善孕期信息</h1>
|
||||
<p className="text-sm text-gray-400 mb-5">帮助我们更准确地解读您的报告</p>
|
||||
|
||||
{/* 基本信息 */}
|
||||
<section className="mb-4 bg-white rounded-3xl shadow-sm p-5">
|
||||
<h2 className="text-base font-semibold text-gray-800 mb-4">
|
||||
基本信息 <span className="text-red-400">*</span>
|
||||
</h2>
|
||||
|
||||
{/* 日期方式切换 */}
|
||||
<p className="text-sm text-gray-500 mb-2">请选择一种方式</p>
|
||||
<div className="flex gap-3 mb-4">
|
||||
<button
|
||||
onClick={() => setDateMode("due_date")}
|
||||
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
|
||||
dateMode === "due_date"
|
||||
? "border-morandi-300 text-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 text-gray-500 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
我知道预产期
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setDateMode("last_period")}
|
||||
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
|
||||
dateMode === "last_period"
|
||||
? "border-morandi-300 text-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 text-gray-500 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
我知道末次月经
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 日期输入 */}
|
||||
{dateMode === "due_date" ? (
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">预产期</p>
|
||||
<Input
|
||||
type="date"
|
||||
value={dueDate}
|
||||
onChange={(e) => setDueDate(e.target.value)}
|
||||
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">末次月经日期</p>
|
||||
<Input
|
||||
type="date"
|
||||
value={lastPeriodDate}
|
||||
onChange={(e) => setLastPeriodDate(e.target.value)}
|
||||
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 孕周计算结果 */}
|
||||
{computedInfo.valid && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: -8 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="mt-3 p-3 bg-morandi-50 rounded-xl"
|
||||
>
|
||||
<p className="text-sm text-morandi-400">
|
||||
当前孕 <span className="font-semibold">{computedInfo.weeks}</span> 周{" "}
|
||||
<span className="font-semibold">{computedInfo.days}</span> 天
|
||||
{dateMode === "last_period" && computedInfo.dueDate && (
|
||||
<span className="ml-2">
|
||||
· 预产期 {new Date(computedInfo.dueDate).toLocaleDateString("zh-CN")}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* 特殊情况(选填) */}
|
||||
<section className="mb-4 bg-white rounded-3xl shadow-sm p-5">
|
||||
<button
|
||||
onClick={() => setShowSpecial(!showSpecial)}
|
||||
className={`flex items-center justify-between w-full ${showSpecial ? "mb-4" : ""}`}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800">特殊情况(选填)</h2>
|
||||
<span className="flex items-center text-xs text-gray-400">
|
||||
影响解读准确性
|
||||
{showSpecial ? (
|
||||
<ChevronUp className="w-4 h-4 ml-1" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 ml-1" />
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{showSpecial && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: "auto" }}
|
||||
className="space-y-5"
|
||||
>
|
||||
{/* 年龄 */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">年龄</p>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="请输入年龄"
|
||||
value={age}
|
||||
onChange={(e) => setAge(e.target.value)}
|
||||
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
|
||||
/>
|
||||
<p className="text-xs text-amber-500 mt-2 flex items-start">
|
||||
<span className="mr-1">💡</span>
|
||||
35岁以上属于高龄孕妇,某些指标的风险评估会不同
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 多胎妊娠 */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">是否多胎妊娠?</p>
|
||||
<div className="flex gap-3">
|
||||
{(["单胎", "双胎", "三胎+"] as MultiplePregnancy[]).map((opt) => (
|
||||
<button
|
||||
key={opt}
|
||||
onClick={() => setMultiplePregnancy(opt)}
|
||||
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
|
||||
multiplePregnancy === opt
|
||||
? "border-morandi-300 text-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 text-gray-500 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
{opt}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 疾病史 */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">是否有以下疾病史?(可多选)</p>
|
||||
<div className="space-y-2">
|
||||
{MEDICAL_CONDITIONS.map((condition) => (
|
||||
<button
|
||||
key={condition}
|
||||
onClick={() => toggleMedicalCondition(condition)}
|
||||
className={`w-full h-12 px-4 rounded-xl border-2 text-left text-sm font-medium transition-all ${
|
||||
medicalHistory.includes(condition)
|
||||
? "border-morandi-300 text-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 text-gray-600 hover:border-gray-300 bg-white"
|
||||
}`}
|
||||
>
|
||||
{condition}
|
||||
</button>
|
||||
))}
|
||||
<button
|
||||
onClick={toggleNoMedicalHistory}
|
||||
className={`w-full h-12 px-4 rounded-xl border-2 text-left text-sm font-medium transition-all ${
|
||||
noMedicalHistory
|
||||
? "border-morandi-300 text-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 text-gray-600 hover:border-gray-300 bg-white"
|
||||
}`}
|
||||
>
|
||||
以上都没有 ✓
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* 补充信息(选填) */}
|
||||
<section className="mb-4 bg-white rounded-3xl shadow-sm p-5">
|
||||
<button
|
||||
onClick={() => setShowExtra(!showExtra)}
|
||||
className={`flex items-center justify-between w-full ${showExtra ? "mb-4" : ""}`}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800">补充信息(选填)</h2>
|
||||
<span className="flex items-center text-xs text-gray-400">
|
||||
用于BMI计算
|
||||
{showExtra ? (
|
||||
<ChevronUp className="w-4 h-4 ml-1" />
|
||||
) : (
|
||||
<ChevronDown className="w-4 h-4 ml-1" />
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{showExtra && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, height: 0 }}
|
||||
animate={{ opacity: 1, height: "auto" }}
|
||||
className="space-y-5"
|
||||
>
|
||||
{/* 孕前体重 */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">孕前体重 (kg)</p>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="请输入"
|
||||
value={preWeight}
|
||||
onChange={(e) => setPreWeight(e.target.value)}
|
||||
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 身高 */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">身高 (cm)</p>
|
||||
<Input
|
||||
type="number"
|
||||
placeholder="请输入"
|
||||
value={height}
|
||||
onChange={(e) => setHeight(e.target.value)}
|
||||
className="h-12 rounded-xl border-2 border-gray-200 focus:border-morandi-200 bg-white"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* 第几次怀孕 */}
|
||||
<div>
|
||||
<p className="text-sm text-gray-600 mb-2">第几次怀孕</p>
|
||||
<div className="flex gap-3">
|
||||
{([1, 2, 3] as PregnancyCount[]).map((count) => (
|
||||
<button
|
||||
key={count}
|
||||
onClick={() => setPregnancyCount(count)}
|
||||
className={`flex-1 h-11 rounded-full border-2 text-sm font-medium transition-all ${
|
||||
pregnancyCount === count
|
||||
? "border-morandi-300 text-morandi-500 bg-morandi-50"
|
||||
: "border-gray-200 text-gray-500 hover:border-gray-300"
|
||||
}`}
|
||||
>
|
||||
{count === 3 ? "第3次+" : `第${count}次`}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
|
||||
{/* 错误提示 */}
|
||||
{error && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="fixed bottom-24 left-4 right-4 mx-auto"
|
||||
>
|
||||
<p className="text-sm text-red-500 bg-red-50 px-4 py-3 rounded-xl text-center">
|
||||
{error}
|
||||
</p>
|
||||
</motion.div>
|
||||
)}
|
||||
|
||||
{/* 底部按钮 */}
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-white/80 backdrop-blur-sm border-t border-gray-100 px-4 py-4 pb-safe z-10">
|
||||
<div className="max-w-md mx-auto">
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit || isSubmitting}
|
||||
className="w-full h-12 rounded-full bg-gradient-to-r from-morandi-400 to-morandi-500 text-white font-semibold text-base shadow-lg disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
|
||||
>
|
||||
{isSubmitting ? (
|
||||
<>
|
||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
||||
保存中...
|
||||
</>
|
||||
) : (
|
||||
"完成建档"
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
473
frontend/src/app/pages/ProfilePage.tsx
Normal file
473
frontend/src/app/pages/ProfilePage.tsx
Normal file
@@ -0,0 +1,473 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
User,
|
||||
Calendar,
|
||||
Heart,
|
||||
Phone,
|
||||
Mail,
|
||||
MapPin,
|
||||
Edit2,
|
||||
Check,
|
||||
X,
|
||||
Camera,
|
||||
Baby,
|
||||
Activity,
|
||||
AlertCircle,
|
||||
Shield,
|
||||
Bell,
|
||||
LogOut,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { useUser, getPregnancyStage } from "../context/UserContext";
|
||||
|
||||
interface UserInfo {
|
||||
name: string;
|
||||
age: number;
|
||||
phone: string;
|
||||
email: string;
|
||||
address: string;
|
||||
lastPeriod: string;
|
||||
dueDate: string;
|
||||
currentWeek: number;
|
||||
currentDay: number;
|
||||
height: number;
|
||||
prePregnancyWeight: number;
|
||||
currentWeight: number;
|
||||
bloodType: string;
|
||||
allergies: string[];
|
||||
medicalHistory: string[];
|
||||
emergencyContact: {
|
||||
name: string;
|
||||
relation: string;
|
||||
phone: string;
|
||||
};
|
||||
}
|
||||
|
||||
export function ProfilePage() {
|
||||
const navigate = useNavigate();
|
||||
const { user, updateUserRemote, logout } = useUser();
|
||||
const [isEditing, setIsEditing] = useState<string | null>(null);
|
||||
const [userInfo, setUserInfo] = useState<UserInfo>({
|
||||
name: user.name || "未设置",
|
||||
age: user.age || 0,
|
||||
phone: user.phone || "未设置",
|
||||
email: "",
|
||||
address: "",
|
||||
lastPeriod: user.lastPeriodDate || "",
|
||||
dueDate: user.dueDate || "",
|
||||
currentWeek: user.currentWeek,
|
||||
currentDay: user.currentDay,
|
||||
height: user.height || 0,
|
||||
prePregnancyWeight: user.prePregnancyWeight || 0,
|
||||
currentWeight: user.currentWeight || 0,
|
||||
bloodType: user.bloodType || "未设置",
|
||||
allergies: user.allergies.length ? user.allergies : ["无"],
|
||||
medicalHistory: user.medicalHistory.length ? user.medicalHistory : ["无重大病史"],
|
||||
emergencyContact: {
|
||||
name: user.emergencyContact.name || "未设置",
|
||||
relation: user.emergencyContact.relation || "",
|
||||
phone: user.emergencyContact.phone || "",
|
||||
},
|
||||
});
|
||||
|
||||
const [editValues, setEditValues] = useState<Partial<UserInfo>>({});
|
||||
|
||||
const handleEdit = (field: string) => {
|
||||
setIsEditing(field);
|
||||
setEditValues({ [field]: (userInfo as any)[field] });
|
||||
};
|
||||
|
||||
const handleSave = (field: string) => {
|
||||
const updated = { ...userInfo, ...(editValues as any) };
|
||||
setUserInfo(updated);
|
||||
setIsEditing(null);
|
||||
setEditValues({});
|
||||
// Sync back to global context + backend
|
||||
updateUserRemote({
|
||||
name: updated.name,
|
||||
age: updated.age,
|
||||
phone: updated.phone,
|
||||
lastPeriodDate: updated.lastPeriod,
|
||||
height: updated.height,
|
||||
prePregnancyWeight: updated.prePregnancyWeight,
|
||||
currentWeight: updated.currentWeight,
|
||||
bloodType: updated.bloodType,
|
||||
allergies: updated.allergies,
|
||||
medicalHistory: updated.medicalHistory,
|
||||
emergencyContact: updated.emergencyContact,
|
||||
});
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
setIsEditing(null);
|
||||
setEditValues({});
|
||||
};
|
||||
|
||||
const calculateBMI = () => {
|
||||
const heightInMeters = userInfo.height / 100;
|
||||
const bmi = userInfo.currentWeight / (heightInMeters * heightInMeters);
|
||||
return bmi.toFixed(1);
|
||||
};
|
||||
|
||||
const calculateWeightGain = () => {
|
||||
return (userInfo.currentWeight - userInfo.prePregnancyWeight).toFixed(1);
|
||||
};
|
||||
|
||||
const InfoItem = ({
|
||||
label,
|
||||
value,
|
||||
field,
|
||||
editable = true,
|
||||
type = "text",
|
||||
icon: Icon,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | number;
|
||||
field: string;
|
||||
editable?: boolean;
|
||||
type?: string;
|
||||
icon?: any;
|
||||
}) => (
|
||||
<div className="flex items-center justify-between py-3 border-b border-gray-100 last:border-0">
|
||||
<div className="flex items-center gap-3">
|
||||
{Icon && (
|
||||
<div className="w-8 h-8 bg-morandi-100 rounded-lg flex items-center justify-center">
|
||||
<Icon className="w-4 h-4 text-morandi-500" />
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">{label}</div>
|
||||
{isEditing === field ? (
|
||||
<input
|
||||
type={type}
|
||||
value={(editValues as any)[field] ?? value}
|
||||
onChange={(e) =>
|
||||
setEditValues({ ...editValues, [field]: e.target.value })
|
||||
}
|
||||
className="mt-1 px-2 py-1 border border-morandi-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-morandi-500"
|
||||
autoFocus
|
||||
/>
|
||||
) : (
|
||||
<div className="font-semibold text-gray-800">{value}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{editable && (
|
||||
<div className="flex items-center gap-2">
|
||||
{isEditing === field ? (
|
||||
<>
|
||||
<button
|
||||
onClick={() => handleSave(field)}
|
||||
className="w-8 h-8 bg-morandi-sage-100 rounded-full flex items-center justify-center hover:bg-morandi-sage-200"
|
||||
>
|
||||
<Check className="w-4 h-4 text-morandi-sage-500" />
|
||||
</button>
|
||||
<button
|
||||
onClick={handleCancel}
|
||||
className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center hover:bg-gray-200"
|
||||
>
|
||||
<X className="w-4 h-4 text-gray-600" />
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleEdit(field)}
|
||||
className="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center hover:bg-gray-200"
|
||||
>
|
||||
<Edit2 className="w-4 h-4 text-gray-600" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">个人中心</h1>
|
||||
<p className="text-xs text-gray-500">管理您的个人信息</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 个人头像卡片 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-gradient-to-br from-morandi-400 to-morandi-500 border-0 text-white p-6 rounded-3xl shadow-sm">
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="relative">
|
||||
<div className="w-20 h-20 bg-white/20 backdrop-blur-sm rounded-full flex items-center justify-center">
|
||||
<User className="w-10 h-10 text-white" />
|
||||
</div>
|
||||
<button className="absolute bottom-0 right-0 w-6 h-6 bg-white rounded-full flex items-center justify-center shadow-sm">
|
||||
<Camera className="w-3 h-3 text-morandi-500" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h2 className="text-2xl font-semibold mb-1">{userInfo.name}</h2>
|
||||
<p className="text-white/90 text-sm">
|
||||
{userInfo.age}岁 · {userInfo.bloodType}
|
||||
</p>
|
||||
<p className="text-white/80 text-sm mt-1">
|
||||
孕{userInfo.currentWeek}周+{userInfo.currentDay}天
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 孕期信息 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
|
||||
<Baby className="w-5 h-5 text-morandi-500" />
|
||||
孕期信息
|
||||
</h2>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<InfoItem
|
||||
label="末次月经"
|
||||
value={userInfo.lastPeriod}
|
||||
field="lastPeriod"
|
||||
type="date"
|
||||
icon={Calendar}
|
||||
/>
|
||||
<InfoItem
|
||||
label="预产期"
|
||||
value={userInfo.dueDate}
|
||||
field="dueDate"
|
||||
type="date"
|
||||
icon={Heart}
|
||||
/>
|
||||
<div className="flex items-center justify-between py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-morandi-100 rounded-lg flex items-center justify-center">
|
||||
<Activity className="w-4 h-4 text-morandi-500" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">当前孕周</div>
|
||||
<div className="font-semibold text-gray-800">
|
||||
{userInfo.currentWeek}周+{userInfo.currentDay}天
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100">
|
||||
{getPregnancyStage(userInfo.currentWeek)}
|
||||
</Badge>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 健康数据 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
|
||||
<Activity className="w-5 h-5 text-morandi-slate-500" />
|
||||
健康数据
|
||||
</h2>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<InfoItem
|
||||
label="身高"
|
||||
value={`${userInfo.height} cm`}
|
||||
field="height"
|
||||
type="number"
|
||||
/>
|
||||
<InfoItem
|
||||
label="孕前体重"
|
||||
value={`${userInfo.prePregnancyWeight} kg`}
|
||||
field="prePregnancyWeight"
|
||||
type="number"
|
||||
/>
|
||||
<InfoItem
|
||||
label="当前体重"
|
||||
value={`${userInfo.currentWeight} kg`}
|
||||
field="currentWeight"
|
||||
type="number"
|
||||
/>
|
||||
<div className="grid grid-cols-2 gap-4 mt-4 pt-4 border-t border-gray-100">
|
||||
<div className="bg-morandi-slate-50 rounded-xl p-3">
|
||||
<div className="text-xs text-morandi-slate-500 mb-1">当前BMI</div>
|
||||
<div className="text-2xl font-semibold text-morandi-500">
|
||||
{calculateBMI()}
|
||||
</div>
|
||||
<div className="text-xs text-morandi-slate-500 mt-1">正常范围</div>
|
||||
</div>
|
||||
<div className="bg-morandi-sage-100 rounded-xl p-3">
|
||||
<div className="text-xs text-morandi-sage-500 mb-1">体重增长</div>
|
||||
<div className="text-2xl font-semibold text-morandi-sage-600">
|
||||
+{calculateWeightGain()} kg
|
||||
</div>
|
||||
<div className="text-xs text-morandi-sage-500 mt-1">符合预期</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 联系方式 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.3 }}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
|
||||
<Phone className="w-5 h-5 text-morandi-600" />
|
||||
联系方式
|
||||
</h2>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<InfoItem
|
||||
label="手机号"
|
||||
value={userInfo.phone}
|
||||
field="phone"
|
||||
icon={Phone}
|
||||
/>
|
||||
<InfoItem
|
||||
label="邮箱"
|
||||
value={userInfo.email}
|
||||
field="email"
|
||||
icon={Mail}
|
||||
/>
|
||||
<InfoItem
|
||||
label="居住地"
|
||||
value={userInfo.address}
|
||||
field="address"
|
||||
icon={MapPin}
|
||||
/>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 医疗信息 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.4 }}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
|
||||
<AlertCircle className="w-5 h-5 text-red-600" />
|
||||
医疗信息
|
||||
</h2>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<div className="text-sm text-gray-500 mb-2">血型</div>
|
||||
<Badge className="bg-red-100 text-red-700 hover:bg-red-100">
|
||||
{userInfo.bloodType}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500 mb-2">药物过敏史</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{userInfo.allergies.map((allergy, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
className="bg-morandi-rose-100 text-morandi-rose-400 hover:bg-morandi-rose-100"
|
||||
>
|
||||
{allergy}
|
||||
</Badge>
|
||||
))}
|
||||
<button className="px-3 py-1 border border-dashed border-gray-300 rounded-full text-sm text-gray-500 hover:border-morandi-200 hover:text-morandi-500">
|
||||
+ 添加
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500 mb-2">既往病史</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{userInfo.medicalHistory.map((history, index) => (
|
||||
<Badge
|
||||
key={index}
|
||||
className="bg-morandi-50 text-morandi-500 hover:bg-morandi-50"
|
||||
>
|
||||
{history}
|
||||
</Badge>
|
||||
))}
|
||||
<button className="px-3 py-1 border border-dashed border-gray-300 rounded-full text-sm text-gray-500 hover:border-morandi-200 hover:text-morandi-500">
|
||||
+ 添加
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 紧急联系人 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.5 }}
|
||||
>
|
||||
<h2 className="text-base font-semibold text-gray-800 mb-3 flex items-center gap-2">
|
||||
<Shield className="w-5 h-5 text-morandi-sage-500" />
|
||||
紧急联系人
|
||||
</h2>
|
||||
<Card className="bg-white rounded-2xl p-5 shadow-sm border-0">
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">姓名</div>
|
||||
<div className="font-semibold text-gray-800">
|
||||
{userInfo.emergencyContact.name}
|
||||
</div>
|
||||
</div>
|
||||
<Badge className="bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100">
|
||||
{userInfo.emergencyContact.relation}
|
||||
</Badge>
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-sm text-gray-500">联系电话</div>
|
||||
<div className="font-semibold text-gray-800">
|
||||
{userInfo.emergencyContact.phone}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 退出登录 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.7 }}
|
||||
>
|
||||
<Button
|
||||
onClick={() => {
|
||||
logout();
|
||||
navigate("/");
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full border-red-200 text-red-600 hover:bg-red-50 hover:text-red-700 hover:border-red-300 rounded-2xl py-6"
|
||||
>
|
||||
<LogOut className="w-5 h-5 mr-2" />
|
||||
退出登录
|
||||
</Button>
|
||||
</motion.div>
|
||||
|
||||
<div className="h-8"></div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
276
frontend/src/app/pages/ReportDetailPage.tsx
Normal file
276
frontend/src/app/pages/ReportDetailPage.tsx
Normal file
@@ -0,0 +1,276 @@
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { useState, useEffect } from "react";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Calendar,
|
||||
FileText,
|
||||
Download,
|
||||
CheckCircle2,
|
||||
X,
|
||||
Heart,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { getReport, type ReportResponse } from "../services/api";
|
||||
|
||||
export function ReportDetailPage() {
|
||||
const navigate = useNavigate();
|
||||
const { reportId } = useParams();
|
||||
const [showDownloadSheet, setShowDownloadSheet] = useState(false);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [downloadDone, setDownloadDone] = useState(false);
|
||||
const [report, setReport] = useState<ReportResponse | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!reportId) return;
|
||||
getReport(reportId)
|
||||
.then(setReport)
|
||||
.catch(() => {})
|
||||
.finally(() => setLoading(false));
|
||||
}, [reportId]);
|
||||
|
||||
const handleDownload = async () => {
|
||||
if (!report?.image_urls || report.image_urls.length === 0) return;
|
||||
|
||||
setIsDownloading(true);
|
||||
|
||||
try {
|
||||
// 下载所有报告图片
|
||||
for (let i = 0; i < report.image_urls.length; i++) {
|
||||
const imageUrl = report.image_urls[i];
|
||||
|
||||
// 获取图片数据
|
||||
const response = await fetch(imageUrl);
|
||||
const blob = await response.blob();
|
||||
|
||||
// 创建下载链接
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `${report.report_type || '报告'}_${report.created_at?.slice(0, 10) || ''}_${i + 1}.jpg`;
|
||||
|
||||
// 触发下载
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
// 释放 URL 对象
|
||||
window.URL.revokeObjectURL(url);
|
||||
|
||||
// 多张图片时添加延迟,避免浏览器阻止
|
||||
if (i < report.image_urls.length - 1) {
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
}
|
||||
}
|
||||
|
||||
setIsDownloading(false);
|
||||
setDownloadDone(true);
|
||||
setTimeout(() => {
|
||||
setDownloadDone(false);
|
||||
setShowDownloadSheet(false);
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error('下载失败:', error);
|
||||
setIsDownloading(false);
|
||||
alert('下载失败,请稍后重试');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-20">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="flex items-center text-gray-600 hover:text-gray-900"
|
||||
>
|
||||
<ChevronLeft className="w-5 h-5 mr-1" />
|
||||
返回
|
||||
</button>
|
||||
<h1 className="font-semibold text-gray-800">原始报告</h1>
|
||||
<div className="w-5" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{loading ? (
|
||||
<div className="flex items-center justify-center py-20">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
|
||||
</div>
|
||||
) : !report ? (
|
||||
<div className="text-center py-20 text-gray-400">报告不存在</div>
|
||||
) : (
|
||||
<>
|
||||
{/* 报告信息 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-white rounded-3xl shadow-sm p-6">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="w-12 h-12 bg-morandi-100 rounded-2xl flex items-center justify-center">
|
||||
<FileText className="w-6 h-6 text-morandi-400" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<h2 className="font-semibold text-gray-800 mb-1">
|
||||
{report.report_type || "检查报告"}
|
||||
</h2>
|
||||
<div className="flex items-center gap-3 text-sm text-gray-600">
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="w-4 h-4" />
|
||||
<span>{report.created_at?.slice(0, 10)}</span>
|
||||
</div>
|
||||
{report.pregnancy_week && (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span>孕 {report.pregnancy_week}周</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 报告图片 */}
|
||||
{report.image_urls.map((url, idx) => (
|
||||
<motion.div
|
||||
key={idx}
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 * (idx + 1) }}
|
||||
>
|
||||
<Card className="bg-white rounded-3xl shadow-sm overflow-hidden">
|
||||
<div className="relative">
|
||||
<img
|
||||
src={url}
|
||||
alt={`报告图片 ${idx + 1}`}
|
||||
className="w-full"
|
||||
style={{ pointerEvents: 'auto' }}
|
||||
/>
|
||||
{/* 长按保存提示 */}
|
||||
<div className="absolute top-3 left-3 bg-morandi-400/90 backdrop-blur-sm rounded-lg px-3 py-1.5 flex items-center gap-1.5 pointer-events-none">
|
||||
<Download className="w-3 h-3 text-white" />
|
||||
<span className="text-xs text-white font-medium">长按图片保存到相册</span>
|
||||
</div>
|
||||
{/* 平台水印 */}
|
||||
<div className="absolute bottom-3 right-3 bg-white/60 backdrop-blur-sm rounded-lg px-2.5 py-1 flex items-center gap-1.5 pointer-events-none">
|
||||
<Heart className="w-3 h-3 text-morandi-400 fill-morandi-400" />
|
||||
<span className="text-xs text-morandi-500 font-medium">孕育无忧</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
|
||||
{/* 提示信息 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
>
|
||||
<Card className="bg-morandi-50 border border-morandi-200 rounded-2xl p-4">
|
||||
<div className="flex items-start gap-2">
|
||||
<Download className="w-4 h-4 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div className="text-xs text-gray-600">
|
||||
<p className="font-medium text-morandi-600 mb-1">保存到相册</p>
|
||||
<p>长按图片 → 选择"保存图片" → 图片将保存到手机相册</p>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 下载弹窗 */}
|
||||
<AnimatePresence>
|
||||
{showDownloadSheet && (
|
||||
<>
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
onClick={() => setShowDownloadSheet(false)}
|
||||
className="fixed inset-0 bg-black/40 z-40"
|
||||
/>
|
||||
<motion.div
|
||||
initial={{ y: "100%" }}
|
||||
animate={{ y: 0 }}
|
||||
exit={{ y: "100%" }}
|
||||
transition={{ type: "spring", damping: 25, stiffness: 300 }}
|
||||
className="fixed bottom-0 left-0 right-0 bg-white rounded-t-3xl z-50"
|
||||
>
|
||||
<div className="mx-auto p-5">
|
||||
<div className="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4" />
|
||||
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<h3 className="font-semibold text-gray-800 text-lg">下载报告</h3>
|
||||
<button
|
||||
onClick={() => setShowDownloadSheet(false)}
|
||||
className="w-8 h-8 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<X className="w-5 h-5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* 下载预览 */}
|
||||
<Card className="bg-morandi-50 border-morandi-100 rounded-2xl p-4 mb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-12 h-12 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-xl flex items-center justify-center flex-shrink-0">
|
||||
<FileText className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h4 className="font-medium text-gray-800 text-sm">{report?.report_type || "检查报告"}</h4>
|
||||
<p className="text-xs text-gray-500 mt-0.5">{report?.created_at?.slice(0, 10)}{report?.pregnancy_week ? ` · 孕${report.pregnancy_week}周` : ""}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-1 bg-white rounded-lg px-2 py-1">
|
||||
<Heart className="w-3 h-3 text-morandi-400 fill-morandi-400" />
|
||||
<span className="text-xs text-morandi-500 font-medium">孕育无忧</span>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<p className="text-xs text-gray-400 mb-4">
|
||||
💡 移动端保存方法:长按图片选择"保存图片"即可保存到相册
|
||||
</p>
|
||||
|
||||
{/* 下载按钮 */}
|
||||
<Button
|
||||
onClick={handleDownload}
|
||||
disabled={isDownloading}
|
||||
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white mb-3"
|
||||
>
|
||||
{isDownloading ? (
|
||||
<>
|
||||
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin mr-2" />
|
||||
下载中...
|
||||
</>
|
||||
) : downloadDone ? (
|
||||
<>
|
||||
<CheckCircle2 className="w-4 h-4 mr-2" />
|
||||
已下载
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Download className="w-4 h-4 mr-2" />
|
||||
下载到本地(电脑端)
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-center text-gray-400">
|
||||
或直接长按上方图片保存
|
||||
</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
</>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
574
frontend/src/app/pages/SharePage.tsx
Normal file
574
frontend/src/app/pages/SharePage.tsx
Normal file
@@ -0,0 +1,574 @@
|
||||
import { useState, useEffect, useRef, useCallback } from "react";
|
||||
import { useNavigate, useParams } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Share2,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
Info,
|
||||
Loader2,
|
||||
Heart,
|
||||
Baby,
|
||||
TrendingUp,
|
||||
Download,
|
||||
Check,
|
||||
Image as ImageIcon,
|
||||
} from "lucide-react";
|
||||
import { toPng } from "html-to-image";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { generateShareData } from "../services/api";
|
||||
|
||||
type SaveStatus = "idle" | "generating" | "success" | "error";
|
||||
|
||||
export function SharePage() {
|
||||
const navigate = useNavigate();
|
||||
const { reportId } = useParams();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [shareData, setShareData] = useState<any>(null);
|
||||
const [saveStatus, setSaveStatus] = useState<SaveStatus>("idle");
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(null);
|
||||
const cardRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!reportId) return;
|
||||
generateShareData(reportId)
|
||||
.then((data) => {
|
||||
setShareData(data.share_data);
|
||||
})
|
||||
.catch(() => {/* keep null */})
|
||||
.finally(() => setLoading(false));
|
||||
}, [reportId]);
|
||||
|
||||
// 生成长图
|
||||
const generateImage = useCallback(async (): Promise<string | null> => {
|
||||
if (!cardRef.current) return null;
|
||||
|
||||
try {
|
||||
// html-to-image: 将 DOM 节点转为 PNG data URL
|
||||
const dataUrl = await toPng(cardRef.current, {
|
||||
cacheBust: true,
|
||||
pixelRatio: 2, // 2x 高清
|
||||
backgroundColor: "#ffffff",
|
||||
style: {
|
||||
// 确保截图时移除圆角阴影的裁切问题
|
||||
borderRadius: "0",
|
||||
},
|
||||
});
|
||||
return dataUrl;
|
||||
} catch (err) {
|
||||
console.error("生成图片失败:", err);
|
||||
return null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 一键保存到相册 / 下载
|
||||
const handleSaveImage = useCallback(async () => {
|
||||
setSaveStatus("generating");
|
||||
|
||||
try {
|
||||
const dataUrl = imageUrl || (await generateImage());
|
||||
if (!dataUrl) {
|
||||
setSaveStatus("error");
|
||||
setTimeout(() => setSaveStatus("idle"), 2000);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!imageUrl) setImageUrl(dataUrl);
|
||||
|
||||
// 尝试使用 Web Share API(移动端可直接分享/保存到相册)
|
||||
if (navigator.share && navigator.canShare) {
|
||||
try {
|
||||
const response = await fetch(dataUrl);
|
||||
const blob = await response.blob();
|
||||
const file = new File([blob], `孕育无忧-报告解读-${reportId}.png`, {
|
||||
type: "image/png",
|
||||
});
|
||||
|
||||
if (navigator.canShare({ files: [file] })) {
|
||||
await navigator.share({
|
||||
files: [file],
|
||||
title: "孕育无忧 · AI 报告解读",
|
||||
});
|
||||
setSaveStatus("success");
|
||||
setTimeout(() => setSaveStatus("idle"), 3000);
|
||||
return;
|
||||
}
|
||||
} catch (shareErr) {
|
||||
// 用户取消分享或不支持,降级到下载
|
||||
if ((shareErr as Error).name === "AbortError") {
|
||||
setSaveStatus("idle");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 降级方案:触发下载(iOS Safari / Android 浏览器)
|
||||
const link = document.createElement("a");
|
||||
link.download = `孕育无忧-报告解读-${reportId}.png`;
|
||||
link.href = dataUrl;
|
||||
link.style.display = "none";
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
||||
setSaveStatus("success");
|
||||
setTimeout(() => setSaveStatus("idle"), 3000);
|
||||
} catch (err) {
|
||||
console.error("保存失败:", err);
|
||||
setSaveStatus("error");
|
||||
setTimeout(() => setSaveStatus("idle"), 2000);
|
||||
}
|
||||
}, [imageUrl, generateImage, reportId]);
|
||||
|
||||
// 预览:在页面加载数据后自动生成图片预览
|
||||
useEffect(() => {
|
||||
if (shareData && cardRef.current && !imageUrl) {
|
||||
// 延迟一帧确保 DOM 渲染完毕
|
||||
const timer = setTimeout(async () => {
|
||||
const url = await generateImage();
|
||||
if (url) setImageUrl(url);
|
||||
}, 500);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [shareData, generateImage, imageUrl]);
|
||||
|
||||
if (loading || !shareData) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin mx-auto mb-3" />
|
||||
<p className="text-sm text-gray-500">正在准备分享内容...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const getStatusColor = (status: string) => {
|
||||
switch (status) {
|
||||
case "normal":
|
||||
return {
|
||||
bg: "bg-morandi-sage-100",
|
||||
text: "text-morandi-sage-600",
|
||||
icon: "text-morandi-sage-400",
|
||||
};
|
||||
case "attention":
|
||||
return {
|
||||
bg: "bg-morandi-rose-100",
|
||||
text: "text-morandi-600",
|
||||
icon: "text-morandi-rose-400",
|
||||
};
|
||||
default:
|
||||
return {
|
||||
bg: "bg-gray-100",
|
||||
text: "text-gray-600",
|
||||
icon: "text-gray-400",
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const statusColors = getStatusColor(shareData.overall_status);
|
||||
|
||||
const getSaveButtonContent = () => {
|
||||
switch (saveStatus) {
|
||||
case "generating":
|
||||
return (
|
||||
<>
|
||||
<Loader2 className="w-5 h-5 animate-spin" />
|
||||
<span>正在生成图片...</span>
|
||||
</>
|
||||
);
|
||||
case "success":
|
||||
return (
|
||||
<>
|
||||
<Check className="w-5 h-5" />
|
||||
<span>已保存到相册</span>
|
||||
</>
|
||||
);
|
||||
case "error":
|
||||
return (
|
||||
<>
|
||||
<AlertCircle className="w-5 h-5" />
|
||||
<span>保存失败,请重试</span>
|
||||
</>
|
||||
);
|
||||
default:
|
||||
return (
|
||||
<>
|
||||
<Download className="w-5 h-5" />
|
||||
<span>保存图片到相册</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 pb-28">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-morandi-400 rounded-full flex items-center justify-center">
|
||||
<Share2 className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">分享长图</h1>
|
||||
<p className="text-xs text-gray-500">生成精美报告长图</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-5">
|
||||
{/* 图片预览区域 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
{/* 如果已经生成了图片,直接展示图片(可长按保存) */}
|
||||
{imageUrl ? (
|
||||
<div className="relative">
|
||||
<img
|
||||
src={imageUrl}
|
||||
alt="分享长图"
|
||||
className="w-full rounded-3xl shadow-lg"
|
||||
style={{ userSelect: "none" }}
|
||||
/>
|
||||
{/* 长按提示覆盖层 */}
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/30 to-transparent rounded-b-3xl px-4 py-3">
|
||||
<p className="text-white text-xs text-center opacity-80">
|
||||
💡 长按图片也可直接保存
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-center py-16 bg-white rounded-3xl shadow-lg">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin mx-auto mb-3" />
|
||||
<p className="text-sm text-gray-500">正在生成长图预览...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
|
||||
{/* 隐藏的 HTML 卡片(用于截图,不展示给用户) */}
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
left: "-9999px",
|
||||
top: 0,
|
||||
width: "375px", // 固定 iPhone 宽度,保证截图一致
|
||||
}}
|
||||
>
|
||||
<div ref={cardRef} style={{ background: "#ffffff", padding: "0" }}>
|
||||
<ShareCardContent shareData={shareData} getStatusColor={getStatusColor} statusColors={statusColors} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 操作提示 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<Card className="bg-morandi-50 border-morandi-200 rounded-2xl p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<Info className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<h4 className="font-semibold text-gray-800 text-sm mb-2">💡 分享说明</h4>
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-xs text-gray-600 leading-relaxed">
|
||||
• 点击下方按钮,一键保存图片到手机相册
|
||||
</p>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">
|
||||
• 也可以长按上方图片直接保存
|
||||
</p>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">
|
||||
• 个人信息已自动脱敏处理,保护您的隐私
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
</div>
|
||||
|
||||
{/* 底部固定操作栏 */}
|
||||
<div className="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4 pb-safe z-10">
|
||||
<div className="max-w-md mx-auto">
|
||||
<Button
|
||||
onClick={handleSaveImage}
|
||||
disabled={saveStatus === "generating"}
|
||||
className={`w-full h-14 rounded-2xl text-base font-semibold flex items-center justify-center gap-2 transition-all ${
|
||||
saveStatus === "success"
|
||||
? "bg-morandi-sage-400 hover:bg-morandi-sage-500 text-white"
|
||||
: saveStatus === "error"
|
||||
? "bg-red-400 hover:bg-red-500 text-white"
|
||||
: "bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-600 text-white shadow-lg shadow-morandi-300/30"
|
||||
}`}
|
||||
>
|
||||
{getSaveButtonContent()}
|
||||
</Button>
|
||||
<p className="text-center text-xs text-gray-400 mt-2">
|
||||
图片将保存到您的手机相册中
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 分享卡片内容组件(纯 HTML/CSS,不使用 motion 动画,用于截图)
|
||||
* 独立提取,确保截图时样式完整、无动画干扰
|
||||
*/
|
||||
function ShareCardContent({
|
||||
shareData,
|
||||
getStatusColor,
|
||||
statusColors,
|
||||
}: {
|
||||
shareData: any;
|
||||
getStatusColor: (status: string) => { bg: string; text: string; icon: string };
|
||||
statusColors: { bg: string; text: string; icon: string };
|
||||
}) {
|
||||
return (
|
||||
<div style={{ background: "#ffffff", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif" }}>
|
||||
<div style={{ padding: "24px", display: "flex", flexDirection: "column", gap: "20px" }}>
|
||||
{/* 标题区 */}
|
||||
<div style={{ textAlign: "center", paddingBottom: "20px", borderBottom: "2px solid #f3f4f6" }}>
|
||||
<div
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "8px",
|
||||
padding: "8px 16px",
|
||||
background: "linear-gradient(135deg, #b8a9c9, #9d8ab5)",
|
||||
color: "white",
|
||||
borderRadius: "9999px",
|
||||
fontSize: "14px",
|
||||
fontWeight: 600,
|
||||
marginBottom: "16px",
|
||||
}}
|
||||
>
|
||||
<Heart style={{ width: 16, height: 16, fill: "white", color: "white" }} />
|
||||
<span>孕育无忧 · AI 智能解读</span>
|
||||
</div>
|
||||
<h2
|
||||
style={{
|
||||
fontSize: "24px",
|
||||
fontWeight: 700,
|
||||
color: "#1f2937",
|
||||
marginBottom: "8px",
|
||||
marginTop: "0",
|
||||
}}
|
||||
>
|
||||
{shareData.report_type}
|
||||
</h2>
|
||||
<div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: "12px", fontSize: "14px", color: "#6b7280" }}>
|
||||
{shareData.pregnancy_week && <span>孕 {shareData.pregnancy_week} 周</span>}
|
||||
{shareData.user_name && (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span>{shareData.user_name}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 整体评估 */}
|
||||
<div className={`${statusColors.bg} rounded-2xl p-5`}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "12px", marginBottom: "12px" }}>
|
||||
<div
|
||||
style={{
|
||||
width: 48,
|
||||
height: 48,
|
||||
background: "rgba(255,255,255,0.5)",
|
||||
borderRadius: "12px",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
>
|
||||
<Baby className={`w-6 h-6 ${statusColors.icon}`} />
|
||||
</div>
|
||||
<div style={{ flex: 1 }}>
|
||||
<h3 style={{ fontWeight: 700, color: "#1f2937", fontSize: "18px", margin: 0 }}>
|
||||
整体评估
|
||||
</h3>
|
||||
<Badge className={`${statusColors.bg} ${statusColors.text} mt-1`}>
|
||||
{shareData.overall_status === "normal" ? "一切正常" : "需要关注"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<p className={`text-sm ${statusColors.text} leading-relaxed`} style={{ margin: 0 }}>
|
||||
{shareData.emotional_summary || shareData.overall_summary}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* 详细指标 */}
|
||||
{shareData.categories && shareData.categories.length > 0 && (
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
|
||||
<h3 style={{ fontWeight: 700, color: "#1f2937", fontSize: "18px", display: "flex", alignItems: "center", gap: "8px", margin: 0 }}>
|
||||
<TrendingUp className="w-5 h-5 text-morandi-400" />
|
||||
详细指标
|
||||
</h3>
|
||||
{shareData.categories.map((category: any, idx: number) => {
|
||||
const catColors = getStatusColor(category.status);
|
||||
return (
|
||||
<div key={idx} className={`${catColors.bg} rounded-2xl p-4`}>
|
||||
<div style={{ display: "flex", alignItems: "center", gap: "8px", marginBottom: "12px" }}>
|
||||
<h4 style={{ fontWeight: 600, color: "#1f2937", margin: 0 }}>{category.category}</h4>
|
||||
<Badge className={`${catColors.bg} ${catColors.text} text-xs`}>
|
||||
{category.status === "normal" ? "正常" : "需关注"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "12px" }}>
|
||||
{category.indicators.map((ind: any, indIdx: number) => (
|
||||
<div key={indIdx} style={{ background: "rgba(255,255,255,0.7)", borderRadius: "12px", padding: "12px" }}>
|
||||
<div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: "8px" }}>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontWeight: 600, color: "#1f2937", fontSize: "14px", marginBottom: "4px" }}>
|
||||
{ind.name}
|
||||
{ind.nickname && (
|
||||
<span style={{ fontSize: "12px", color: "#9ca3af", marginLeft: "8px" }}>({ind.nickname})</span>
|
||||
)}
|
||||
</div>
|
||||
{ind.value && (
|
||||
<div style={{ fontSize: "18px", fontWeight: 700, color: "#7c6995" }}>
|
||||
{ind.value} {ind.unit}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Badge className={`text-xs ${
|
||||
ind.status === "normal"
|
||||
? "bg-morandi-sage-100 text-morandi-sage-600"
|
||||
: "bg-morandi-rose-100 text-morandi-rose-600"
|
||||
}`}>
|
||||
{ind.status === "normal" ? "正常" : ind.status === "high" ? "偏高" : "偏低"}
|
||||
</Badge>
|
||||
</div>
|
||||
{ind.what_is_it && (
|
||||
<p style={{ fontSize: "12px", color: "#6b7280", marginBottom: "8px", margin: "0 0 8px 0" }}>
|
||||
{ind.what_is_it}
|
||||
</p>
|
||||
)}
|
||||
{ind.suggestion && (
|
||||
<div style={{ background: "#faf7fc", borderRadius: "8px", padding: "8px", marginTop: "8px" }}>
|
||||
<p style={{ fontSize: "12px", color: "#4b5563", margin: 0 }}>💡 {ind.suggestion}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 行动建议 */}
|
||||
{shareData.action_items && shareData.action_items.length > 0 && (
|
||||
<div>
|
||||
<h3 style={{ fontWeight: 700, color: "#1f2937", fontSize: "18px", marginBottom: "12px", marginTop: 0 }}>
|
||||
接下来该做什么?
|
||||
</h3>
|
||||
<div style={{ display: "flex", flexDirection: "column", gap: "8px" }}>
|
||||
{shareData.action_items.map((item: any, idx: number) => (
|
||||
<div
|
||||
key={idx}
|
||||
style={{
|
||||
borderRadius: "12px",
|
||||
padding: "12px",
|
||||
background: item.priority === "high" ? "#fce4ec" : "#faf7fc",
|
||||
}}
|
||||
>
|
||||
<div style={{ display: "flex", alignItems: "flex-start", gap: "8px" }}>
|
||||
<span
|
||||
style={{
|
||||
flexShrink: 0,
|
||||
width: 20,
|
||||
height: 20,
|
||||
background: "#b8a9c9",
|
||||
color: "white",
|
||||
borderRadius: "50%",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
fontSize: "12px",
|
||||
fontWeight: 700,
|
||||
marginTop: "2px",
|
||||
}}
|
||||
>
|
||||
{idx + 1}
|
||||
</span>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{ fontWeight: 600, color: "#1f2937", fontSize: "14px", marginBottom: "4px" }}>
|
||||
{item.title || item.content}
|
||||
</div>
|
||||
{item.description && (
|
||||
<p style={{ fontSize: "12px", color: "#6b7280", margin: 0 }}>{item.description}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 温馨提示 */}
|
||||
{shareData.tips && shareData.tips.length > 0 && (
|
||||
<div className="bg-morandi-50 rounded-2xl p-4">
|
||||
<h4 style={{ fontWeight: 600, color: "#1f2937", fontSize: "14px", marginBottom: "8px", display: "flex", alignItems: "center", gap: "8px", marginTop: 0 }}>
|
||||
<Heart className="w-4 h-4 text-morandi-400" />
|
||||
温馨提示
|
||||
</h4>
|
||||
<ul style={{ listStyle: "none", padding: 0, margin: 0, display: "flex", flexDirection: "column", gap: "4px" }}>
|
||||
{shareData.tips.map((tip: string, idx: number) => (
|
||||
<li key={idx} style={{ fontSize: "12px", color: "#6b7280", display: "flex", alignItems: "flex-start", gap: "8px" }}>
|
||||
<span style={{ color: "#b8a9c9" }}>•</span>
|
||||
<span>{tip}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 底部声明 */}
|
||||
<div style={{ paddingTop: "20px", borderTop: "2px solid #f3f4f6", textAlign: "center" }}>
|
||||
<p style={{ fontSize: "12px", color: "#9ca3af", marginBottom: "4px", margin: "0 0 4px 0" }}>
|
||||
本报告由 AI 生成,仅供参考,不能替代医生诊断
|
||||
</p>
|
||||
<p style={{ fontSize: "12px", color: "#9ca3af", marginBottom: "8px", margin: "0 0 8px 0" }}>
|
||||
如有疑问请及时咨询专业医生
|
||||
</p>
|
||||
<div
|
||||
style={{
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
gap: "4px",
|
||||
fontSize: "11px",
|
||||
color: "#b8a9c9",
|
||||
padding: "4px 12px",
|
||||
background: "#faf7fc",
|
||||
borderRadius: "9999px",
|
||||
}}
|
||||
>
|
||||
<Heart style={{ width: 12, height: 12, fill: "#b8a9c9", color: "#b8a9c9" }} />
|
||||
<span>孕育无忧 · yun.tun88.com</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
323
frontend/src/app/pages/TimelinePage.tsx
Normal file
323
frontend/src/app/pages/TimelinePage.tsx
Normal file
@@ -0,0 +1,323 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion } from "motion/react";
|
||||
import {
|
||||
ChevronLeft,
|
||||
Search,
|
||||
Filter,
|
||||
FileText,
|
||||
CheckCircle2,
|
||||
AlertCircle,
|
||||
ChevronRight,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Badge } from "../components/ui/badge";
|
||||
import { getTimeline } from "../services/api";
|
||||
|
||||
interface Report {
|
||||
id: string;
|
||||
type: string;
|
||||
date: string;
|
||||
status: "normal" | "attention" | "warning";
|
||||
summary: string;
|
||||
period: "early" | "mid" | "late";
|
||||
week: number;
|
||||
}
|
||||
|
||||
export function TimelinePage() {
|
||||
const navigate = useNavigate();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedPeriod, setSelectedPeriod] = useState("all");
|
||||
const [reports, setReports] = useState<Report[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
getTimeline()
|
||||
.then((data) => {
|
||||
setReports(
|
||||
data.reports.map((r) => ({
|
||||
id: r.id,
|
||||
type: r.report_type,
|
||||
date: r.date,
|
||||
status: (r.status as Report["status"]) || "normal",
|
||||
summary: r.summary,
|
||||
period: (r.period as Report["period"]) || "early",
|
||||
week: r.week,
|
||||
}))
|
||||
);
|
||||
})
|
||||
.catch(() => {/* keep empty */})
|
||||
.finally(() => setLoading(false));
|
||||
}, []);
|
||||
|
||||
const filteredReports = reports.filter((report) => {
|
||||
const matchesSearch =
|
||||
report.type.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||
report.summary.toLowerCase().includes(searchQuery.toLowerCase());
|
||||
const matchesPeriod =
|
||||
selectedPeriod === "all" || report.period === selectedPeriod;
|
||||
return matchesSearch && matchesPeriod;
|
||||
});
|
||||
|
||||
const periods = [
|
||||
{ id: "all", name: "全部", weeks: "1-40周" },
|
||||
{ id: "early", name: "孕早期", weeks: "1-12周" },
|
||||
{ id: "mid", name: "孕中期", weeks: "13-27周" },
|
||||
{ id: "late", name: "孕晚期", weeks: "28-40周" },
|
||||
];
|
||||
|
||||
const groupedReports = filteredReports.reduce((acc, report) => {
|
||||
const month = report.date.substring(0, 7); // "2026-03"
|
||||
if (!acc[month]) {
|
||||
acc[month] = [];
|
||||
}
|
||||
acc[month].push(report);
|
||||
return acc;
|
||||
}, {} as Record<string, Report[]>);
|
||||
|
||||
const monthNames: Record<string, string> = {};
|
||||
Object.keys(groupedReports).forEach((month) => {
|
||||
const [y, m] = month.split("-");
|
||||
monthNames[month] = `${y}年${parseInt(m)}月`;
|
||||
});
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 text-morandi-400 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ChevronLeft className="w-6 h-6 text-gray-600" />
|
||||
</button>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-10 h-10 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full flex items-center justify-center">
|
||||
<FileText className="w-5 h-5 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-semibold text-gray-800">报告时间轴</h1>
|
||||
<p className="text-xs text-gray-500">
|
||||
共{filteredReports.length}份报告
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 搜索框 */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
placeholder="搜索报告类型或内容..."
|
||||
className="pl-12 rounded-full border-gray-200"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-6">
|
||||
{/* 孕期筛选 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<div className="flex gap-2 overflow-x-auto pb-2">
|
||||
{periods.map((period) => (
|
||||
<button
|
||||
key={period.id}
|
||||
onClick={() => setSelectedPeriod(period.id as any)}
|
||||
className={`flex-shrink-0 px-6 py-3 rounded-2xl font-semibold text-sm transition-all ${
|
||||
selectedPeriod === period.id
|
||||
? "bg-gradient-to-r from-morandi-400 to-morandi-400 text-white shadow-sm"
|
||||
: "bg-white text-gray-600 hover:bg-gray-50"
|
||||
}`}
|
||||
>
|
||||
<div>{period.name}</div>
|
||||
<div className="text-xs opacity-80">{period.weeks}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</motion.div>
|
||||
|
||||
{/* 统计卡片 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.1 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-4 shadow-sm border-0">
|
||||
<div className="grid grid-cols-3 gap-4">
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-semibold text-morandi-sage-500 mb-1">
|
||||
{
|
||||
filteredReports.filter((r) => r.status === "normal").length
|
||||
}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">正常</div>
|
||||
</div>
|
||||
<div className="text-center border-l border-r border-gray-100">
|
||||
<div className="text-2xl font-semibold text-morandi-600 mb-1">
|
||||
{
|
||||
filteredReports.filter((r) => r.status === "attention")
|
||||
.length
|
||||
}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">需关注</div>
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="text-2xl font-semibold text-red-600 mb-1">
|
||||
{
|
||||
filteredReports.filter((r) => r.status === "warning").length
|
||||
}
|
||||
</div>
|
||||
<div className="text-xs text-gray-500">异常</div>
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
|
||||
{/* 时间轴 */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 20 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
transition={{ delay: 0.2 }}
|
||||
className="space-y-6"
|
||||
>
|
||||
{Object.keys(groupedReports)
|
||||
.sort()
|
||||
.reverse()
|
||||
.map((month) => (
|
||||
<div key={month}>
|
||||
<h2 className="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-morandi-400 rounded-full"></div>
|
||||
{monthNames[month] || month}
|
||||
</h2>
|
||||
<div className="relative pl-6 space-y-4">
|
||||
{/* 时间线 */}
|
||||
<div className="absolute left-1 top-0 bottom-0 w-0.5 bg-gradient-to-b from-morandi-200 to-morandi-200"></div>
|
||||
|
||||
{groupedReports[month].map((report, index) => (
|
||||
<motion.div
|
||||
key={report.id}
|
||||
initial={{ opacity: 0, x: -20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
transition={{ delay: 0.3 + index * 0.05 }}
|
||||
className="relative"
|
||||
>
|
||||
{/* 时间点 */}
|
||||
<div
|
||||
className={`absolute -left-6 top-4 w-3 h-3 rounded-full border-2 border-white ${
|
||||
report.status === "normal"
|
||||
? "bg-morandi-sage-400"
|
||||
: report.status === "attention"
|
||||
? "bg-morandi-rose-400"
|
||||
: "bg-red-500"
|
||||
}`}
|
||||
></div>
|
||||
|
||||
<Card
|
||||
onClick={() => navigate(`/analysis/${report.id}`)}
|
||||
className="bg-white rounded-2xl p-4 shadow-sm hover:shadow-sm transition-all cursor-pointer border-0"
|
||||
>
|
||||
<div className="flex items-center gap-4">
|
||||
<div
|
||||
className={`w-12 h-12 rounded-xl flex items-center justify-center ${
|
||||
report.status === "normal"
|
||||
? "bg-morandi-sage-100"
|
||||
: report.status === "attention"
|
||||
? "bg-morandi-rose-100"
|
||||
: "bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{report.status === "normal" ? (
|
||||
<CheckCircle2
|
||||
className={`w-6 h-6 ${
|
||||
report.status === "normal"
|
||||
? "text-morandi-sage-400"
|
||||
: report.status === "attention"
|
||||
? "text-morandi-rose-400"
|
||||
: "text-red-500"
|
||||
}`}
|
||||
/>
|
||||
) : (
|
||||
<AlertCircle
|
||||
className={`w-6 h-6 ${
|
||||
report.status === "attention"
|
||||
? "text-morandi-rose-400"
|
||||
: "text-red-500"
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-semibold text-gray-800">
|
||||
{report.type}
|
||||
</h3>
|
||||
<Badge className="bg-morandi-100 text-morandi-500 hover:bg-morandi-100 text-xs">
|
||||
孕{report.week}周
|
||||
</Badge>
|
||||
<Badge
|
||||
className={`text-xs ${
|
||||
report.status === "normal"
|
||||
? "bg-morandi-sage-100 text-morandi-sage-600 hover:bg-morandi-sage-100"
|
||||
: report.status === "attention"
|
||||
? "bg-morandi-rose-100 text-morandi-600 hover:bg-morandi-rose-100"
|
||||
: "bg-red-100 text-red-700 hover:bg-red-100"
|
||||
}`}
|
||||
>
|
||||
{report.status === "normal"
|
||||
? "正常"
|
||||
: report.status === "attention"
|
||||
? "关注"
|
||||
: "异常"}
|
||||
</Badge>
|
||||
</div>
|
||||
<p className="text-sm text-gray-600 truncate">
|
||||
{report.summary}
|
||||
</p>
|
||||
<p className="text-xs text-gray-400 mt-1">
|
||||
{report.date}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<ChevronRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</motion.div>
|
||||
|
||||
{filteredReports.length === 0 && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="text-center py-12"
|
||||
>
|
||||
<FileText className="w-16 h-16 text-gray-300 mx-auto mb-4" />
|
||||
<p className="text-gray-500">暂无相关报告</p>
|
||||
</motion.div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
840
frontend/src/app/pages/VoiceRecordPage.tsx
Normal file
840
frontend/src/app/pages/VoiceRecordPage.tsx
Normal file
@@ -0,0 +1,840 @@
|
||||
import { useState, useRef, useEffect, useCallback } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { motion, AnimatePresence } from "motion/react";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Mic,
|
||||
MicOff,
|
||||
Square,
|
||||
Play,
|
||||
Pause,
|
||||
Trash2,
|
||||
Stethoscope,
|
||||
Smile,
|
||||
ShieldCheck,
|
||||
Settings,
|
||||
RefreshCw,
|
||||
Pencil,
|
||||
Check,
|
||||
} from "lucide-react";
|
||||
import { Card } from "../components/ui/card";
|
||||
import { Button } from "../components/ui/button";
|
||||
|
||||
type Recording = {
|
||||
id: string;
|
||||
name: string;
|
||||
tag: string;
|
||||
duration: number;
|
||||
date: string;
|
||||
mood: string;
|
||||
audioUrl?: string;
|
||||
audioData?: string;
|
||||
};
|
||||
|
||||
type MicPermission = "checking" | "prompt" | "granted" | "denied" | "unsupported" | "insecure";
|
||||
|
||||
const TABS = [
|
||||
{ key: "visit", label: "就诊记录", icon: Stethoscope },
|
||||
{ key: "mood", label: "孕期心情", icon: Smile },
|
||||
] as const;
|
||||
|
||||
type TabKey = (typeof TABS)[number]["key"];
|
||||
|
||||
const STORAGE_KEY = "voice_recordings";
|
||||
|
||||
function blobToBase64(blob: Blob): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onloadend = () => resolve(reader.result as string);
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
function base64ToBlobUrl(base64: string): string {
|
||||
const [header, data] = base64.split(",");
|
||||
const mime = header.match(/:(.*?);/)?.[1] || "audio/webm";
|
||||
const binary = atob(data);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return URL.createObjectURL(new Blob([bytes], { type: mime }));
|
||||
}
|
||||
|
||||
export function VoiceRecordPage() {
|
||||
const navigate = useNavigate();
|
||||
const [activeTab, setActiveTab] = useState<TabKey>("visit");
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [recordingTime, setRecordingTime] = useState(0);
|
||||
const [playingId, setPlayingId] = useState<string | null>(null);
|
||||
const [micPermission, setMicPermission] = useState<MicPermission>("checking");
|
||||
const [isRequesting, setIsRequesting] = useState(false);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editingName, setEditingName] = useState("");
|
||||
|
||||
const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);
|
||||
const mediaRecorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null);
|
||||
|
||||
const [recordings, setRecordings] = useState<Recording[]>([]);
|
||||
|
||||
const currentTag = TABS.find((t) => t.key === activeTab)!.label;
|
||||
const filteredRecordings = recordings.filter((r) => r.tag === currentTag);
|
||||
|
||||
// ─── 权限检测 ───
|
||||
const checkPermission = useCallback(async () => {
|
||||
// 检查是否在安全上下文中(HTTPS 或 localhost)
|
||||
if (!window.isSecureContext) {
|
||||
setMicPermission("insecure");
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查浏览器是否支持
|
||||
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
||||
setMicPermission("unsupported");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// 使用 Permissions API 查询(部分浏览器支持)
|
||||
if (navigator.permissions && navigator.permissions.query) {
|
||||
const result = await navigator.permissions.query({ name: "microphone" as PermissionName });
|
||||
setMicPermission(result.state as MicPermission);
|
||||
// 监听权限变化(用户在系统设置中更改)
|
||||
result.onchange = () => {
|
||||
setMicPermission(result.state as MicPermission);
|
||||
};
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Permissions API 不支持 microphone 查询(如 Firefox),fallback
|
||||
}
|
||||
|
||||
// Fallback:尝试实际请求来判断
|
||||
setMicPermission("prompt");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkPermission();
|
||||
}, [checkPermission]);
|
||||
|
||||
// ─── 从 localStorage 恢复录音 ───
|
||||
useEffect(() => {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
if (saved) {
|
||||
const parsed: Recording[] = JSON.parse(saved);
|
||||
setRecordings(
|
||||
parsed.map((r) => ({
|
||||
...r,
|
||||
audioUrl: r.audioData ? base64ToBlobUrl(r.audioData) : undefined,
|
||||
}))
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ─── 录音变化时持久化到 localStorage ───
|
||||
useEffect(() => {
|
||||
try {
|
||||
const toSave = recordings.map(({ audioUrl, ...rest }) => rest);
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
|
||||
} catch {
|
||||
/* storage full or unavailable */
|
||||
}
|
||||
}, [recordings]);
|
||||
|
||||
// ─── 请求麦克风权限 ───
|
||||
const requestPermission = async () => {
|
||||
setIsRequesting(true);
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
// 拿到权限后立即释放
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
setMicPermission("granted");
|
||||
} catch (err: unknown) {
|
||||
const error = err as DOMException;
|
||||
if (error.name === "NotAllowedError" || error.name === "PermissionDeniedError") {
|
||||
setMicPermission("denied");
|
||||
} else {
|
||||
setMicPermission("unsupported");
|
||||
}
|
||||
} finally {
|
||||
setIsRequesting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ─── 录音功能 ───
|
||||
const formatTime = (seconds: number) => {
|
||||
const m = Math.floor(seconds / 60);
|
||||
const s = seconds % 60;
|
||||
return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
|
||||
};
|
||||
|
||||
const startRecording = async () => {
|
||||
try {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
const mediaRecorder = new MediaRecorder(stream);
|
||||
mediaRecorderRef.current = mediaRecorder;
|
||||
chunksRef.current = [];
|
||||
|
||||
mediaRecorder.ondataavailable = (e) => {
|
||||
if (e.data.size > 0) chunksRef.current.push(e.data);
|
||||
};
|
||||
|
||||
mediaRecorder.start();
|
||||
setIsRecording(true);
|
||||
setRecordingTime(0);
|
||||
timerRef.current = setInterval(() => {
|
||||
setRecordingTime((prev) => prev + 1);
|
||||
}, 1000);
|
||||
} catch {
|
||||
// 录音时被拒绝,更新权限状态
|
||||
setMicPermission("denied");
|
||||
}
|
||||
};
|
||||
|
||||
const stopRecording = () => {
|
||||
setIsRecording(false);
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
|
||||
const recorder = mediaRecorderRef.current;
|
||||
if (recorder && recorder.state !== "inactive") {
|
||||
const duration = recordingTime;
|
||||
recorder.onstop = async () => {
|
||||
const mimeType = recorder.mimeType || "audio/webm";
|
||||
const blob = new Blob(chunksRef.current, { type: mimeType });
|
||||
const audioUrl = URL.createObjectURL(blob);
|
||||
const audioData = await blobToBase64(blob);
|
||||
recorder.stream.getTracks().forEach((track) => track.stop());
|
||||
|
||||
if (duration > 0) {
|
||||
const moodList = ["😊", "🥰", "😌", "💪", "🤔"];
|
||||
const now = new Date();
|
||||
const timeStr = `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}`;
|
||||
const dateStr = now.toISOString().split("T")[0];
|
||||
setRecordings((prev) => {
|
||||
const count = prev.filter((r) => r.tag === currentTag && r.date === dateStr).length + 1;
|
||||
return [
|
||||
{
|
||||
id: Date.now().toString(),
|
||||
name: `${currentTag} ${dateStr} ${timeStr}${count > 1 ? ` (${count})` : ""}`,
|
||||
tag: currentTag,
|
||||
duration,
|
||||
date: dateStr,
|
||||
mood: moodList[Math.floor(Math.random() * moodList.length)],
|
||||
audioUrl,
|
||||
audioData,
|
||||
},
|
||||
...prev,
|
||||
];
|
||||
});
|
||||
}
|
||||
};
|
||||
recorder.stop();
|
||||
}
|
||||
setRecordingTime(0);
|
||||
};
|
||||
|
||||
const startRename = (rec: Recording) => {
|
||||
setEditingId(rec.id);
|
||||
setEditingName(rec.name);
|
||||
};
|
||||
|
||||
const confirmRename = () => {
|
||||
if (editingId && editingName.trim()) {
|
||||
setRecordings((prev) =>
|
||||
prev.map((r) => (r.id === editingId ? { ...r, name: editingName.trim() } : r))
|
||||
);
|
||||
}
|
||||
setEditingId(null);
|
||||
setEditingName("");
|
||||
};
|
||||
|
||||
const deleteRecording = (id: string) => {
|
||||
const rec = recordings.find((r) => r.id === id);
|
||||
if (rec?.audioUrl) URL.revokeObjectURL(rec.audioUrl);
|
||||
setRecordings((prev) => prev.filter((r) => r.id !== id));
|
||||
};
|
||||
|
||||
const togglePlay = (id: string) => {
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current = null;
|
||||
}
|
||||
|
||||
if (playingId === id) {
|
||||
setPlayingId(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const rec = recordings.find((r) => r.id === id);
|
||||
if (!rec?.audioUrl) return;
|
||||
|
||||
const audio = new Audio(rec.audioUrl);
|
||||
audioRef.current = audio;
|
||||
audio.onended = () => {
|
||||
setPlayingId(null);
|
||||
audioRef.current = null;
|
||||
};
|
||||
audio.play().catch(() => {
|
||||
setPlayingId(null);
|
||||
audioRef.current = null;
|
||||
});
|
||||
setPlayingId(id);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timerRef.current) clearInterval(timerRef.current);
|
||||
if (audioRef.current) {
|
||||
audioRef.current.pause();
|
||||
audioRef.current = null;
|
||||
}
|
||||
if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
|
||||
mediaRecorderRef.current.stop();
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
// ─── 权限引导 UI ───
|
||||
const renderPermissionGuide = () => {
|
||||
if (micPermission === "checking") {
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
className="flex flex-col items-center gap-4 py-4"
|
||||
>
|
||||
<motion.div
|
||||
animate={{ rotate: 360 }}
|
||||
transition={{ duration: 1.5, repeat: Infinity, ease: "linear" }}
|
||||
>
|
||||
<RefreshCw className="w-8 h-8 text-morandi-400" />
|
||||
</motion.div>
|
||||
<p className="text-sm text-gray-500">正在检查麦克风权限...</p>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
if (micPermission === "unsupported") {
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex flex-col items-center gap-4 py-4"
|
||||
>
|
||||
<div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center">
|
||||
<MicOff className="w-8 h-8 text-gray-400" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="font-medium text-gray-700 mb-1">浏览器不支持录音</p>
|
||||
<p className="text-sm text-gray-500 leading-relaxed">
|
||||
请使用 Safari、Chrome 等现代浏览器访问
|
||||
</p>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
if (micPermission === "insecure") {
|
||||
const currentUrl = window.location.href;
|
||||
const httpsUrl = currentUrl.replace(/^http:/, "https:");
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex flex-col items-center gap-5 py-4"
|
||||
>
|
||||
<div className="w-20 h-20 bg-amber-50 rounded-full flex items-center justify-center">
|
||||
<ShieldCheck className="w-10 h-10 text-amber-500" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="font-semibold text-gray-800 mb-2">需要安全连接</p>
|
||||
<p className="text-sm text-gray-500 leading-relaxed px-2">
|
||||
麦克风和摄像头功能需要通过 HTTPS 安全连接才能使用,当前页面使用的是不安全的 HTTP 连接
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-amber-50 rounded-xl p-4 w-full">
|
||||
<p className="text-sm font-medium text-gray-700 mb-2">解决方法:</p>
|
||||
<ol className="text-sm text-gray-600 space-y-2">
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-amber-200 text-amber-700 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
|
||||
<span>将地址栏中的 <strong>http://</strong> 改为 <strong>https://</strong></span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-amber-200 text-amber-700 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
|
||||
<span>如果浏览器提示证书不安全,点击「继续访问」或「高级」→「继续」</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
onClick={() => { window.location.href = httpsUrl; }}
|
||||
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
|
||||
>
|
||||
<ShieldCheck className="w-4 h-4 mr-2" />
|
||||
切换到 HTTPS 访问
|
||||
</Button>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
if (micPermission === "prompt") {
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex flex-col items-center gap-5 py-4"
|
||||
>
|
||||
<div className="w-20 h-20 bg-gradient-to-br from-morandi-100 to-morandi-200 rounded-full flex items-center justify-center">
|
||||
<Mic className="w-10 h-10 text-morandi-500" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="font-semibold text-gray-800 mb-2">需要麦克风权限</p>
|
||||
<p className="text-sm text-gray-500 leading-relaxed px-4">
|
||||
录音功能需要访问您的麦克风,点击下方按钮授权后即可开始录音
|
||||
</p>
|
||||
</div>
|
||||
<div className="bg-morandi-50 rounded-xl p-4 w-full">
|
||||
<div className="flex items-start gap-3">
|
||||
<ShieldCheck className="w-5 h-5 text-morandi-400 flex-shrink-0 mt-0.5" />
|
||||
<div>
|
||||
<p className="text-xs text-gray-600 leading-relaxed">
|
||||
我们仅在录音时使用麦克风,录音数据保存在您的设备本地,不会上传到服务器
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
onClick={requestPermission}
|
||||
disabled={isRequesting}
|
||||
className="w-full h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
|
||||
>
|
||||
{isRequesting ? (
|
||||
<>
|
||||
<motion.div
|
||||
animate={{ rotate: 360 }}
|
||||
transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
|
||||
className="mr-2"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4" />
|
||||
</motion.div>
|
||||
正在请求权限...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Mic className="w-4 h-4 mr-2" />
|
||||
授权麦克风
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
if (micPermission === "denied") {
|
||||
const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent);
|
||||
const isAndroid = /Android/.test(navigator.userAgent);
|
||||
const isWechat = /MicroMessenger/.test(navigator.userAgent);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
className="flex flex-col items-center gap-5 py-4"
|
||||
>
|
||||
<div className="w-20 h-20 bg-red-50 rounded-full flex items-center justify-center">
|
||||
<MicOff className="w-10 h-10 text-red-400" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<p className="font-semibold text-gray-800 mb-2">麦克风权限已被拒绝</p>
|
||||
<p className="text-sm text-gray-500 leading-relaxed px-2">
|
||||
请按以下步骤手动开启麦克风权限后,点击"重新检测"
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="w-full space-y-3">
|
||||
{isWechat ? (
|
||||
<div className="bg-morandi-50 rounded-xl p-4">
|
||||
<p className="text-sm font-medium text-gray-700 mb-2">微信内操作:</p>
|
||||
<ol className="text-sm text-gray-600 space-y-2">
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
|
||||
<span>点击右上角「...」更多按钮</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
|
||||
<span>选择「设置」</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
|
||||
<span>开启「麦克风」权限</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
) : isIOS ? (
|
||||
<div className="bg-morandi-50 rounded-xl p-4">
|
||||
<p className="text-sm font-medium text-gray-700 mb-2">iOS 设备操作:</p>
|
||||
<ol className="text-sm text-gray-600 space-y-2">
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
|
||||
<span>打开手机「设置」应用</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
|
||||
<span>向下滑动找到「Safari浏览器」(或当前浏览器)</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
|
||||
<span>点击进入,找到「麦克风」并开启</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
) : isAndroid ? (
|
||||
<div className="bg-morandi-50 rounded-xl p-4">
|
||||
<p className="text-sm font-medium text-gray-700 mb-2">安卓设备操作:</p>
|
||||
<ol className="text-sm text-gray-600 space-y-2">
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
|
||||
<span>打开手机「设置」→「应用管理」</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
|
||||
<span>找到当前浏览器应用</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
|
||||
<span>点击「权限」→ 开启「麦克风」</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
) : (
|
||||
<div className="bg-morandi-50 rounded-xl p-4">
|
||||
<p className="text-sm font-medium text-gray-700 mb-2">浏览器操作:</p>
|
||||
<ol className="text-sm text-gray-600 space-y-2">
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">1</span>
|
||||
<span>点击地址栏左侧的锁形图标或设置图标</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">2</span>
|
||||
<span>找到「麦克风」权限设置</span>
|
||||
</li>
|
||||
<li className="flex gap-2">
|
||||
<span className="flex-shrink-0 w-5 h-5 bg-morandi-200 text-morandi-600 rounded-full flex items-center justify-center text-xs font-semibold">3</span>
|
||||
<span>将其改为「允许」,然后刷新页面</span>
|
||||
</li>
|
||||
</ol>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 w-full">
|
||||
<Button
|
||||
onClick={() => {
|
||||
setMicPermission("checking");
|
||||
checkPermission();
|
||||
}}
|
||||
className="flex-1 h-12 rounded-xl bg-gradient-to-r from-morandi-400 to-morandi-500 hover:from-morandi-500 hover:to-morandi-500 text-white font-medium"
|
||||
>
|
||||
<RefreshCw className="w-4 h-4 mr-2" />
|
||||
重新检测
|
||||
</Button>
|
||||
<Button
|
||||
onClick={requestPermission}
|
||||
variant="outline"
|
||||
className="flex-1 h-12 rounded-xl border-2 border-morandi-200 text-morandi-500 font-medium"
|
||||
>
|
||||
<Settings className="w-4 h-4 mr-2" />
|
||||
再次请求
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
// ─── 录音控制区 UI(已授权状态)───
|
||||
const renderRecorder = () => (
|
||||
<AnimatePresence mode="wait">
|
||||
{isRecording ? (
|
||||
<motion.div
|
||||
key="recording"
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="flex flex-col items-center gap-4"
|
||||
>
|
||||
{/* 波形动画 */}
|
||||
<div className="flex items-center gap-1 h-12">
|
||||
{Array.from({ length: 24 }).map((_, i) => (
|
||||
<motion.div
|
||||
key={i}
|
||||
className="w-1 bg-morandi-400 rounded-full"
|
||||
animate={{
|
||||
height: [6, 14 + Math.random() * 24, 6],
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.6 + Math.random() * 0.4,
|
||||
repeat: Infinity,
|
||||
delay: i * 0.05,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-2 h-2 bg-red-400 rounded-full animate-pulse" />
|
||||
<span className="text-lg font-mono font-semibold text-gray-700">
|
||||
{formatTime(recordingTime)}
|
||||
</span>
|
||||
<span className="text-sm text-gray-400">· {currentTag}</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={stopRecording}
|
||||
className="w-16 h-16 bg-red-400 hover:bg-red-500 rounded-full flex items-center justify-center shadow-sm shadow-red-200 transition-all hover:scale-105"
|
||||
>
|
||||
<Square className="w-6 h-6 text-white fill-white" />
|
||||
</button>
|
||||
<span className="text-xs text-gray-400">点击停止录音</span>
|
||||
</motion.div>
|
||||
) : (
|
||||
<motion.div
|
||||
key="idle"
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
className="flex flex-col items-center gap-4"
|
||||
>
|
||||
<p className="text-sm text-gray-500">
|
||||
{activeTab === "visit"
|
||||
? "记录就诊过程,方便日后回顾"
|
||||
: "记录今天的心情和感受"}
|
||||
</p>
|
||||
<button
|
||||
onClick={startRecording}
|
||||
className="w-16 h-16 bg-gradient-to-br from-morandi-400 to-morandi-500 rounded-full flex items-center justify-center shadow-sm transition-all hover:scale-105"
|
||||
>
|
||||
<Mic className="w-7 h-7 text-white" />
|
||||
</button>
|
||||
<span className="text-xs text-gray-400">点击开始录音</span>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh bg-morandi-50">
|
||||
{/* 顶部导航 */}
|
||||
<div className="bg-white border-b border-gray-100 sticky top-0 z-10">
|
||||
<div className="mx-auto px-4 py-4 flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => navigate(-1)}
|
||||
className="w-10 h-10 rounded-full hover:bg-gray-100 flex items-center justify-center"
|
||||
>
|
||||
<ArrowLeft className="w-5 h-5 text-gray-600" />
|
||||
</button>
|
||||
<h1 className="font-semibold text-gray-800 text-base">语音记录</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto p-4 space-y-5">
|
||||
{/* Tab 切换 */}
|
||||
<div className="flex bg-white rounded-2xl p-1.5 shadow-sm">
|
||||
{TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.key}
|
||||
onClick={() => {
|
||||
if (!isRecording) setActiveTab(tab.key);
|
||||
}}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl text-sm font-medium transition-all ${
|
||||
activeTab === tab.key
|
||||
? "bg-morandi-400 text-white shadow-sm"
|
||||
: "text-gray-500 hover:text-gray-700"
|
||||
}`}
|
||||
>
|
||||
<tab.icon className="w-4 h-4" />
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* 录音控制区 */}
|
||||
<Card className="bg-white rounded-2xl p-6 shadow-md border-0">
|
||||
<div className="bg-gradient-to-r from-morandi-50 to-morandi-100 rounded-2xl p-5">
|
||||
{micPermission === "granted" ? renderRecorder() : renderPermissionGuide()}
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
{/* 录音列表 */}
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h2 className="font-semibold text-gray-800">
|
||||
{currentTag} ({filteredRecordings.length})
|
||||
</h2>
|
||||
</div>
|
||||
|
||||
{filteredRecordings.length === 0 ? (
|
||||
<Card className="bg-white rounded-2xl p-8 shadow-md border-0 text-center">
|
||||
<Mic className="w-10 h-10 text-gray-300 mx-auto mb-3" />
|
||||
<p className="text-sm text-gray-400">暂无录音,点击上方开始记录</p>
|
||||
</Card>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{filteredRecordings.map((rec) => (
|
||||
<motion.div
|
||||
key={rec.id}
|
||||
layout
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
>
|
||||
<Card className="bg-white rounded-2xl p-4 shadow-md border-0 group">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
onClick={() => togglePlay(rec.id)}
|
||||
disabled={!rec.audioUrl}
|
||||
className="w-11 h-11 rounded-full bg-morandi-100 flex items-center justify-center flex-shrink-0 hover:bg-morandi-200 transition-colors disabled:opacity-50"
|
||||
>
|
||||
{playingId === rec.id ? (
|
||||
<Pause className="w-5 h-5 text-morandi-500" />
|
||||
) : (
|
||||
<Play className="w-5 h-5 text-morandi-500 ml-0.5" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
{editingId === rec.id ? (
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<input
|
||||
autoFocus
|
||||
value={editingName}
|
||||
onChange={(e) => setEditingName(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter") confirmRename();
|
||||
if (e.key === "Escape") { setEditingId(null); setEditingName(""); }
|
||||
}}
|
||||
onBlur={confirmRename}
|
||||
className="flex-1 min-w-0 text-sm font-medium text-gray-700 border-b-2 border-morandi-400 outline-none bg-transparent py-0.5"
|
||||
/>
|
||||
<button
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={confirmRename}
|
||||
className="p-1 rounded hover:bg-morandi-100"
|
||||
>
|
||||
<Check className="w-4 h-4 text-morandi-500" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-sm font-medium text-gray-700 truncate">
|
||||
{rec.name || rec.tag}
|
||||
</span>
|
||||
<span className="text-base flex-shrink-0">{rec.mood}</span>
|
||||
<button
|
||||
onClick={() => startRename(rec)}
|
||||
className="p-1 rounded hover:bg-morandi-100 flex-shrink-0"
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5 text-gray-400" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2 text-xs text-gray-400">
|
||||
<span>{formatTime(rec.duration)}</span>
|
||||
<span>·</span>
|
||||
<span>{rec.date}</span>
|
||||
</div>
|
||||
|
||||
{/* 播放波形动画 */}
|
||||
{playingId === rec.id && (
|
||||
<div className="flex items-center gap-0.5 mt-2 h-4">
|
||||
{Array.from({ length: 30 }).map((_, i) => (
|
||||
<motion.div
|
||||
key={i}
|
||||
className="w-1 bg-morandi-300 rounded-full"
|
||||
animate={{
|
||||
height: [3, 6 + Math.random() * 10, 3],
|
||||
}}
|
||||
transition={{
|
||||
duration: 0.5 + Math.random() * 0.3,
|
||||
repeat: Infinity,
|
||||
delay: i * 0.03,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => setDeletingId(rec.id)}
|
||||
className="p-2 rounded-lg hover:bg-red-50 active:bg-red-50 transition-all"
|
||||
>
|
||||
<Trash2 className="w-4 h-4 text-gray-400 hover:text-red-400" />
|
||||
</button>
|
||||
</div>
|
||||
</Card>
|
||||
</motion.div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 删除确认弹窗 */}
|
||||
<AnimatePresence>
|
||||
{deletingId && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-8"
|
||||
onClick={() => setDeletingId(null)}
|
||||
>
|
||||
<motion.div
|
||||
initial={{ scale: 0.9, opacity: 0 }}
|
||||
animate={{ scale: 1, opacity: 1 }}
|
||||
exit={{ scale: 0.9, opacity: 0 }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
className="bg-white rounded-2xl p-6 w-full max-w-sm shadow-xl"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-3 mb-5">
|
||||
<div className="w-12 h-12 bg-red-50 rounded-full flex items-center justify-center">
|
||||
<Trash2 className="w-6 h-6 text-red-400" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-gray-800">确认删除</h3>
|
||||
<p className="text-sm text-gray-500 text-center">
|
||||
删除后无法恢复,确定要删除这条录音吗?
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setDeletingId(null)}
|
||||
className="flex-1 h-11 rounded-xl"
|
||||
>
|
||||
取消
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
deleteRecording(deletingId);
|
||||
setDeletingId(null);
|
||||
}}
|
||||
className="flex-1 h-11 rounded-xl bg-red-400 hover:bg-red-500 text-white"
|
||||
>
|
||||
删除
|
||||
</Button>
|
||||
</div>
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user