/** * 04 图片与 AI 生图(docs/v2.1/image-suite.md): * 采集图片(分组勾选/上传/单张AI生图) + 出图方案(AI规划/风格/要求/模型/一键生成) + 生成结果(导出 ZIP)。 * 交互对齐 image-suite-studio 面板 02/03/04 区块;套图服务端接口 Phase B 提供。 */ import { useEffect, useMemo, useRef, useState, type CSSProperties } from 'react'; import { Alert, App as AntdApp, Button, Card, Checkbox, Col, Empty, Image, Input, InputNumber, Popconfirm, Popover, Progress, Radio, Row, Segmented, Select, Space, Tag, Typography, Upload, } from 'antd'; import { DownloadOutlined, SettingOutlined, ThunderboltOutlined, UploadOutlined } from '@ant-design/icons'; import { ProductAsset, ProductDetail } from '@/services/product'; import { apiErrorMessage } from '@/services/api'; import { DEFAULT_IMAGE_MODEL, DEFAULT_PLAN, DEFAULT_WATERMARK, IMAGE_MODEL_OPTIONS, STYLE_SET_OPTIONS, SuiteInfo, SuiteTextPayload, WatermarkPayload, deleteAsset, downloadSuiteZip, exportImages, generateSuite, getSuite, planSuite, uploadProductAsset, type PlanItem, } from '@/services/suite'; import { cleanFilename, downloadBlob } from '@/utils/file'; import AiImageGenModal from './AiImageGenModal'; const { Text } = Typography; const GROUP_LABELS: Record = { main: '主图', sku: 'SKU 图', detail: '详情图', generated: '生成图', upload: '手动上传', param: '参数图', video: '视频', }; const DISPLAY_GROUPS = ['main', 'sku', 'detail', 'generated', 'upload']; const WATERMARK_STORAGE_KEY = 'trialWatermark'; /** 方案数量步进器:左减号 / 中间可输入 / 右加号(0-5) */ function PlanStepper({ value, onChange }: { value: number; onChange: (v: number) => void }) { const [text, setText] = useState(String(value)); useEffect(() => setText(String(value)), [value]); const clamp = (v: number) => Math.max(0, Math.min(5, Number.isNaN(v) ? 0 : v)); const commit = () => onChange(clamp(parseInt(text, 10))); const btnBase: CSSProperties = { width: 26, height: 26, padding: 0, border: 'none', background: '#f5f5f5', cursor: 'pointer', fontSize: 15, lineHeight: '26px', color: '#555', }; return ( setText(e.target.value.replace(/[^\d]/g, ''))} onBlur={commit} onKeyDown={(e) => e.key === 'Enter' && (e.target as HTMLInputElement).blur()} title="可直接输入数量(0-5)" style={{ width: 34, height: 26, textAlign: 'center', border: 'none', outline: 'none', fontSize: 13, fontWeight: 600, color: value === 0 ? '#bbb' : '#333', background: '#fff', }} /> ); } interface Props { product: ProductDetail; assets: ProductAsset[]; onRefreshAssets: () => void; } /** 商品信息 → 规划/生成的文本素材(包装字段覆盖回参数表,对齐 image-suite-studio editedTexts) */ function buildSuiteTexts(product: ProductDetail): SuiteTextPayload[] { const raw = (product.raw ?? {}) as Record; const texts: SuiteTextPayload[] = []; const title = ((raw.title_zh as string) ?? (raw.title as string) ?? '').trim(); if (title) texts.push({ kind: 'title', content: title }); if (raw.price) texts.push({ kind: 'price', content: String(raw.price) }); (['brand', 'sales', 'shop'] as const).forEach((k) => { const v = raw[k]; if (v) texts.push({ kind: k, content: String(v) }); }); const sellingPoint = (raw.selling_point as string) ?? (raw.sellingPoints as string); if (sellingPoint) texts.push({ kind: 'selling_point', content: sellingPoint }); let pairs = Array.isArray(raw.params) ? [...(raw.params as Array<{ key: string; value: string }>)] : []; pairs = pairs.filter((p) => !/尺寸|长宽高|重量/i.test(p.key)); if (product.weight != null && product.weight > 0) pairs.push({ key: '重量', value: `${product.weight}g` }); const scale = product.dimension_unit === 'cm' ? 1 : 0.1; if (product.depth != null && product.width != null && product.height != null) { const d = { l: product.depth * scale, w: product.width * scale, h: product.height * scale }; pairs.push({ key: '产品尺寸', value: `${d.l}×${d.w}×${d.h}` }); } if (pairs.length) texts.push({ kind: 'params', content: '', pairs }); if (raw.desc) texts.push({ kind: 'desc', content: String(raw.desc) }); return texts; } function loadWatermark(): WatermarkPayload { try { const s = localStorage.getItem(WATERMARK_STORAGE_KEY); if (s) return { ...DEFAULT_WATERMARK, ...(JSON.parse(s) as WatermarkPayload) }; } catch { /* 忽略坏数据 */ } return DEFAULT_WATERMARK; } export default function TrialSuitePanel({ product, assets, onRefreshAssets }: Props) { // message / modal 用 App 上下文版本:静态方法吃不到 ConfigProvider 动态主题(控制台告警) const { modal, message } = AntdApp.useApp(); // 素材选择(默认全部不勾选,用户按需勾选参考底图;SKU 规格名供 AI 规划 variant 绑定,与勾选无关) const [selectedKeys, setSelectedKeys] = useState>(() => new Set()); /** 上传成功待自动勾选的 asset id */ const pendingSelectRef = useRef>(new Set()); const [uploadingCount, setUploadingCount] = useState(0); // 出图方案 const [plan, setPlan] = useState(DEFAULT_PLAN.map((p) => ({ ...p }))); const [planSource, setPlanSource] = useState<'default' | 'ai'>('default'); const [planSummary, setPlanSummary] = useState(''); const [planning, setPlanning] = useState(false); const [planThenGenerate, setPlanThenGenerate] = useState(false); const [styleSet, setStyleSet] = useState(1); const [stylePrompts, setStylePrompts] = useState>({}); const [requirements, setRequirements] = useState(''); const [model, setModel] = useState(DEFAULT_IMAGE_MODEL); const [watermark, setWatermark] = useState(loadWatermark); // 生成 const [suite, setSuite] = useState(null); const [generating, setGenerating] = useState(false); const [exportingZip, setExportingZip] = useState(false); const [exportingResult, setExportingResult] = useState(false); const [exportingImages, setExportingImages] = useState(false); const pollRef = useRef | null>(null); /** 规划请求序号:重置后丢弃迟到的过期响应 */ const planSeqRef = useRef(0); // 单张 AI 生图弹窗(afterAssetId:结果插到该素材之后,方便对比) const [genModal, setGenModal] = useState<{ url: string; name: string; afterAssetId?: string } | null>(null); // 采集图片卡只放采集/上传素材;单张 AI 生图结果(generated)放「生成结果」卡展示 const imgs = useMemo(() => assets.filter((a) => a.type !== 'video' && a.group_key !== 'generated'), [assets]); const generatedAssets = useMemo(() => assets.filter((a) => a.group_key === 'generated'), [assets]); const groupImages = (g: string) => imgs.filter((a) => a.group_key === g); const assetUrl = (a: ProductAsset) => a.stored_url || a.source_url; // 图名:取 URL 路径末段(采集图为源站文件名;上传图为落盘文件名),无路径时回退规格名 const assetName = (a: ProductAsset): string => { const raw = a.source_url || a.stored_url || ''; try { const seg = decodeURIComponent(new URL(raw, window.location.origin).pathname.split('/').pop() || ''); return seg || a.variant_name || '未命名'; } catch { return a.variant_name || '未命名'; } }; const rawObj = (product.raw ?? {}) as Record; const productTitle = ((rawObj.title_zh as string) || (rawObj.title as string) || product.name || '').trim(); // 上传完成的素材自动勾选(素材列表刷新后合并) useEffect(() => { if (pendingSelectRef.current.size === 0) return; const next = new Set(selectedKeys); let touched = false; pendingSelectRef.current.forEach((id) => { if (assets.some((a) => a.id === id) && !next.has(id)) { next.add(id); touched = true; } }); pendingSelectRef.current.clear(); if (touched) setSelectedKeys(next); // eslint-disable-next-line react-hooks/exhaustive-deps }, [assets]); // 组件卸载停止轮询 useEffect(() => () => { if (pollRef.current) clearInterval(pollRef.current); }, []); const stopPolling = () => { if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null; } }; const toggleKey = (key: string) => { setSelectedKeys((prev) => { const next = new Set(prev); if (next.has(key)) next.delete(key); else next.add(key); return next; }); }; const toggleGroup = (g: string, on: boolean) => { setSelectedKeys((prev) => { const next = new Set(prev); groupImages(g).forEach((a) => (on ? next.add(a.id) : next.delete(a.id))); return next; }); }; const uploadButton = ( { setUploadingCount((c) => c + 1); try { const r = await uploadProductAsset(product.id, file as File); pendingSelectRef.current.add(r.asset_id); onSuccess?.(r); } catch (e) { message.error(`${(file as File).name}:${apiErrorMessage(e)}`); onError?.(e as Error); } finally { setUploadingCount((c) => c - 1); onRefreshAssets(); } }} > ); // ── 下载采集图片(勾选图打包 ZIP) ───────────────────────────── const handleExportImages = async () => { const selected = imgs.filter((a) => selectedKeys.has(a.id)); if (selected.length === 0) { message.warning('请先勾选要下载的图片'); return; } setExportingImages(true); try { const blob = await exportImages({ title: productTitle, images: selected.map((a) => ({ url: assetUrl(a), groupName: GROUP_LABELS[a.group_key] ?? a.group_key, variantName: a.variant_name, key: a.id, })), }); downloadBlob(blob, `${cleanFilename(productTitle) || '采集图片'}.zip`); } catch (e) { message.error(apiErrorMessage(e)); } finally { setExportingImages(false); } }; // ── AI 智能规划 ───────────────────────────────────────────── const currentStylePrompt = stylePrompts[styleSet] ?? STYLE_SET_OPTIONS.find((s) => s.value === styleSet)?.prompt ?? ''; const totalPlanned = plan.reduce((s, i) => s + i.count, 0); const pollSuite = (suiteId: string) => { stopPolling(); const startedAt = Date.now(); let failCount = 0; let timeoutWarned = false; pollRef.current = setInterval(async () => { try { const s = await getSuite(suiteId); setSuite(s); failCount = 0; // 超时兜底:单张最长约 5 分钟,超预算仍 running 多半是任务已中断 const budgetMs = ((s.total ?? 1) * 5 + 10) * 60_000; if (!timeoutWarned && ['running', 'pending'].includes(s.status) && Date.now() - startedAt > budgetMs) { timeoutWarned = true; message.warning('任务耗时异常,可能已中断(如服务端重启),可稍后观察或重新生成'); } if (['done', 'partial', 'failed'].includes(s.status)) { stopPolling(); setGenerating(false); if (s.status === 'partial') message.warning(s.error || '部分生成失败,可重试或更换风格重新生成'); if (s.status === 'failed') message.error(s.error || '生成失败'); // Phase B 起服务端会把生成图回写素材(generated 组) if (s.status !== 'failed') onRefreshAssets(); } } catch { failCount += 1; if (failCount >= 3) { stopPolling(); setGenerating(false); message.error('连续查询生成进度失败,已停止跟踪;若服务端刚重启,请重新生成'); } } }, 3000); }; const startGenerate = async (planOverride?: PlanItem[]): Promise => { if (selectedKeys.size === 0) { message.warning('请先在采集图片区勾选参考底图'); return; } const activePlan = (planOverride ?? plan).filter((p) => p.count > 0); if (activePlan.length === 0) { message.warning('出图方案的张数都是 0'); return; } setGenerating(true); setSuite(null); try { const { suite_id } = await generateSuite({ product_id: product.id, texts: buildSuiteTexts(product), images: imgs .filter((a) => selectedKeys.has(a.id)) .map((a) => ({ url: assetUrl(a), group_key: a.group_key, variant_name: a.variant_name })), style_set: styleSet, style_prompt: currentStylePrompt || null, requirements: requirements.trim() || null, plan: activePlan, platform: 'ozon', model, // 水印开启才下发,关闭时不带(服务端按无水印处理) watermark: watermark.enabled ? watermark : undefined, }); pollSuite(suite_id); } catch (e) { setGenerating(false); message.error(apiErrorMessage(e)); } }; const handlePlan = async () => { const seq = ++planSeqRef.current; setPlanning(true); try { const skuVariants = Array.from( new Set(assets.filter((a) => a.group_key === 'sku' && a.variant_name).map((a) => a.variant_name!)), ); const stats: Record = {}; imgs.forEach((a) => { stats[a.group_key] = (stats[a.group_key] ?? 0) + 1; }); const data = await planSuite({ product_id: product.id, texts: buildSuiteTexts(product), sku_variants: skuVariants, image_stats: stats, platform: 'ozon', requirements: requirements.trim() || null, }); if (seq !== planSeqRef.current) return; // 已被重置,丢弃过期响应 setPlan(data.items); setPlanSource('ai'); setPlanSummary(data.summary); if (planThenGenerate) { await startGenerate(data.items); } else { const total = data.items.reduce((s, i) => s + i.count, 0); message.info(`AI 方案已生成:${data.summary}(共 ${total} 张)。可逐项调整数量,0 即不生成。`); } } catch (e) { if (seq !== planSeqRef.current) return; message.error(apiErrorMessage(e)); } finally { if (seq === planSeqRef.current) setPlanning(false); } }; const handleGenerate = () => { if (selectedKeys.size === 0) { message.warning('请先在采集图片区勾选参考底图'); return; } if (totalPlanned === 0) { message.warning('出图方案的张数都是 0'); return; } modal.confirm({ title: '生成电商套图', content: (
目标平台「Ozon」(俄文文案 · 3:4 图片),模型「{model}」,风格「 {STYLE_SET_OPTIONS.find((s) => s.value === styleSet)?.label}」,共 {totalPlanned} 张、参考底图{' '} {selectedKeys.size} 张。生成需要几分钟,可在下方查看进度。
), okText: '开始生成', cancelText: '取消', onOk: () => startGenerate(), }); }; const handleExportZip = async () => { if (!suite) return; setExportingZip(true); try { const blob = await downloadSuiteZip(suite.id); downloadBlob(blob, `${cleanFilename(productTitle) || '套图'}.zip`); } catch (e) { message.error(apiErrorMessage(e)); } finally { setExportingZip(false); } }; // ── 导出全部生图结果(套图成功图 + 单张 AI 生图回写图,分组建文件夹) ── const handleExportResult = async () => { const suiteOk = (suite?.images ?? []).filter((i) => i.status === 'ok'); if (suiteOk.length === 0 && generatedAssets.length === 0) { message.warning('暂无生图结果可导出'); return; } setExportingResult(true); try { const images = [ ...suiteOk.map((img, i) => ({ url: img.url, groupName: '套图结果', variantName: null, key: `suite-${String(i + 1).padStart(3, '0')}`, })), ...generatedAssets.map((a, i) => ({ url: assetUrl(a), groupName: '单张生图', variantName: a.variant_name, key: `single-${String(i + 1).padStart(3, '0')}`, })), ]; const blob = await exportImages({ title: `${cleanFilename(productTitle) || '生图'}-生图结果`, images }); downloadBlob(blob, `${cleanFilename(productTitle) || '生图'}-生图结果.zip`); } catch (e) { message.error(apiErrorMessage(e)); } finally { setExportingResult(false); } }; const setPlanCount = (idx: number, count: number) => { setPlan((prev) => prev.map((p, i) => (i === idx ? { ...p, count } : p))); }; const togglePlanRow = (idx: number) => { setPlan((prev) => prev.map((p, i) => (i === idx ? { ...p, count: p.count > 0 ? 0 : 1 } : p))); }; const planAllEnabled = plan.every((p) => p.count >= 1); const togglePlanAll = (on: boolean) => { setPlan((prev) => prev.map((p) => (on ? { ...p, count: Math.max(p.count, 1) } : { ...p, count: 0 }))); }; const doneCount = suite?.images.filter((i) => i.status === 'ok').length ?? 0; const suiteTotal = suite?.total ?? totalPlanned; const patchWatermark = (patch: Partial) => { setWatermark((prev) => { const next = { ...prev, ...patch }; try { localStorage.setItem(WATERMARK_STORAGE_KEY, JSON.stringify(next)); } catch { /* 忽略存储失败 */ } return next; }); }; const watermarkPopup = (
patchWatermark({ enabled: e.target.checked })} > 生成图加水印 {watermark.enabled && ( <>
patchWatermark({ type: e.target.value })} options={[ { value: 'image', label: '图片徽章' }, { value: 'text', label: '文字' }, ]} />
{watermark.type === 'text' && ( patchWatermark({ text: e.target.value })} /> )}
不透明度(%) patchWatermark({ opacity: v ?? 30 })} />
位置固定右下角;重新生成后生效,已生成的图不变 )}
); const selectableCount = imgs.length; /** 删除一张已生成的图片(二次确认后调用),成功后刷新素材列表 */ const handleDeleteGenerated = async (assetId: string) => { try { await deleteAsset(assetId); message.success('已删除'); onRefreshAssets(); } catch (e) { message.error(apiErrorMessage(e)); } }; const displayGroups = DISPLAY_GROUPS.filter((g) => groupImages(g).length > 0); return (
{/* ── 4 采集图片 ── */}
{uploadButton} } > {displayGroups.length === 0 ? ( ) : ( {displayGroups.map((g) => (
{groupImages(g).map((a) => { const on = selectedKeys.has(a.id); return (
toggleKey(a.id)} style={{ position: 'absolute', top: 6, right: 6, width: 20, height: 20, borderRadius: '50%', background: on ? '#1677ff' : 'rgba(255,255,255,0.9)', color: on ? '#fff' : '#bbb', border: '1px solid #d9d9d9', display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', fontSize: 12, zIndex: 2, userSelect: 'none', }} > ✓ {a.status !== 'uploaded' && ( {a.status === 'failed' ? '转存失败' : '转存中'} )} {/* AI 生图:半透明悬浮在图片右下角 */}
{a.variant_name || assetName(a)}
); })}
))}
)}
{/* ── 5 出图方案(左:规划操作+方案列表;右:风格/要求/模型/生成) ── */}
AI 方案} > {/* 左列整块:与价格试算右列相同的浅灰卡片 */}
setPlanThenGenerate(e.target.checked)} title="勾选后,AI 规划完成将自动开始生成" > 规划并生成
{plan.map((p, idx) => (
togglePlanRow(idx)} title="点击勾选/取消该方案(数量用右侧加减调整)" style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '6px 8px', borderRadius: 6, cursor: 'pointer', opacity: p.count === 0 ? 0.45 : 1, background: p.count === 0 ? 'transparent' : 'rgba(22,119,255,0.03)', }} >
0}>{p.title} {p.variant_name && {p.variant_name}} {p.detail && ( {p.detail} )} {p.prompt_hint && ( 🎯 {p.prompt_hint} )}
e.stopPropagation()}> setPlanCount(idx, v)} />
))}
togglePlanAll(e.target.checked)} title="勾选:全部方案至少 1 张(>1 张保留原数量);取消:全部改为 0,方便单独勾选一种方案" > 全部方案 {planSource === 'ai' && ( { setPlan(DEFAULT_PLAN.map((p) => ({ ...p }))); setPlanSource('default'); setPlanSummary(''); }} > 恢复默认方案 )} {planSummary || '方案与张数由规划器按商品信息自动决定,可手动微调,0 即不生成'}
视觉风格
setStyleSet(v as number)} options={STYLE_SET_OPTIONS.map((s) => ({ value: s.value, label: s.label }))} />
风格提示词(可编辑,直接决定生成画面风格) {stylePrompts[styleSet] !== undefined && ( setStylePrompts((p) => { const n = { ...p }; delete n[styleSet]; return n; }) } > 恢复默认 )} setStylePrompts((p) => ({ ...p, [styleSet]: e.target.value }))} />
生图要求(优先级最高,强制约束,会覆盖其他设定) setRequirements(e.target.value)} placeholder="选填,例如:必须保留商品正面品牌标识;背景必须为纯黑色;不得添加任何文字水印" />