import { useState, useEffect, useRef, useCallback } from 'react'; import { Droplets, Eraser, Loader2, X, Play, Square, CheckCircle2, AlertTriangle, Save, FileEdit, Eye } from 'lucide-react'; import { batchAPI, imageAPI } from '../api'; /** * 批量水印弹窗(文件夹级) * mode='add' 批量加水印:文字水印(九宫格单个 / 平铺) * mode='remove' 批量去水印:按百分比区域生成 mask → 后端 LaMa inpaint * * 流程:配置 → 启动任务(立即返回 taskId)→ 1s 轮询进度 → 完成/取消 */ // 九宫格位置(与后端 makeWatermarkSvg 的 pos 规则一致) const POSITIONS = [ ['top-left', 'top-center', 'top-right'], ['middle-left', 'middle-center', 'middle-right'], ['bottom-left', 'bottom-center', 'bottom-right'] ]; const POSITION_LABEL = { 'top-left': '左上', 'top-center': '顶部', 'top-right': '右上', 'middle-left': '左侧', 'middle-center': '居中', 'middle-right': '右侧', 'bottom-left': '左下', 'bottom-center': '底部', 'bottom-right': '右下' }; // 去水印预设区域(百分比) const REGION_PRESETS = [ { key: 'bottom-right', label: '右下角', region: { x: 68, y: 86, w: 30, h: 11 } }, { key: 'bottom-left', label: '左下角', region: { x: 2, y: 86, w: 30, h: 11 } }, { key: 'top-right', label: '右上角', region: { x: 68, y: 3, w: 30, h: 11 } }, { key: 'top-left', label: '左上角', region: { x: 2, y: 3, w: 30, h: 11 } }, { key: 'center', label: '画面居中', region: { x: 35, y: 42, w: 30, h: 16 } }, { key: 'bottom-bar', label: '底部横条', region: { x: 0, y: 88, w: 100, h: 11 } }, { key: 'right-bar', label: '右侧竖条', region: { x: 85, y: 0, w: 15, h: 100 } }, { key: 'custom', label: '自定义', region: null } ]; const clampPct = (v) => Math.max(0, Math.min(100, Number(v) || 0)); function Field({ label, children, hint }) { return (
{label}
{children} {hint &&
{hint}
}
); } function Slider({ value, onChange, min, max, step = 1, suffix = '' }) { return (
onChange(Number(e.target.value))} /> {value}{suffix}
); } function BatchWatermarkModal({ isOpen, mode, folder, libraryId, onClose, onFinished }) { const [phase, setPhase] = useState('config'); // config | running | done const [imageCount, setImageCount] = useState(0); const [starting, setStarting] = useState(false); const [error, setError] = useState(''); // 加水印配置 const [text, setText] = useState(''); const [tile, setTile] = useState(false); const [position, setPosition] = useState('bottom-right'); const [fontSizePct, setFontSizePct] = useState(4); const [opacity, setOpacity] = useState(50); const [color, setColor] = useState('#ffffff'); const [marginPct, setMarginPct] = useState(2); const [rotate, setRotate] = useState(-30); const [stroke, setStroke] = useState(true); // 去水印配置 const [presetKey, setPresetKey] = useState('bottom-right'); const [region, setRegion] = useState({ x: 68, y: 86, w: 30, h: 11 }); // 输出方式 const [output, setOutput] = useState('overwrite'); // 任务进度 const [taskId, setTaskId] = useState(null); const [progress, setProgress] = useState(null); const pollRef = useRef(null); // 打开时重置 + 取图片数 useEffect(() => { if (!isOpen) return; setPhase('config'); setError(''); setTaskId(null); setProgress(null); setStarting(false); setOutput('overwrite'); if (mode === 'remove') { setPresetKey('bottom-right'); setRegion({ x: 68, y: 86, w: 30, h: 11 }); } let cancelled = false; (async () => { try { const resp = await imageAPI.getCount(libraryId, { folder }); if (!cancelled) setImageCount(resp.count ?? 0); } catch (_) { if (!cancelled) setImageCount(0); } })(); return () => { cancelled = true; }; }, [isOpen, mode, folder, libraryId]); // 停止轮询 const stopPolling = useCallback(() => { if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; } }, []); useEffect(() => stopPolling, [stopPolling]); const startPolling = useCallback((id) => { stopPolling(); pollRef.current = setInterval(async () => { try { const s = await batchAPI.status(id); setProgress(s); if (s.status !== 'running') { stopPolling(); setPhase('done'); onFinished?.(s); } } catch (_) { /* 网络抖动,继续轮询 */ } }, 1000); }, [stopPolling, onFinished]); const handleStart = async () => { setError(''); if (mode === 'add' && !text.trim()) { setError('请输入水印文字'); return; } setStarting(true); try { const payload = { libraryId, folder, type: mode, output }; payload.options = mode === 'add' ? { text: text.trim(), tile, position, fontSizePct, opacity, color, marginPct, rotate, stroke } : { region }; const resp = await batchAPI.start(payload); setTaskId(resp.taskId); setPhase('running'); setProgress({ status: 'running', total: resp.total, done: 0, failed: 0, skipped: 0, current: '', errors: [] }); startPolling(resp.taskId); } catch (err) { setError(err?.message || '启动失败'); } finally { setStarting(false); } }; const handleCancel = async () => { if (!taskId) return; try { await batchAPI.cancel(taskId); } catch (_) { /* 任务可能已结束 */ } stopPolling(); setPhase('done'); }; const handleClose = () => { stopPolling(); onClose(); }; if (!isOpen) return null; const isAdd = mode === 'add'; const title = isAdd ? '批量加水印' : '批量去水印'; const Icon = isAdd ? Droplets : Eraser; const accent = isAdd ? 'text-blue-500' : 'text-emerald-500'; const accentBtn = isAdd ? 'bg-blue-500 hover:bg-blue-600' : 'bg-emerald-500 hover:bg-emerald-600'; const pct = progress && progress.total > 0 ? Math.round(((progress.done + progress.failed + progress.skipped) / progress.total) * 100) : 0; return (
e.stopPropagation()} > {/* 头部 */}

