gongxiangp2/components/performance-survey-attachments.tsx

210 lines
7.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use client'
import { useEffect, useState } from 'react'
import type { PerformanceCaseAttachment } from '@/lib/performance-survey-attachment-contract'
type RequestData = <T>(path: string, options?: RequestInit) => Promise<T>
const previewStatus: Record<string, string> = {
queued: '等待生成预览',
processing: '正在生成预览',
ready: '预览已就绪',
failed: '预览生成失败',
}
const actionClass = 'inline-flex min-h-11 items-center rounded-md px-3 text-sm font-medium text-[#0050cb] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50'
const pageButtonClass = `${actionClass} border border-[#d9e0ea]`
function DocumentPreview({ attachment, fileUrl }: { attachment: PerformanceCaseAttachment; fileUrl: string }) {
const [page, setPage] = useState(1)
const [imageFailed, setImageFailed] = useState(false)
const previewPageCount = attachment.previewPageCount || 1
const goToPage = (next: number) => {
if (!Number.isInteger(next) || next < 1 || next > previewPageCount) return
setPage(next)
setImageFailed(false)
}
return (
<>
<div className="flex flex-wrap items-center gap-3 py-2">
<button type="button" disabled={page <= 1} onClick={() => goToPage(page - 1)} className={pageButtonClass}>
上一页
</button>
<label className="flex items-center gap-2 text-sm">
页码
<select
aria-label="页码"
value={page}
onChange={(event) => goToPage(Number(event.target.value))}
className="h-11 rounded-md border border-[#d9e0ea] px-2"
>
{Array.from({ length: previewPageCount }, (_, index) => (
<option key={index + 1} value={index + 1}>{index + 1}</option>
))}
</select>
<span>/ {previewPageCount}</span>
</label>
<button type="button" disabled={page >= previewPageCount} onClick={() => goToPage(page + 1)} className={pageButtonClass}>
下一页
</button>
</div>
{(attachment.pageCount || 0) > previewPageCount && (
<p className="mb-2 text-sm text-[#667085]">
共{attachment.pageCount}页,预览前{previewPageCount}页。下载原件可查看完整内容。
</p>
)}
{imageFailed ? (
<div className="py-2 text-sm text-[#b42318]">
<p role="alert">预览页读取失败</p>
<button type="button" className={actionClass} onClick={() => setImageFailed(false)}>重新读取</button>
</div>
) : (
<img
key={page}
src={`${fileUrl}?variant=page&page=${page}`}
alt={`${attachment.originalName} 第${page}页`}
loading="lazy"
className="h-auto w-full border border-[#e5eaf2]"
onError={() => setImageFailed(true)}
/>
)}
</>
)
}
function AttachmentPreview({ initial, request }: { initial: PerformanceCaseAttachment; request: RequestData }) {
const [attachment, setAttachment] = useState(initial)
const [open, setOpen] = useState(false)
const [error, setError] = useState<string | null>(null)
const [retrying, setRetrying] = useState(false)
const [videoAttempt, setVideoAttempt] = useState(0)
const endpoint = `/case-attachments/${attachment.id}`
const fileUrl = `/api/performance-survey${endpoint}/file`
const panelId = `attachment-${attachment.id}`
const pending = attachment.status === 'queued' || attachment.status === 'processing'
const status = previewStatus[attachment.status] || '读取预览状态'
useEffect(() => { setAttachment(initial) }, [initial])
useEffect(() => {
if (!open || !pending) return
const controller = new AbortController()
let timer: ReturnType<typeof setTimeout>
const refresh = async () => {
try {
const next = await request<PerformanceCaseAttachment>(endpoint, { signal: controller.signal })
if (controller.signal.aborted) return
setAttachment(next)
setError(null)
} catch (failure) {
if (controller.signal.aborted) return
setError(failure instanceof Error ? failure.message : '读取预览状态失败')
}
timer = setTimeout(refresh, 4000)
}
void refresh()
return () => {
controller.abort()
clearTimeout(timer)
}
}, [open, pending, endpoint, request])
const retry = async () => {
setRetrying(true)
setError(null)
try {
const next = await request<PerformanceCaseAttachment>(`${endpoint}/retry`, { method: 'POST' })
setAttachment(next)
} catch (failure) {
setError(failure instanceof Error ? failure.message : '重试失败')
} finally {
setRetrying(false)
}
}
return (
<section className="min-w-0 border-t border-[#e5eaf2] py-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0 flex-1">
<h3 className="break-all text-sm font-semibold text-[#111827]">{attachment.originalName}</h3>
<p className="mt-1 text-xs text-[#667085]">
{attachment.kind === 'video' ? '视频' : '文档'} · {(attachment.size / 1024 / 1024).toFixed(1)} MB · {status}
</p>
</div>
<a href={fileUrl} className={`${actionClass} underline underline-offset-4`}>下载原件</a>
</div>
<button
type="button"
aria-expanded={open}
aria-controls={panelId}
onClick={() => setOpen(!open)}
className={actionClass}
>
{open ? '收起预览' : '展开预览'}
</button>
<div id={panelId} hidden={!open} className="min-w-0">
{open && (
<>
{pending && (
<p role="status" className="py-3 text-sm text-[#667085]">{status},原件已保存。</p>
)}
{attachment.status === 'failed' && (
<div className="py-2 text-sm">
<p className="break-words text-[#b42318]">{attachment.error || '预览生成失败'}。可下载原件查看。</p>
<button type="button" disabled={retrying} onClick={retry} className={`mt-2 ${pageButtonClass}`}>
{retrying ? '正在重试…' : '重新生成预览'}
</button>
</div>
)}
{error && <p role="alert" className="py-2 text-sm text-[#b42318]">{error}</p>}
{attachment.status === 'ready' && attachment.kind === 'video' && (
<>
<video
key={videoAttempt}
controls
playsInline
preload="metadata"
className="max-h-[70vh] w-full rounded-lg bg-black"
src={`${fileUrl}?variant=video`}
aria-label={attachment.originalName}
onError={() => setError('视频暂时无法播放,可重试或下载原件')}
/>
{error && (
<button
type="button"
className={actionClass}
onClick={() => { setError(null); setVideoAttempt((current) => current + 1) }}
>
重新读取
</button>
)}
</>
)}
{attachment.status === 'ready' && attachment.kind === 'document' && (
<DocumentPreview attachment={attachment} fileUrl={fileUrl} />
)}
</>
)}
</div>
</section>
)
}
export function PerformanceSurveyAttachments({
attachments = [],
request,
}: {
attachments?: PerformanceCaseAttachment[]
request: RequestData
}) {
if (!attachments.length) return null
return (
<div className="mt-3 min-w-0">
{attachments.map((attachment) => (
<AttachmentPreview key={attachment.id} initial={attachment} request={request} />
))}
</div>
)
}