Files
tangzhuan-yu/frontend/components/ProductFormFields.tsx
T

594 lines
23 KiB
TypeScript

import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Loader2, Plus, Sparkles, X } from 'lucide-react';
import { ResellCategory } from '../types';
import {
getResellAiOptimize,
getResellCategories,
uploadResellImage,
} from '../services/api';
/**
* 统一商品表单(一键转卖 / 编辑商品详情 / 手动添加商品 共用)。
*
* 三个入口共用同一套字段与交互:多图(封面/替换/设首图/URL)、
* 标题 30 字 + AI 优化候选、价格/数量、运费方式、描述 8000 字、
* 商品类目 + 「修改类目」搜索候选。字段值统一由 form/onChange 托管,
* 各入口自己决定提交到哪个接口。
*/
export interface EditImage {
url: string;
width: number;
height: number;
}
export const DELIVERY_OPTIONS = ['包邮', '无需邮寄', '一口价', '按距离计费'] as const;
export interface ProductFormValue {
images: EditImage[];
title: string;
price: string;
quantity: string;
/** 运费方式:包邮 / 无需邮寄 / 一口价 / 按距离计费 */
delivery: string;
/** 运费(delivery === '一口价' 时填写) */
postPrice: string;
desc: string;
/** 发布/保存用类目;为空则由后端自动识别 */
cat: ResellCategory | null;
}
export const emptyProductForm: ProductFormValue = {
images: [],
title: '',
price: '',
quantity: '1',
delivery: '包邮',
postPrice: '0',
desc: '',
cat: null,
};
export interface ProductFormFieldsProps {
form: ProductFormValue;
onChange: (updater: (current: ProductFormValue) => ProductFormValue) => void;
/** AI 优化与类目候选需要的账号;缺省则隐藏 AI 按钮且不加载类目 */
cookieId?: string;
/** 类目候选识别用商品 ID(kgraph 需要源商品图) */
itemId?: string;
notify: (type: 'success' | 'error', message: string) => void;
/** 价格输入框下方的提示(转卖显示「源商品原价 X 元」) */
priceHint?: React.ReactNode;
/** 类目为空时的占位文案 */
catEmptyText?: string;
/** 类目区之后的自定义内容(本地详情 textarea、发布成功提示等) */
children?: React.ReactNode;
}
// 读图片真实宽高(闲鱼 payload 需要 widthSize/heightSize);加载失败返回 null
const readImageSize = (src: string): Promise<{ width: number; height: number } | null> =>
new Promise(resolve => {
const probe = new Image();
probe.onload = () => resolve({
width: probe.naturalWidth || 1000,
height: probe.naturalHeight || 1000,
});
probe.onerror = () => resolve(null);
probe.src = src;
});
const ProductFormFields: React.FC<ProductFormFieldsProps> = ({
form,
onChange,
cookieId,
itemId,
notify,
priceHint,
catEmptyText = '未设置(点「修改类目」选择)',
children,
}) => {
// 图片增删改替
const [imgUrlDraft, setImgUrlDraft] = useState('');
const [showAddUrl, setShowAddUrl] = useState(false);
const [imgBusy, setImgBusy] = useState(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const replaceIdxRef = useRef<number | null>(null);
// AI 一键优化:候选标题 + 生成中状态
const [aiTitles, setAiTitles] = useState<string[]>([]);
const [aiLoading, setAiLoading] = useState(false);
// 类目选择器:候选列表 + 手选状态
const [catOptions, setCatOptions] = useState<ResellCategory[]>([]);
const [catLoading, setCatLoading] = useState(false);
const [catLoadedFor, setCatLoadedFor] = useState('');
const [showCatPicker, setShowCatPicker] = useState(false);
const [catKeyword, setCatKeyword] = useState('');
const set = (patch: Partial<ProductFormValue>) =>
onChange(current => ({ ...current, ...patch }));
const images = form.images;
const setImages = (updater: (list: EditImage[]) => EditImage[]) =>
onChange(current => ({ ...current, images: updater(current.images) }));
// 类目候选按关键词过滤(候选来自闲鱼 kgraph,通常上百条)
const filteredCats = useMemo(() => {
const kw = catKeyword.trim().toLowerCase();
if (!kw) return catOptions;
return catOptions.filter(opt => opt.cat_name.toLowerCase().includes(kw));
}, [catOptions, catKeyword]);
// ------------------------------------------------------------------
// 转卖图片:删除 / 设为首图 / URL 添加 / 本地上传替换
// ------------------------------------------------------------------
const removeImage = (idx: number) => {
if (images.length <= 1) {
notify('error', '至少保留一张图片');
return;
}
setImages(list => list.filter((_, i) => i !== idx));
};
const promoteImage = (idx: number) => {
if (idx <= 0) return;
setImages(list => {
const next = [...list];
const [picked] = next.splice(idx, 1);
return [picked, ...next];
});
};
const addImageFromUrl = async () => {
const url = imgUrlDraft.trim();
if (imgBusy) return;
if (!/^https?:\/\//.test(url)) {
notify('error', '请输入以 http(s):// 开头的图片地址');
return;
}
if (images.length >= 9) {
notify('error', '最多 9 张图片');
return;
}
setImgBusy(true);
try {
const size = await readImageSize(url);
if (!size) {
notify('error', '该图片地址无法加载(可能防盗链或已失效)');
return;
}
setImages(list => [...list, { url, ...size }].slice(0, 9));
setImgUrlDraft('');
setShowAddUrl(false);
notify('success', '已添加图片');
} finally {
setImgBusy(false);
}
};
const uploadImageFiles = async (files: FileList | null, replaceIdx: number | null) => {
if (!files || !files.length) return;
const file = files[0];
setImgBusy(true);
try {
const res = await uploadResellImage(file);
// 相对路径转绝对:闲鱼服务器要能直接抓取该地址
const absolute = new URL(res.path, window.location.origin).href;
const size = await readImageSize(absolute);
if (!size) {
notify('error', '图片上传后无法加载,请重试');
return;
}
if (replaceIdx != null) {
setImages(list => list.map((img, i) => (i === replaceIdx ? { url: absolute, ...size } : img)));
notify('success', '图片已替换');
} else {
if (images.length >= 9) {
notify('error', '最多 9 张图片');
return;
}
setImages(list => [...list, { url: absolute, ...size }].slice(0, 9));
notify('success', '图片已添加');
}
// 本机/局域网地址闲鱼抓不到,提示一下
if (/^(https?:\/\/)?(localhost|127\.0\.0\.1|192\.168\.)/.test(window.location.origin)) {
notify('error', '当前访问地址非公网,闲鱼可能无法拉取上传的图片,建议通过公网域名操作');
}
} catch (error) {
notify('error', error instanceof Error ? error.message : '图片上传失败');
} finally {
setImgBusy(false);
if (fileInputRef.current) fileInputRef.current.value = '';
replaceIdxRef.current = null;
}
};
// ------------------------------------------------------------------
// AI 一键优化:多候选标题点击填入 + 描述改写
// ------------------------------------------------------------------
const handleAiOptimize = async () => {
if (!cookieId || aiLoading) return;
setAiLoading(true);
try {
const res = await getResellAiOptimize({
cookie_id: cookieId,
title: form.title,
description: form.desc,
});
if (!res.success) {
notify('error', res.message || 'AI 优化失败,请重试');
return;
}
const titles = res.titles || [];
setAiTitles(titles);
if (res.description && res.description !== form.desc) {
set({ desc: res.description as string });
}
notify(
'success',
titles.length
? `AI 已生成 ${titles.length} 个候选标题(点击选用),描述已同步优化`
: '描述已优化',
);
} catch (error) {
notify('error', error instanceof Error ? error.message : 'AI 优化失败');
} finally {
setAiLoading(false);
}
};
// ------------------------------------------------------------------
// 类目候选:同一个商品只拉一次,供「修改类目」搜索选择
// ------------------------------------------------------------------
const loadCategories = async () => {
if (!cookieId || catLoading || catLoadedFor === `${cookieId}:${itemId}`) return;
if (!itemId) {
notify('error', '请先填写商品 ID,识别类目需要源商品图');
return;
}
setCatLoading(true);
try {
const res = await getResellCategories({
cookie_id: cookieId,
item_id: itemId,
title: form.title || '',
});
setCatOptions(res.options || []);
setCatLoadedFor(`${cookieId}:${itemId}`);
// 接口给出当前类目且表单还没类目时兜底填入(tbCatId 允许为空)
const current = res.current;
const options = res.options || [];
onChange(prev => {
// 老数据把类目存成了纯数字 ID(如 50023914),在候选里换回可读名字
if (prev.cat && !prev.cat.cat_id && /^\d+$/.test(prev.cat.cat_name.trim())) {
const raw = prev.cat.cat_name.trim();
const hit = options.find(opt => opt.cat_id === raw || opt.channel_cat_id === raw);
if (hit) return { ...prev, cat: hit };
}
if (prev.cat) return prev;
if (current?.cat_id && current?.channel_cat_id) return { ...prev, cat: current };
return prev;
});
} catch (error) {
notify(
'error',
`类目列表加载失败(${error instanceof Error ? error.message : '未知错误'}),可稍后再点「修改类目」`,
);
} finally {
setCatLoading(false);
}
};
// 切换到新商品时重置图片/AI/类目状态(由使用方重建 form,这里同步清掉组件内缓存)
const contextKey = `${cookieId}:${itemId}`;
useEffect(() => {
setCatLoadedFor(current => (current === contextKey ? current : ''));
setCatOptions([]);
setAiTitles([]);
setShowCatPicker(false);
setCatKeyword('');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [contextKey]);
// ------------------------------------------------------------------
// 渲染
// ------------------------------------------------------------------
return (
<>
<div>
<div className="mb-2 flex items-center justify-between">
<span className="text-xs text-gray-500">
图片({images.length}/9)· 第一张为封面,悬停可替换/删除
</span>
</div>
{images.length ? (
<>
<div className="flex flex-wrap gap-2">
{images.map((img, idx) => (
<div key={`${img.url}-${idx}`} className="group relative h-20 w-20 shrink-0">
<img
src={img.url}
alt=""
className="h-full w-full rounded-md border border-gray-200 object-cover"
/>
{idx === 0 && (
<span className="absolute inset-x-0 bottom-0 rounded-b-md bg-black/55 text-center text-[10px] leading-4 text-white">
封面
</span>
)}
<button
type="button"
onClick={() => removeImage(idx)}
title="删除该图"
className="absolute -right-1.5 -top-1.5 hidden h-5 w-5 items-center justify-center rounded-full bg-red-500 text-white shadow group-hover:flex"
>
<X className="h-3 w-3" />
</button>
<div
className={`absolute inset-x-0 hidden gap-1 bg-black/55 p-0.5 group-hover:flex ${idx === 0 ? 'bottom-4' : 'bottom-0'}`}
>
<button
type="button"
onClick={() => { replaceIdxRef.current = idx; fileInputRef.current?.click(); }}
className="flex-1 rounded bg-white/20 text-[10px] text-white hover:bg-white/40"
>
替换
</button>
{idx > 0 && (
<button
type="button"
onClick={() => promoteImage(idx)}
className="flex-1 rounded bg-white/20 text-[10px] text-white hover:bg-white/40"
>
设首图
</button>
)}
</div>
</div>
))}
{images.length < 9 && (
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={imgBusy}
className="flex h-20 w-20 shrink-0 flex-col items-center justify-center gap-1 rounded-md border border-dashed border-gray-300 text-gray-400 transition hover:border-purple-400 hover:text-purple-500 disabled:opacity-60"
>
{imgBusy ? <Loader2 className="h-5 w-5 animate-spin" /> : <Plus className="h-5 w-5" />}
<span className="text-[10px]">上传</span>
</button>
)}
<button
type="button"
onClick={() => setShowAddUrl(value => !value)}
className="flex h-20 w-20 shrink-0 flex-col items-center justify-center gap-1 rounded-md border border-dashed border-gray-300 text-gray-400 transition hover:border-purple-400 hover:text-purple-500"
>
<span className="text-base leading-none">🔗</span>
<span className="text-[10px]">URL</span>
</button>
</div>
{showAddUrl && (
<div className="mt-2 flex gap-2">
<input
value={imgUrlDraft}
onChange={event => setImgUrlDraft(event.target.value)}
placeholder="粘贴图片地址 https://…"
className="ios-input min-w-0 flex-1 rounded-md px-3 py-2 text-sm"
/>
<button
type="button"
onClick={addImageFromUrl}
disabled={imgBusy}
className="shrink-0 rounded-md bg-purple-500 px-3 text-xs font-bold text-white disabled:opacity-60"
>
{imgBusy ? '读取中…' : '添加'}
</button>
</div>
)}
</>
) : (
<p className="text-xs text-gray-400">暂无图片,点下方「上传」或「URL」添加</p>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={event => uploadImageFiles(event.target.files, replaceIdxRef.current)}
/>
</div>
<div>
<div className="mb-2 flex items-center justify-between gap-2">
<label className="text-sm font-bold text-gray-700" htmlFor="pf-title">标题</label>
{cookieId && (
<button
type="button"
onClick={handleAiOptimize}
disabled={aiLoading}
className="inline-flex shrink-0 items-center gap-1 rounded-md bg-purple-50 px-2.5 py-1 text-xs font-bold text-purple-600 transition hover:bg-purple-100 disabled:cursor-not-allowed disabled:opacity-60"
>
{aiLoading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Sparkles className="h-3.5 w-3.5" />}
{aiLoading ? 'AI 生成中…' : 'AI 优化标题+描述'}
</button>
)}
</div>
<input
id="pf-title"
value={form.title}
maxLength={30}
onChange={event => set({ title: event.target.value })}
className="ios-input w-full rounded-md px-3 py-2.5"
placeholder="商品标题"
/>
<p className={`mt-1 text-xs ${form.title.length > 30 ? 'text-red-500' : 'text-gray-400'}`}>
闲鱼限 30 字,当前 {form.title.length} 字
</p>
{aiTitles.length > 0 && (
<div className="mt-2 flex flex-col gap-1.5">
<p className="text-xs text-gray-400">AI 候选标题(点击填入上方输入框):</p>
{aiTitles.map((title, index) => (
<button
key={`${title}-${index}`}
type="button"
onClick={() => set({ title: title.slice(0, 30) })}
className={`rounded-md border px-2.5 py-1.5 text-left text-xs leading-relaxed transition ${
form.title === title
? 'border-purple-500 bg-purple-50 text-purple-700'
: 'border-gray-200 bg-white text-gray-700 hover:border-purple-400 hover:bg-purple-50'
}`}
>
{title}
</button>
))}
</div>
)}
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="pf-price">价格(元)</label>
<input
id="pf-price"
value={form.price}
inputMode="decimal"
onChange={event => set({ price: event.target.value })}
className="ios-input w-full rounded-md px-3 py-2.5"
placeholder="例如 99"
/>
{priceHint && <p className="mt-1 text-xs text-gray-400">{priceHint}</p>}
</div>
<div>
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="pf-qty">数量</label>
<input
id="pf-qty"
value={form.quantity}
inputMode="numeric"
onChange={event => set({ quantity: event.target.value })}
className="ios-input w-full rounded-md px-3 py-2.5"
/>
</div>
</div>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<div>
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="pf-delivery">运费方式</label>
<select
id="pf-delivery"
value={form.delivery}
onChange={event => set({ delivery: event.target.value })}
className="ios-input w-full rounded-md px-3 py-2.5"
>
{DELIVERY_OPTIONS.map(option => (
<option key={option} value={option}>{option}</option>
))}
</select>
</div>
{form.delivery === '一口价' && (
<div>
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="pf-post">运费(元)</label>
<input
id="pf-post"
value={form.postPrice}
inputMode="decimal"
onChange={event => set({ postPrice: event.target.value })}
className="ios-input w-full rounded-md px-3 py-2.5"
/>
</div>
)}
</div>
<div>
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="pf-desc">描述</label>
<textarea
id="pf-desc"
value={form.desc}
rows={5}
maxLength={8000}
onChange={event => set({ desc: event.target.value })}
className="ios-input w-full rounded-md px-3 py-2.5"
placeholder="商品描述"
/>
<p className="mt-1 text-xs text-gray-400">{form.desc.length} / 8000</p>
</div>
<div>
<div className="mb-2 flex items-center justify-between gap-3">
<label className="text-sm font-bold text-gray-700">商品类目</label>
<button
type="button"
onClick={() => {
if (!showCatPicker) void loadCategories();
setShowCatPicker(value => !value);
}}
className="text-xs font-bold text-[#ff4400] hover:underline"
>
{showCatPicker ? '收起' : '修改类目'}
</button>
</div>
<div className="ios-input rounded-md px-3 py-2.5 text-sm text-gray-800">
{form.cat
? (/^\d+$/.test(form.cat.cat_name.trim())
? `类目 #${form.cat.cat_name.trim()}(点「修改类目」更换)`
: form.cat.cat_name)
: catEmptyText}
</div>
{showCatPicker && (
<div className="mt-2 rounded-md border border-gray-200 bg-gray-50 p-3">
<input
value={catKeyword}
onChange={event => setCatKeyword(event.target.value)}
placeholder="搜索类目,如:电子资料 / 内存条"
className="ios-input w-full rounded-md px-3 py-2 text-sm"
aria-label="搜索类目"
/>
{catLoading ? (
<p className="mt-2 flex items-center gap-2 text-xs text-gray-500">
<Loader2 className="h-3.5 w-3.5 animate-spin" /> 正在加载类目…
</p>
) : filteredCats.length ? (
<ul className="mt-2 max-h-56 overflow-y-auto rounded-md bg-white">
{filteredCats.slice(0, 150).map(opt => {
const active = Boolean(
form.cat
&& form.cat.cat_id === opt.cat_id
&& form.cat.channel_cat_id === opt.channel_cat_id,
);
return (
<li key={`${opt.cat_id}-${opt.channel_cat_id}`}>
<button
type="button"
onClick={() => {
set({ cat: opt });
setShowCatPicker(false);
setCatKeyword('');
}}
className={`flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-sm ${active ? 'bg-[#ffc940]/25 font-bold text-gray-900' : 'text-gray-700 hover:bg-gray-100'}`}
>
<span className="truncate">{opt.cat_name}</span>
<span className={`shrink-0 text-[10px] ${active ? 'text-gray-900' : 'text-gray-400'}`}>
{active ? '当前' : '选择'}
</span>
</button>
</li>
);
})}
</ul>
) : (
<p className="mt-2 text-xs text-gray-400">
{catOptions.length ? '没有匹配的类目,换个关键词试试' : '候选类目加载失败,可关掉弹窗重开重试'}
</p>
)}
<p className="mt-2 text-[11px] leading-4 text-gray-400">
候选来自闲鱼发布页的分类列表,选中后按该类目保存/发布;识别不准确时可在这里手动改。
</p>
</div>
)}
</div>
{children}
</>
);
};
export default ProductFormFields;