{title}

{folder} {imageCount} 个文件
{/* 内容 */}
{phase === 'config' && ( <> {isAdd ? ( <> setText(e.target.value)} placeholder="例如:素材室出品" maxLength={50} className="w-full px-3 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
{!tile && (
{POSITIONS.flat().map((pos) => ( ))}
)}
setColor(e.target.value)} className="w-9 h-9 rounded cursor-pointer border border-gray-300 dark:border-gray-600 bg-transparent" /> {['#ffffff', '#000000', '#ff3b30', '#ffd60a'].map((c) => (
) : ( <>
{REGION_PRESETS.map((p) => ( ))}
{/* 区域示意 */}
{[['x', '左边距'], ['y', '上边距'], ['w', '宽度'], ['h', '高度']].map(([k, lb]) => ( ))}
修复区域内的所有内容都会被抹除重建(包括文字、logo、图案)。水印位置在整批图片中不一致时请分批处理,或用编辑器单张涂抹。
)} {/* 输出方式 */}
{output === 'overwrite' ? '原图将被替换(缩略图与索引同步更新)' : isAdd ? '生成 新图名_wm.jpg 保留原图' : '生成 新图名_nowm.jpg 保留原图'}
{error && (
{error}
)} )} {(phase === 'running' || phase === 'done') && progress && (
{/* 状态 */}
{phase === 'running' ? ( ) : progress.failed > 0 ? ( ) : ( )}
{phase === 'running' ? (isAdd ? '正在加水印…' : '正在去水印…(AI 修复较慢,请耐心等待)') : progress.status === 'cancelled' ? '已取消' : progress.status === 'error' ? '任务异常终止' : '处理完成'}
{phase === 'running' && progress.current ? progress.current : `成功 ${progress.done} · 失败 ${progress.failed}${progress.skipped ? ` · 跳过 ${progress.skipped}` : ''} / 共 ${progress.total}`}
{progress.done + progress.failed + progress.skipped}/{progress.total}
{/* 进度条 */}
0 && phase === 'done' ? 'bg-amber-500' : isAdd ? 'bg-blue-500' : 'bg-emerald-500'}`} style={{ width: `${pct}%` }} />
{/* 统计 */}
{[ ['成功', progress.done, 'text-emerald-600 dark:text-emerald-400'], ['失败', progress.failed, progress.failed ? 'text-red-500' : 'text-gray-500'], ['跳过', progress.skipped, 'text-gray-500'] ].map(([lb, v, cls]) => (
{v}
{lb}
))}
{/* 错误明细 */} {progress.errors && progress.errors.length > 0 && (
失败明细(最多记录 20 条)
{progress.errors.map((e, i) => (
{e.path || '(全局)'} — {e.error}
))}
)}
)}
{/* 底部按钮 */}
{phase === 'config' && ( <> )} {phase === 'running' && ( )} {phase === 'done' && ( <> )}
); } export default BatchWatermarkModal;