"use client" import type React from "react" import { useState } from "react" import type { FamilyMember } from "@/types/family" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Textarea } from "@/components/ui/textarea" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group" import { CalendarIcon, User, Scroll, Users, Images, BookOpen } from "lucide-react" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Switch } from "@/components/ui/switch" import { ImageUpload } from "@/components/ui/image-upload" import { PhotoGallery } from "./photo-gallery" import { StoryManager } from "./story-manager" import { DateInputWithLunar } from "@/components/ui/date-input-with-lunar" import { MemberNameWithStatus } from "@/components/member-name-with-status" interface MemberFormProps { initialData?: Partial existingMembers?: FamilyMember[] onSubmit: (data: FamilyMember) => void onCancel: () => void isFounder?: boolean } export function MemberForm({ initialData, existingMembers = [], onSubmit, onCancel, isFounder = false }: MemberFormProps) { // 计算最大世系 const maxGeneration = existingMembers.length > 0 ? Math.max(...existingMembers.map(m => m.generation || 1)) : 1 // 获取始祖的姓氏(第1世成员) const ancestorSurname = existingMembers.find(m => m.generation === 1)?.surname || "" // 始祖专用样式 const founderCardClass = isFounder ? "border-2 border-amber-400 shadow-md" : "" // 生成兼容的UUID const generateUUID = () => { if (typeof crypto !== 'undefined' && crypto.randomUUID) { return crypto.randomUUID() } // 降级方案:生成简单的UUID return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { const r = Math.random() * 16 | 0 const v = c === 'x' ? r : (r & 0x3 | 0x8) return v.toString(16) }) } // Initialize state with default values or initialData const [formData, setFormData] = useState>(() => { const defaults = { id: generateUUID(), surname: ancestorSurname, givenName: "", fullName: "", gender: "MALE" as "MALE" | "FEMALE", generation: maxGeneration, spouseIds: [], childrenIds: [], tags: [], } if (!initialData) return defaults return { ...defaults, ...initialData, gender: (initialData.gender || "MALE").toUpperCase() as "MALE" | "FEMALE", spouseIds: initialData.spouseIds || [], childrenIds: initialData.childrenIds || [], tags: initialData.tags || [], fatherId: initialData.fatherId || undefined, motherId: initialData.motherId || undefined, } }) const [errors, setErrors] = useState([]) const handleChange = (field: keyof FamilyMember, value: any) => { setFormData((prev) => { const newData = { ...prev, [field]: value } // Auto-update full name if surname or given name changes if (field === "surname" || field === "givenName") { newData.fullName = (newData.surname || "") + (newData.givenName || "") } // 选择父亲时自动带出母亲 if (field === "fatherId" && value) { const father = existingMembers.find(m => m.id === value) if (father && father.spouseIds && father.spouseIds.length > 0) { // 找到父亲的配偶(母亲) const motherId = father.spouseIds[0] newData.motherId = motherId } } // 选择母亲时自动带出父亲 if (field === "motherId" && value) { const mother = existingMembers.find(m => m.id === value) if (mother && mother.spouseIds && mother.spouseIds.length > 0) { // 找到母亲的配偶(父亲) const fatherId = mother.spouseIds[0] newData.fatherId = fatherId } } return newData }) // Clear errors when user makes changes if (errors.length > 0) setErrors([]) } const handleSpouseAdd = (spouseId: string) => { if (!spouseId || spouseId === "none") return setFormData((prev) => { const currentSpouses = prev.spouseIds || [] // 避免重复添加 if (currentSpouses.includes(spouseId)) return prev return { ...prev, spouseIds: [...currentSpouses, spouseId] } }) } const handleSpouseRemove = (spouseId: string) => { setFormData((prev) => ({ ...prev, spouseIds: (prev.spouseIds || []).filter(id => id !== spouseId) })) } const handleChildAdd = (childId: string) => { if (!childId || childId === "none") return setFormData((prev) => { const currentChildren = prev.childrenIds || [] // 避免重复添加 if (currentChildren.includes(childId)) return prev return { ...prev, childrenIds: [...currentChildren, childId] } }) } const handleChildRemove = (childId: string) => { setFormData((prev) => ({ ...prev, childrenIds: (prev.childrenIds || []).filter(id => id !== childId) })) } const validate = (): boolean => { const newErrors: string[] = [] // 1. Date Validation if (formData.birthDate && formData.deathDate) { if (new Date(formData.birthDate) > new Date(formData.deathDate)) { newErrors.push("出生日期不能晚于逝世日期") } } // 2. Parent Age Validation const birthYear = formData.birthDate ? new Date(formData.birthDate).getFullYear() : null if (birthYear) { if (formData.fatherId) { const father = existingMembers.find((m) => m.id === formData.fatherId) if (father?.birthDate) { const fatherBirthYear = new Date(father.birthDate).getFullYear() if (birthYear - fatherBirthYear < 15) { newErrors.push(`与父亲的年龄差过小 (${birthYear - fatherBirthYear}岁),请确认`) } if (birthYear < fatherBirthYear) { newErrors.push("出生日期不能早于父亲") } } } if (formData.motherId) { const mother = existingMembers.find((m) => m.id === formData.motherId) if (mother?.birthDate) { const motherBirthYear = new Date(mother.birthDate).getFullYear() if (birthYear - motherBirthYear < 15) { newErrors.push(`与母亲的年龄差过小 (${birthYear - motherBirthYear}岁),请确认`) } if (birthYear < motherBirthYear) { newErrors.push("出生日期不能早于母亲") } } } } // 3. Generation Validation if (formData.fatherId) { const father = existingMembers.find((m) => m.id === formData.fatherId) if (father && formData.generation !== father.generation + 1) { newErrors.push(`世系错误:父亲是第 ${father.generation} 世,子女应为第 ${father.generation + 1} 世`) } } // 4. Circular Reference Detection (循环引用检测) if (formData.fatherId || formData.motherId) { const visited = new Set() const checkCircular = (memberId: string): boolean => { if (memberId === formData.id) return true if (visited.has(memberId)) return false visited.add(memberId) const member = existingMembers.find((m) => m.id === memberId) if (!member) return false if (member.fatherId && checkCircular(member.fatherId)) return true if (member.motherId && checkCircular(member.motherId)) return true return false } if (formData.fatherId && checkCircular(formData.fatherId)) { newErrors.push("检测到循环引用:不能将自己的后代设置为父亲") } if (formData.motherId && checkCircular(formData.motherId)) { newErrors.push("检测到循环引用:不能将自己的后代设置为母亲") } } // 5. Self-Reference Detection (自我引用检测) if (formData.fatherId === formData.id) { newErrors.push("不能将自己设置为自己的父亲") } if (formData.motherId === formData.id) { newErrors.push("不能将自己设置为自己的母亲") } if (formData.spouseIds?.includes(formData.id || "")) { newErrors.push("不能将自己设置为自己的配偶") } setErrors(newErrors) return newErrors.length === 0 } const handleSubmit = (e: React.FormEvent) => { e.preventDefault() if (validate()) { onSubmit(formData as FamilyMember) } } const potentialRelatives = existingMembers.filter((m) => m.id !== formData.id) return (
{errors.length > 0 && (

请检查以下问题:

    {errors.map((err, index) => (
  • {err}
  • ))}
)}
{/* 基本信息和家庭关系 - 两列布局 */}
{/* 左列:基本信息 */} 基本信息
handleChange("avatarUrl", imageUrl || null)} />
handleChange("surname", e.target.value)} />
handleChange("givenName", e.target.value)} />
handleChange("generation", Number.parseInt(e.target.value))} />
{/* 右列:家庭关系 */} 家庭关系
{isFounder ? ( handleChange("spouseFatherName", e.target.value)} /> ) : (
{!formData.fatherId && ( handleChange("spouseFatherName", e.target.value)} className="flex-1" /> )}
)}
{isFounder ? ( handleChange("spouseMotherName", e.target.value)} /> ) : (
{!formData.motherId && ( handleChange("spouseMotherName", e.target.value)} className="flex-1" /> )}
)}
{/* 已选配偶列表 */} {formData.spouseIds && formData.spouseIds.length > 0 && (
{formData.spouseIds.map((spouseId, index) => { const spouse = existingMembers.find(m => m.id === spouseId) if (!spouse) return null return (
{index + 1}. (第{spouse.generation}世)
) })}
)}
{/* 已选子女列表 */} {formData.childrenIds && formData.childrenIds.length > 0 && (
{formData.childrenIds.map((childId, index) => { const child = existingMembers.find(m => m.id === childId) if (!child) return null return (
{index + 1}. (第{child.generation}世)
) })}
)}
{/* Traditional Names */} 传统称谓
handleChange("courtesyName", e.target.value)} placeholder="例如:伯虎" />
handleChange("artName", e.target.value)} placeholder="例如:六如居士" />
handleChange("generationName", e.target.value)} />
handleChange("posthumousName", e.target.value)} />
{/* Dates & Places */} 生平与地点
handleChange("birthDate", value)} showLunarToggle={false} /> handleChange("deathDate", value)} showLunarToggle={false} />
{/* 统一的公历/农历选择 */} {(formData.birthDate || formData.deathDate) && (
handleChange("isLunarDate", val === "lunar")} className="flex flex-row gap-6" >

{formData.isLunarDate ? "💡 将按农历日期计算每年的纪念日,如生日、祭日等" : "💡 将按公历日期计算每年的纪念日"}

)}
handleChange("ancestralHome", e.target.value)} placeholder="例如:福建省泉州市" />
handleChange("burialPlace", e.target.value)} />
{/* Contact Information */} 联系方式 在世成员的联系方式
handleChange("phone", e.target.value)} placeholder="例如:13800138000" />
handleChange("telephone", e.target.value)} placeholder="例如:0592-1234567" />
handleChange("email", e.target.value)} placeholder="例如:example@email.com" />
handleChange("address", e.target.value)} placeholder="例如:福建省厦门市思明区XX路XX号" />
{/* Biography */} 生平事迹