"use client" import { useState, useEffect } from "react" import { Button } from "@/components/ui/button" import { Card } from "@/components/ui/card" import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog" import { X, Upload, Image as ImageIcon, Plus, ZoomIn } from "lucide-react" import { useDialog } from "@/components/ui/alert-dialog-custom" import imageCompression from "browser-image-compression" interface PhotoGalleryProps { photoIds?: string[] onChange: (photoIds: string[]) => void readonly?: boolean } export function PhotoGallery({ photoIds = [], onChange, readonly = false }: PhotoGalleryProps) { const { showAlert, showConfirm } = useDialog() const [photos, setPhotos] = useState<{ id: string; url: string }[]>([]) const [selectedPhoto, setSelectedPhoto] = useState(null) const [isUploading, setIsUploading] = useState(false) // 加载照片 useEffect(() => { // photoIds 现在直接是 URL 数组 const loadedPhotos = photoIds.map((url) => ({ id: url, url })) setPhotos(loadedPhotos) }, [photoIds]) const handleUpload = async (e: React.ChangeEvent) => { const files = e.target.files if (!files || files.length === 0) return setIsUploading(true) try { const newPhotoIds: string[] = [] for (const file of Array.from(files)) { if (!file.type.startsWith('image/')) continue // 压缩图片 const options = { maxSizeMB: 2, maxWidthOrHeight: 1920, useWebWorker: true, } const compressedFile = await imageCompression(file, options) // 上传到服务器 const formData = new FormData() formData.append('file', compressedFile) const response = await fetch('/api/upload', { method: 'POST', body: formData, }) if (!response.ok) { throw new Error('上传失败') } const { url } = await response.json() newPhotoIds.push(url) } // 更新照片列表 onChange([...photoIds, ...newPhotoIds]) } catch (error) { console.error('上传照片失败:', error) await showAlert('上传照片失败', '错误') } finally { setIsUploading(false) e.target.value = '' } } const handleDelete = async (photoId: string) => { const confirmed = await showConfirm('确定要删除这张照片吗?', '删除照片') if (confirmed) { onChange(photoIds.filter(id => id !== photoId)) } } return (

照片墙 ({photos.length})

{!readonly && ( )}
{photos.length > 0 ? (
{photos.map((photo) => (
家族照片 setSelectedPhoto(photo.url)} /> {!readonly && ( )}
))}
) : (
暂无照片
)} {/* 照片预览对话框 */} setSelectedPhoto(null)}> 照片预览 {selectedPhoto && ( 照片预览 )}
) }