'use client' import { useEffect, useMemo, useState } from 'react' import Image from 'next/image' export interface ViewerAssetItem { id: string fileName: string fileUrl: string fileKind: 'pdf' | 'image' } interface DocumentAssetViewerProps { title: string items: ViewerAssetItem[] } function formatLabel(fileName: string, index: number): string { const normalized = String(fileName || '').trim() return normalized || `文件 ${index + 1}` } export default function DocumentAssetViewer({ title, items }: DocumentAssetViewerProps) { const normalizedItems = useMemo( () => items .filter((item) => item.fileUrl) .map((item, index) => ({ ...item, fileName: formatLabel(item.fileName, index), })), [items], ) const [selectedId, setSelectedId] = useState(normalizedItems[0]?.id || '') useEffect(() => { setSelectedId(normalizedItems[0]?.id || '') }, [normalizedItems]) const selectedItem = normalizedItems.find((item) => item.id === selectedId) || normalizedItems[0] const handleOpenFile = () => { if (!selectedItem?.fileUrl) { return } window.open(selectedItem.fileUrl, '_blank', 'noopener,noreferrer') } const handleDownloadFile = async () => { if (!selectedItem?.fileUrl) { return } try { const response = await fetch(selectedItem.fileUrl) if (!response.ok) { throw new Error('文件下载失败') } const blob = await response.blob() const objectUrl = URL.createObjectURL(blob) const anchor = document.createElement('a') anchor.href = objectUrl anchor.download = selectedItem.fileName document.body.appendChild(anchor) anchor.click() document.body.removeChild(anchor) URL.revokeObjectURL(objectUrl) } catch (error) { console.error('[DocumentAssetViewer] 下载失败,改为直接打开原文件:', error) window.open(selectedItem.fileUrl, '_blank', 'noopener,noreferrer') } } if (!selectedItem) { return (