client/MicUploadPage.jsx

704 lines
30 KiB
JavaScript
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.

// MIC产品上传 — 前端页面
//
// 接入方式(对照 App.jsx 里"后板图模板"菜单项的现成写法):
//
// 1. import { MicUploadPage } from './mic-upload/MicUploadPage';
// (或者把这个文件内容直接并入 App.jsx,看你想不想保持单文件习惯)
//
// 2. NAV_GROUPS 里"产品"分组,在 backpanel 那一项下面加一行(App.jsx 约2121行):
// { id: 'mic-upload', label: 'MIC产品上传', icon: UploadCloud },
// UploadCloud 需要从 lucide-react 多 import 一个图标。
//
// 3. 渲染switch里(App.jsx约3722-3724行 backpanel那块下面)加:
// {view === 'mic-upload' && <MicUploadPage products={products} productCategories={productCategories} />}
// products / productCategories 都是 App.jsx 里已有的那两个state(约2225/2274行)。
//
// 本组件是单模式(一次只处理一个产品),批量队列以后再加。
import React, { useState, useRef, useCallback, useEffect } from 'react';
const VIEWPORT = { width: 1280, height: 800 };
function useMicSession() {
const [sessionId, setSessionId] = useState(null);
const [wsToken, setWsToken] = useState(null);
const [connected, setConnected] = useState(false);
const [logs, setLogs] = useState([]);
const wsRef = useRef(null);
const frameCallbackRef = useRef(null);
const appendLog = useCallback((entry) => {
setLogs((prev) => [...prev.slice(-300), entry]);
}, []);
const openWs = useCallback((id, token, onFrame) => {
frameCallbackRef.current = onFrame;
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${window.location.host}/ws/mic-upload?sessionId=${id}&token=${token}`);
ws.onopen = () => setConnected(true);
ws.onclose = () => setConnected(false);
ws.onerror = () => setConnected(false);
ws.onmessage = (ev) => {
let msg;
try { msg = JSON.parse(ev.data); } catch (e) { return; }
if (msg.type === 'frame') {
// 收到画面帧本身就是"确实连着"的铁证——直接在这里也置一次true,
// 不完全依赖onopen这一个事件(万一它在某些代理环境下没如期触发)
setConnected(true);
frameCallbackRef.current && frameCallbackRef.current(msg.data);
} else if (msg.type === 'log') {
appendLog(msg);
}
};
wsRef.current = ws;
}, [appendLog]);
// 单例会话:POST这个接口既是"新建"也是"接上已经在跑的那个",后端会自己判断
// 要不要真的启动新浏览器。所以组件挂载时(首次进这个页面/刷新/从别的菜单
// 切回来)都直接调它就够了,不需要额外猜"之前的会话还在不在"。
const connect = useCallback(async (onFrame) => {
setLogs([]);
const res = await fetch('/api/mic-upload/sessions', { method: 'POST' });
const data = await res.json();
if (!res.ok) throw new Error(data.error || '启动会话失败');
setSessionId(data.sessionId);
setWsToken(data.wsToken);
openWs(data.sessionId, data.wsToken, onFrame);
return data; // { sessionId, wsToken, phase, reused }
}, [openWs]);
const stop = useCallback(async () => {
if (wsRef.current) { try { wsRef.current.close(); } catch (e) {} wsRef.current = null; }
if (sessionId) {
try { await fetch(`/api/mic-upload/sessions/${sessionId}`, { method: 'DELETE' }); } catch (e) {}
}
setSessionId(null);
setWsToken(null);
setConnected(false);
}, [sessionId]);
const sendInput = useCallback((msg) => {
if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {
wsRef.current.send(JSON.stringify(msg));
}
}, []);
// 画面卡住(比如网络抖了一下)时用——只重开WebSocket这一根管子,浏览器/
// 会话本身不受影响,不需要重新POST /sessions,token还是原来那个。
const refreshWs = useCallback(() => {
if (!sessionId || !wsToken) return;
if (wsRef.current) { try { wsRef.current.close(); } catch (e) {} wsRef.current = null; }
openWs(sessionId, wsToken, frameCallbackRef.current);
}, [sessionId, wsToken, openWs]);
// 组件卸载(切到别的菜单)时只关WebSocket连接,后端的浏览器会话继续留着——
// 是单例的,切回来时挂载effect会重新POST /sessions,自动接上同一个。
useEffect(() => () => { if (wsRef.current) wsRef.current.close(); }, []);
return { sessionId, wsToken, connected, logs, connect, stop, sendInput, refreshWs };
}
// canvas <-> 远程浏览器坐标换算:canvas按容器宽度等比缩放显示,鼠标事件按缩放比换算回1280x800
function useRemoteCanvas(sendInput) {
const canvasRef = useRef(null);
const scaleRef = useRef(1);
const drawFrame = useCallback((base64Jpeg) => {
const canvas = canvasRef.current;
if (!canvas) return;
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
canvas.width = VIEWPORT.width;
canvas.height = VIEWPORT.height;
ctx.drawImage(img, 0, 0, VIEWPORT.width, VIEWPORT.height);
};
img.src = `data:image/jpeg;base64,${base64Jpeg}`;
}, []);
const toRemoteCoords = useCallback((e) => {
const canvas = canvasRef.current;
const rect = canvas.getBoundingClientRect();
scaleRef.current = VIEWPORT.width / rect.width;
const x = Math.round((e.clientX - rect.left) * scaleRef.current);
const y = Math.round((e.clientY - rect.top) * scaleRef.current);
return { x, y };
}, []);
const handlers = {
onMouseMove: (e) => { const { x, y } = toRemoteCoords(e); sendInput({ type: 'mousemove', x, y }); },
onMouseDown: (e) => { const { x, y } = toRemoteCoords(e); sendInput({ type: 'mousedown', x, y, button: 'left' }); },
onMouseUp: (e) => { const { x, y } = toRemoteCoords(e); sendInput({ type: 'mouseup', x, y, button: 'left' }); },
onWheel: (e) => { sendInput({ type: 'wheel', dx: e.deltaX, dy: e.deltaY }); e.preventDefault(); },
};
return { canvasRef, drawFrame, handlers };
}
// 捕获键盘输入的隐藏input——登录表单里的账号密码靠这个转发过去
function KeyCaptureInput({ sendInput }) {
const [value, setValue] = useState('');
return (
<input
className="mic-key-capture"
value={value}
placeholder="点这里输入账号/密码/验证码,会实时转发到远程浏览器"
onChange={(e) => {
const next = e.target.value;
if (next.length > value.length) {
sendInput({ type: 'text', text: next.slice(value.length) });
} else if (next.length < value.length) {
for (let i = 0; i < value.length - next.length; i++) sendInput({ type: 'keydown', key: 'Backspace' });
}
setValue(next);
}}
onKeyDown={(e) => {
if (e.key === 'Enter') { sendInput({ type: 'keydown', key: 'Enter' }); setValue(''); }
if (e.key === 'Tab') { sendInput({ type: 'keydown', key: 'Tab' }); e.preventDefault(); }
}}
style={{ width: '100%', padding: '8px 10px', fontSize: 13, border: '1px solid var(--line, #ddd)', borderRadius: 6 }}
/>
);
}
// 已保存的MIC账号/密码——只存是否已保存(hasEmail/hasPassword)在前端state,
// 密码明文从不出现在前端:保存时直接PUT给后端加密存储;使用时点"填入"按钮,
// 后端解密后直接当键盘输入发给远程浏览器,不经过任何前端网络请求。
function SavedCredentialsPanel({ sessionId, sendAutofill }) {
const [hasEmail, setHasEmail] = useState(false);
const [hasPassword, setHasPassword] = useState(false);
const [emailInput, setEmailInput] = useState('');
const [passwordInput, setPasswordInput] = useState('');
const [saving, setSaving] = useState(false);
const [msg, setMsg] = useState('');
useEffect(() => {
fetch('/api/mic-upload/credentials')
.then((r) => r.json())
.then((d) => { setHasEmail(!!d.hasEmail); setHasPassword(!!d.hasPassword); })
.catch(() => {});
}, []);
async function handleSave() {
if (!emailInput && !passwordInput) return;
setSaving(true);
setMsg('');
try {
const res = await fetch('/api/mic-upload/credentials', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: emailInput || undefined, password: passwordInput || undefined }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '保存失败');
setHasEmail(data.hasEmail);
setHasPassword(data.hasPassword);
setEmailInput('');
setPasswordInput('');
setMsg('已保存');
} catch (e) {
setMsg(e.message);
} finally {
setSaving(false);
}
}
return (
<div style={{ border: '1px solid var(--line, #ddd)', borderRadius: 6, padding: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
<div style={{ fontSize: 12, color: 'var(--ink-soft, #888)' }}>
已保存:账号{hasEmail ? '✓' : '未保存'} / 密码{hasPassword ? '✓' : '未保存'}
</div>
<input
placeholder="MIC账号邮箱(留空=不改)"
value={emailInput}
onChange={(e) => setEmailInput(e.target.value)}
style={{ padding: '6px 8px', fontSize: 13 }}
/>
<input
type="password"
placeholder="MIC密码(留空=不改)"
value={passwordInput}
onChange={(e) => setPasswordInput(e.target.value)}
style={{ padding: '6px 8px', fontSize: 13 }}
/>
<button className="btn-secondary" disabled={saving || (!emailInput && !passwordInput)} onClick={handleSave}>
{saving ? '保存中...' : '保存账号/密码'}
</button>
{msg && <div style={{ fontSize: 12 }}>{msg}</div>}
{sessionId && (
<div style={{ display: 'flex', gap: 6 }}>
<button className="btn-ghost" disabled={!hasEmail} style={{ flex: 1 }} onClick={() => sendAutofill('email')}>
填入账号
</button>
<button className="btn-ghost" disabled={!hasPassword} style={{ flex: 1 }} onClick={() => sendAutofill('password')}>
填入密码
</button>
</div>
)}
<div style={{ fontSize: 11, color: 'var(--ink-soft, #888)' }}>
用法:先点一下右侧画面里要填的那个输入框(让它获得焦点),再点这里的"填入"按钮。
</div>
</div>
);
}
// 品类 -> MIC仿造发布模板URL 配置面板。列表来自CRM"产品分组"里的品类树,
// 每个细分品类(type)一行,读写走 /api/mic-upload/templates。
function TemplateConfigPanel({ productCategories, onClose }) {
const [values, setValues] = useState({});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [msg, setMsg] = useState('');
useEffect(() => {
fetch('/api/mic-upload/templates', { cache: 'no-store' })
.then((r) => r.json())
.then((d) => setValues(d.value || {}))
.catch((e) => setMsg(`读取失败: ${e.message}`))
.finally(() => setLoading(false));
}, []);
async function handleSave() {
setMsg('');
setSaving(true);
try {
const res = await fetch('/api/mic-upload/templates', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: values }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '保存失败');
setMsg('已保存');
} catch (e) {
setMsg(e.message);
} finally {
setSaving(false);
}
}
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 50 }}>
<div style={{ background: '#fff', borderRadius: 8, padding: 20, width: 520, maxHeight: '80vh', overflowY: 'auto' }}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
<div className="panel-title">品类发布模板配置</div>
<button className="btn-ghost" onClick={onClose}>关闭</button>
</div>
<div style={{ fontSize: 12, color: 'var(--ink-soft, #888)', marginBottom: 10 }}>
每个品类填一个"仿造发布"模板产品的完整URL(形如
https://membercenter.made-in-china.com/productmanage.do?xcase=addSimilar&prodId=xxxx),
需要你先在MIC后台为每个品类找一个字段结构合适的已发布产品。留空的品类点"开始自动填写"时会报错提示先配置。
</div>
{loading ? (
<div>加载中...</div>
) : (
<>
{(productCategories || []).map((cat) => (
<div key={cat.id} style={{ marginBottom: 10 }}>
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>{cat.name}</div>
{(cat.types || []).map((typeName) => (
<div key={typeName} style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
<div style={{ width: 120, fontSize: 12, flexShrink: 0 }}>{typeName}</div>
<input
placeholder="addSimilar模板URL"
value={values[typeName] || ''}
onChange={(e) => setValues((prev) => ({ ...prev, [typeName]: e.target.value }))}
style={{ flex: 1, padding: '4px 6px', fontSize: 12 }}
/>
</div>
))}
</div>
))}
<button className="btn-primary" disabled={saving} onClick={handleSave}>
{saving ? '保存中...' : '保存全部'}
</button>
{msg && <span style={{ marginLeft: 8, fontSize: 12 }}>{msg}</span>}
</>
)}
</div>
</div>
);
}
export function MicUploadPage({ products = [], productCategories = [] }) {
const { sessionId, connected, logs, connect, stop, sendInput, refreshWs } = useMicSession();
const { canvasRef, drawFrame, handlers } = useRemoteCanvas(sendInput);
// connecting -> browsing -> ready -> filling -> filled -> submitted(还有个 error 态)
const [phase, setPhase] = useState('connecting');
const [reviewSecondsLeft, setReviewSecondsLeft] = useState(0);
const [queueIds, setQueueIds] = useState([]); // 选中要批量处理的产品,按点击顺序
const [queueIndex, setQueueIndex] = useState(-1); // 当前处理到队列里第几个,-1=还没开始
const [search, setSearch] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [showTemplateConfig, setShowTemplateConfig] = useState(false);
const logEndRef = useRef(null);
// 挂载时(首次进这个页面/刷新/从别的菜单切回来)都直接"接上"后端那个长期
// 存在的单例浏览器会话——已经登录过的话这里会直接跳到 ready,不用再点
// "新建会话"。只有第一次真正创建全新浏览器时才会自动顺手打开登录页。
useEffect(() => {
let cancelled = false;
async function boot() {
try {
const data = await connect(drawFrame);
if (cancelled) return;
if (data.phase === 'ready') {
setPhase('ready');
} else if (!data.reused) {
// 全新浏览器,页面是空白的,顺手直接打开登录页
await fetch(`/api/mic-upload/sessions/${data.sessionId}/login`, { method: 'POST' });
if (!cancelled) setPhase('browsing');
} else {
// 接上了一个还没登录完的旧会话,画面上是它原来的样子,不用重新导航
setPhase('browsing');
}
} catch (e) {
if (!cancelled) { setError(e.message); setPhase('error'); }
}
}
boot();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => { logEndRef.current?.scrollIntoView({ block: 'end' }); }, [logs]);
useEffect(() => () => {
if (reviewTimerRef.current) clearInterval(reviewTimerRef.current);
}, []);
const filteredProducts = products.filter((p) => {
if (!search.trim()) return true;
const q = search.trim().toLowerCase();
return (p.name || '').toLowerCase().includes(q) || (p.brand || '').toLowerCase().includes(q);
});
async function handleRetryConnect() {
setError('');
setPhase('connecting');
try {
const data = await connect(drawFrame);
if (data.phase === 'ready') setPhase('ready');
else setPhase('browsing');
} catch (e) {
setError(e.message);
setPhase('error');
}
}
// 万一MIC那边的登录态失效了(cookie过期之类),手动强制跳回登录页用这个,
// 不用整个重新连接会话。
async function handleManualGotoLogin() {
if (!sessionId) { setError('会话已断开'); return; }
setError('');
setBusy(true);
try {
const res = await fetch(`/api/mic-upload/sessions/${sessionId}/login`, { method: 'POST' });
const data = await res.json();
if (!res.ok) throw new Error(data.error || '打开登录页失败');
setPhase('browsing');
} catch (e) {
setError(e.message);
} finally {
setBusy(false);
}
}
async function handleLoginConfirmed() {
if (sessionId) {
try { await fetch(`/api/mic-upload/sessions/${sessionId}/mark-ready`, { method: 'POST' }); } catch (e) {}
}
setPhase('ready');
}
async function sendAutofill(field) {
if (!sessionId) { setError('会话已断开'); return; }
setError('');
try {
const res = await fetch(`/api/mic-upload/sessions/${sessionId}/autofill`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ field }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '填入失败');
} catch (e) {
setError(e.message);
}
}
const reviewTimerRef = useRef(null);
// 按队列顺序处理第idx个产品:导航到模板+AI生成标题关键词+填表,填完后不会
// 立刻提交——留几秒钟给你在右侧画面里看一眼/顺手点进某个框改一下(画面
// 上的鼠标点击、打字任何时候都能转发过去,不限于登录阶段),倒计时结束
// 没人管它才会自动提交,省得每次都要手动点。
async function runFillForIndex(idx) {
if (!sessionId) { setError('会话已断开,请重新打开登录页'); return; }
const productId = queueIds[idx];
if (!productId) { setError('队列为空'); return; }
setError('');
setBusy(true);
setQueueIndex(idx);
setPhase('filling');
try {
const res = await fetch(`/api/mic-upload/sessions/${sessionId}/publish`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId }),
});
const data = await res.json();
if (!res.ok) throw new Error(data.error || '自动填写失败');
startReviewCountdown(idx);
} catch (e) {
setError(e.message);
setPhase('ready');
setBusy(false);
}
}
const REVIEW_SECONDS = 8;
function startReviewCountdown(idx) {
setBusy(false);
setPhase('review');
setReviewSecondsLeft(REVIEW_SECONDS);
if (reviewTimerRef.current) clearInterval(reviewTimerRef.current);
reviewTimerRef.current = setInterval(() => {
setReviewSecondsLeft((s) => {
if (s <= 1) {
clearInterval(reviewTimerRef.current);
reviewTimerRef.current = null;
submitOneAuto(idx);
return 0;
}
return s - 1;
});
}, 1000);
}
function pauseReview() {
if (reviewTimerRef.current) { clearInterval(reviewTimerRef.current); reviewTimerRef.current = null; }
setPhase('paused'); // 暂停后倒计时不会自己继续,得你手动点"确认提交"
}
async function submitOneAuto(idx) {
if (reviewTimerRef.current) { clearInterval(reviewTimerRef.current); reviewTimerRef.current = null; }
setBusy(true);
setPhase('submitting');
try {
const res = await fetch(`/api/mic-upload/sessions/${sessionId}/submit`, { method: 'POST' });
const data = await res.json();
if (!res.ok) throw new Error(data.error || '提交失败');
const nextIdx = idx + 1;
if (nextIdx < queueIds.length) {
await runFillForIndex(nextIdx); // 递归接着处理队列下一个,全程不用点按钮
} else {
setPhase('submitted');
setQueueIds([]);
setQueueIndex(-1);
setBusy(false);
}
} catch (e) {
setError(`第${idx + 1}个产品提交失败: ${e.message}`);
setPhase('ready');
setBusy(false);
}
}
async function handleFill() {
if (queueIds.length === 0) { setError('请先选择至少一个产品'); return; }
await runFillForIndex(0);
}
function toggleQueue(productId) {
// 提交完一批之后phase停在'submitted',这时候点选新产品要能重新回到'ready'
// 才会显示"开始自动填写"按钮;处理中(filling/submitting)不允许中途改选,忽略点击。
if (phase === 'filling' || phase === 'submitting' || phase === 'review' || phase === 'paused') return;
if (phase === 'submitted') setPhase('ready');
setQueueIds((prev) => (
prev.includes(productId) ? prev.filter((id) => id !== productId) : [...prev, productId]
));
}
async function handleClose() {
if (reviewTimerRef.current) { clearInterval(reviewTimerRef.current); reviewTimerRef.current = null; }
await stop();
setQueueIds([]);
setQueueIndex(-1);
// 关掉之后自动重新连接一次——这会真正启动一个全新的浏览器(旧的已经关了),
// 相当于手动"重启"这个模块,不用刷新整个页面。
await handleRetryConnect();
}
return (
<div className="panel" style={{ display: 'flex', gap: 16, height: '100%' }}>
{/* 左:产品选择 + 流程控制 */}
<div style={{ width: 300, flexShrink: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
<div className="panel-title">MIC产品上传</div>
<button className="btn-ghost" onClick={() => setShowTemplateConfig(true)}>配置发布模板</button>
{phase === 'connecting' && (
<div style={{ fontSize: 13, color: 'var(--ink-soft, #888)' }}>连接中...</div>
)}
{phase === 'error' && (
<button className="btn-primary" onClick={handleRetryConnect}>重试连接</button>
)}
{phase !== 'connecting' && phase !== 'error' && (
<>
<div style={{ fontSize: 12, color: 'var(--ink-soft, #888)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<span>画面状态:{connected ? '已连接' : '连接中...'}</span>
<button className="btn-ghost" style={{ fontSize: 11, padding: '2px 6px' }} onClick={refreshWs}>刷新画面</button>
</div>
{(phase === 'browsing') && (
<>
<SavedCredentialsPanel sessionId={sessionId} sendAutofill={sendAutofill} />
<KeyCaptureInput sendInput={sendInput} />
<button className="btn-secondary" onClick={handleLoginConfirmed}>已登录,继续</button>
</>
)}
{(phase === 'ready' || phase === 'filling' || phase === 'submitting' || phase === 'review' || phase === 'paused' || phase === 'submitted') && (
<>
<input
placeholder="搜索产品(型号/品牌)"
value={search}
onChange={(e) => setSearch(e.target.value)}
style={{ padding: '6px 8px', fontSize: 13 }}
/>
<div style={{ maxHeight: 220, overflowY: 'auto', border: '1px solid var(--line, #ddd)', borderRadius: 6 }}>
{filteredProducts.length === 0 && (
<div style={{ padding: 8, fontSize: 12, color: 'var(--ink-soft, #888)' }}>没有匹配的产品</div>
)}
{filteredProducts.map((p) => {
const orderIdx = queueIds.indexOf(p.id);
const selected = orderIdx >= 0;
return (
<div
key={p.id}
onClick={() => toggleQueue(p.id)}
style={{
display: 'flex', justifyContent: 'space-between', alignItems: 'center',
padding: '6px 8px', fontSize: 13, cursor: 'pointer',
background: selected ? 'var(--brand-soft, #fde7d0)' : 'transparent',
borderBottom: '1px solid var(--line, #eee)',
}}
>
<span>{p.brand ? `[${p.brand}] ` : ''}{p.name}</span>
<span style={{
fontWeight: 700, color: selected ? 'var(--brand, #d9822b)' : '#999',
minWidth: 16, textAlign: 'center', fontSize: 11,
}}>
{selected ? `#${orderIdx + 1}` : '+'}
</span>
</div>
);
})}
</div>
{queueIds.length > 0 && (
<div style={{ fontSize: 11, color: 'var(--ink-soft, #888)' }}>
已选 {queueIds.length} 个,按点选顺序依次处理。再点一下已选的行可以取消。
</div>
)}
</>
)}
{phase === 'ready' && (
<>
<button className="btn-primary" disabled={busy || queueIds.length === 0} onClick={handleFill}>
{busy ? '正在填写...' : queueIds.length > 1 ? `开始批量填写(共${queueIds.length}个)` : '开始自动填写'}
</button>
{queueIds.length === 0 && (
<div style={{ fontSize: 11, color: 'var(--ink-soft, #888)' }}>
提示:先在上面的列表里点选一个或多个产品(不是只搜索),选中后这里才会真正开始填写。
</div>
)}
</>
)}
{(phase === 'filling' || phase === 'submitting') && (
<div style={{ fontSize: 12, color: 'var(--ink-soft, #888)' }}>
{phase === 'filling' ? '正在自动填写...' : '正在提交...'}
{queueIds.length > 1 && ` 第 ${queueIndex + 1} / ${queueIds.length} 个`}
</div>
)}
{(phase === 'review' || phase === 'paused') && (
<div style={{ border: '1px solid var(--brand, #d9822b)', borderRadius: 6, padding: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
<div style={{ fontSize: 12 }}>
{phase === 'review'
? `已填完,${reviewSecondsLeft}秒后自动提交——这段时间可以在右侧画面里点进任意框直接改`
: '已暂停,改好了再点提交'}
{queueIds.length > 1 && `(第 ${queueIndex + 1} / ${queueIds.length} 个)`}
</div>
<KeyCaptureInput sendInput={sendInput} />
<div style={{ display: 'flex', gap: 6 }}>
{phase === 'review' && (
<button className="btn-ghost" style={{ flex: 1 }} onClick={pauseReview}>暂停检查</button>
)}
<button className="btn-primary" style={{ flex: 1 }} disabled={busy} onClick={() => submitOneAuto(queueIndex)}>
立即提交
</button>
</div>
</div>
)}
{phase === 'submitted' && (
<div style={{ color: 'var(--success, #2a8f4d)', fontSize: 13 }}>✅ 已全部提交,请在画面里核对发布结果</div>
)}
{phase !== 'browsing' && (
<button className="btn-ghost" disabled={busy} onClick={handleManualGotoLogin}>
重新打开登录页(登录态失效时用)
</button>
)}
<button className="btn-ghost" onClick={handleClose}>关闭会话(只是关掉浏览器进程释放内存,登录态存在磁盘上,下次重新连接大概率还是已登录)</button>
</>
)}
{error && <div style={{ color: 'var(--danger, #d33)', fontSize: 13 }}>{error}</div>}
<div style={{ flex: 1, overflowY: 'auto', fontSize: 12, fontFamily: 'monospace', background: '#111', color: '#ddd', padding: 8, borderRadius: 6 }}>
{logs.map((l, i) => (
<div key={i} style={{ color: l.level === 'ERROR' ? '#ff6b6b' : l.level === 'WARNING' ? '#ffd166' : l.level === 'SUCCESS' ? '#6bd97a' : '#ddd' }}>
{l.msg}
</div>
))}
<div ref={logEndRef} />
</div>
</div>
{/* 右:远程浏览器画面 */}
<div style={{ flex: 1, minWidth: 0, background: '#000', borderRadius: 8, overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{phase === 'connecting' && (
<div style={{ color: '#888' }}>连接中...</div>
)}
{phase === 'error' && (
<div style={{ color: '#888' }}>连接失败,点左侧"重试连接"</div>
)}
{phase !== 'connecting' && phase !== 'error' && (
<canvas
ref={canvasRef}
style={{ width: '100%', height: 'auto', cursor: 'default' }}
onMouseMove={handlers.onMouseMove}
onMouseDown={handlers.onMouseDown}
onMouseUp={handlers.onMouseUp}
onWheel={handlers.onWheel}
/>
)}
</div>
{showTemplateConfig && (
<TemplateConfigPanel productCategories={productCategories} onClose={() => setShowTemplateConfig(false)} />
)}
</div>
);
}