"use client"; import { useSession } from "next-auth/react"; import { useRouter } from "next/navigation"; import { useState, useEffect } from "react"; import Header from "@/components/Header"; import LoadingSpinner from "@/components/LoadingSpinner"; interface UserProfile { id: string; name: string; email: string; image?: string; createdAt: string; } export default function ProfilePage() { const { data: session, status } = useSession(); const router = useRouter(); const [isEditing, setIsEditing] = useState(false); const [name, setName] = useState(""); const [isSaving, setIsSaving] = useState(false); const [isLoading, setIsLoading] = useState(true); const [userProfile, setUserProfile] = useState(null); // 获取用户资料 const fetchUserProfile = async () => { try { const response = await fetch("/api/user/profile"); if (response.ok) { const result = await response.json(); if (result.success && result.data) { const data = result.data; setUserProfile(data); setName(data.name || ""); } else { console.error("API 返回数据格式错误:", result); } } } catch (error) { console.error("获取用户资料失败:", error); } finally { setIsLoading(false); } }; useEffect(() => { if (status === "authenticated") { fetchUserProfile(); } }, [status]); const handleSave = async () => { setIsSaving(true); try { const response = await fetch("/api/user/profile", { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ name }), }); if (response.ok) { const result = await response.json(); if (result.success && result.data) { const updatedProfile = result.data; setUserProfile(updatedProfile); setIsEditing(false); // 刷新 session 以更新显示名称 window.location.reload(); } else { throw new Error("API 返回数据格式错误"); } } else { throw new Error("保存失败"); } } catch (error) { console.error("保存失败:", error); alert("保存失败,请重试"); } finally { setIsSaving(false); } }; if (status === "loading" || isLoading) { return (
); } if (status === "unauthenticated") { router.push("/login"); return null; } if (!session?.user || !userProfile) { return null; } return (
{userProfile.name?.[0] || userProfile.email?.[0] || "U"}

个人资料

管理你的账户信息

{/* 基本信息 */}

基本信息

{isEditing ? ( setName(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="请输入显示名称" /> ) : (
{userProfile.name || "未设置"}
)}
{userProfile.email}
{userProfile.email?.includes("@gmail.com") ? "Google 账户" : "邮箱账户"}
{new Date(userProfile.createdAt).toLocaleDateString( "zh-CN" )}
{/* 操作按钮 */}
{isEditing ? ( <> ) : ( )}
); }