feat(商品): 编辑商品与手动添加统一为一键转卖式表单,复用 ProductFormFields
This commit is contained in:
1 parent
361c0fe0e9
commit
a88f4f453c
2 files changed
+742
-105
No files matched your search
+149
-105
@@ -45,6 +45,7 @@ import { confirmAction } from '../services/feedback';
|
||||
import DeliveryProtection from './DeliveryProtection';
|
||||
import GeneralDeliveryRules from './GeneralDeliveryRules';
|
||||
import {EmptyState, NoticeBanner, PageHeader, PageLoading, PageTabs} from './ui';
|
||||
import ProductFormFields, {EditImage, ProductFormValue, emptyProductForm} from './ProductFormFields';
|
||||
import SkuRecognitionPanel from './SkuRecognitionPanel';
|
||||
|
||||
type Notice = { type: 'success' | 'error'; message: string } | null;
|
||||
@@ -69,23 +70,43 @@ interface DeliveryForm {
|
||||
interface ManualItemForm {
|
||||
cookieId: string;
|
||||
itemId: string;
|
||||
title: string;
|
||||
price: string;
|
||||
imageUrl: string;
|
||||
description: string;
|
||||
/** 与一键转卖一致的统一表单(图片/标题/价格/数量/运费/描述/类目) */
|
||||
form: ProductFormValue;
|
||||
/** 本地详情(自动发货展示的说明文字) */
|
||||
detail: string;
|
||||
}
|
||||
|
||||
const emptyManualItem: ManualItemForm = {
|
||||
cookieId: '',
|
||||
itemId: '',
|
||||
title: '',
|
||||
price: '',
|
||||
imageUrl: '',
|
||||
description: '',
|
||||
form: {...emptyProductForm},
|
||||
detail: '',
|
||||
};
|
||||
|
||||
/** item_image 是首图、item_images 是多图 JSON;老数据只有单图时回填成一张 */
|
||||
const itemToImages = (item: Item): EditImage[] => {
|
||||
if (item.item_images) {
|
||||
try {
|
||||
const parsed = JSON.parse(item.item_images);
|
||||
if (Array.isArray(parsed)) {
|
||||
const urls = parsed.filter((url): url is string => typeof url === 'string' && Boolean(url));
|
||||
if (urls.length) return urls.map(url => ({url, width: 1000, height: 1000}));
|
||||
}
|
||||
} catch {
|
||||
// 旧数据不是 JSON,走下面的单图兜底
|
||||
}
|
||||
}
|
||||
if (item.item_image) return [{url: item.item_image, width: 1000, height: 1000}];
|
||||
return [];
|
||||
};
|
||||
|
||||
/** 类目回填:老数据只存了类目名(无 ID),点「修改类目」后可换成带 ID 的候选 */
|
||||
const itemToCat = (item: Item) => {
|
||||
const catName = (item.item_category || '').trim();
|
||||
if (!catName) return null;
|
||||
return {cat_id: '', channel_cat_id: '', tb_cat_id: '', cat_name: catName};
|
||||
};
|
||||
|
||||
const createEmptyVariant = (index = 0): DeliveryVariantForm => ({
|
||||
clientId: `${Date.now()}-${index}-${Math.random().toString(36).slice(2)}`,
|
||||
displayName: '',
|
||||
@@ -199,6 +220,8 @@ const ItemList: React.FC = () => {
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
|
||||
const [detailItem, setDetailItem] = useState<Item | null>(null);
|
||||
/** 编辑商品弹窗的统一表单(与一键转卖同款字段) */
|
||||
const [detailForm, setDetailForm] = useState<ProductFormValue>({...emptyProductForm});
|
||||
const [itemDetail, setItemDetail] = useState('');
|
||||
const [deliveryItem, setDeliveryItem] = useState<Item | null>(null);
|
||||
const [deliveryLoading, setDeliveryLoading] = useState(false);
|
||||
@@ -479,12 +502,17 @@ const ItemList: React.FC = () => {
|
||||
};
|
||||
|
||||
const openManualModal = () => {
|
||||
setManualForm({ ...emptyManualItem, cookieId: selectedAccount || accounts[0]?.id || '' });
|
||||
setManualForm({
|
||||
...emptyManualItem,
|
||||
form: {...emptyProductForm},
|
||||
cookieId: selectedAccount || accounts[0]?.id || '',
|
||||
});
|
||||
setShowManualModal(true);
|
||||
};
|
||||
|
||||
const handleCreateManualItem = async () => {
|
||||
if (!manualForm.cookieId || !manualForm.itemId.trim() || !manualForm.title.trim()) {
|
||||
const {cookieId, itemId, form, detail} = manualForm;
|
||||
if (!cookieId || !itemId.trim() || !form.title.trim()) {
|
||||
setNotice({ type: 'error', message: '账号、商品 ID 和商品标题为必填项' });
|
||||
return;
|
||||
}
|
||||
@@ -492,13 +520,18 @@ const ItemList: React.FC = () => {
|
||||
setSavingKey('manual-item');
|
||||
try {
|
||||
await createManualItem({
|
||||
cookie_id: manualForm.cookieId,
|
||||
item_id: manualForm.itemId.trim(),
|
||||
title: manualForm.title.trim(),
|
||||
price: manualForm.price.trim(),
|
||||
image_url: manualForm.imageUrl.trim(),
|
||||
description: manualForm.description.trim(),
|
||||
detail: manualForm.detail.trim(),
|
||||
cookie_id: cookieId,
|
||||
item_id: itemId.trim(),
|
||||
title: form.title.trim(),
|
||||
price: form.price.trim(),
|
||||
image_url: form.images[0]?.url || '',
|
||||
description: form.desc.trim(),
|
||||
detail: detail.trim(),
|
||||
category: form.cat?.cat_name?.trim() || '',
|
||||
quantity: form.quantity.trim(),
|
||||
ship_mode: form.delivery,
|
||||
post_price: form.postPrice.trim(),
|
||||
images: form.images.map(image => image.url),
|
||||
});
|
||||
setItems(await getItems());
|
||||
setShowManualModal(false);
|
||||
@@ -513,19 +546,41 @@ const ItemList: React.FC = () => {
|
||||
const openDetail = (item: Item) => {
|
||||
setDetailItem(item);
|
||||
setItemDetail(item.item_detail || '');
|
||||
setDetailForm({
|
||||
images: itemToImages(item),
|
||||
title: item.item_title || '',
|
||||
price: item.item_price || '',
|
||||
quantity: item.quantity || '1',
|
||||
delivery: item.ship_mode || '包邮',
|
||||
postPrice: item.post_price || '0',
|
||||
desc: item.item_description || '',
|
||||
cat: itemToCat(item),
|
||||
});
|
||||
};
|
||||
|
||||
const handleSaveDetail = async () => {
|
||||
if (!detailItem) return;
|
||||
const key = itemKey(detailItem);
|
||||
setSavingKey(key);
|
||||
if (!detailForm.title.trim()) {
|
||||
setNotice({ type: 'error', message: '商品标题不能为空' });
|
||||
return;
|
||||
}
|
||||
setSavingKey(itemKey(detailItem));
|
||||
try {
|
||||
await updateItemDetail(detailItem.cookie_id, detailItem.item_id, itemDetail);
|
||||
setItems(current => current.map(item =>
|
||||
itemKey(item) === key ? { ...item, item_detail: itemDetail } : item,
|
||||
));
|
||||
await updateItemDetail(detailItem.cookie_id, detailItem.item_id, {
|
||||
item_detail: itemDetail,
|
||||
title: detailForm.title.trim(),
|
||||
description: detailForm.desc.trim(),
|
||||
category: detailForm.cat?.cat_name?.trim() || '',
|
||||
price: detailForm.price.trim(),
|
||||
item_image: detailForm.images[0]?.url || '',
|
||||
images: detailForm.images.map(image => image.url),
|
||||
quantity: detailForm.quantity.trim(),
|
||||
ship_mode: detailForm.delivery,
|
||||
post_price: detailForm.postPrice.trim(),
|
||||
});
|
||||
setItems(await getItems());
|
||||
setDetailItem(null);
|
||||
setNotice({ type: 'success', message: '商品详情已保存' });
|
||||
setNotice({ type: 'success', message: '商品信息已保存' });
|
||||
} catch (error) {
|
||||
setNotice({ type: 'error', message: error instanceof Error ? error.message : '保存失败' });
|
||||
} finally {
|
||||
@@ -1440,23 +1495,37 @@ const ItemList: React.FC = () => {
|
||||
<div className="modal-overlay">
|
||||
<div className="modal-container">
|
||||
<div className="modal-header flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h3 className="text-lg font-bold text-gray-900">编辑商品详情</h3>
|
||||
<p className="mt-1 line-clamp-1 text-sm text-gray-500">{detailItem.item_title || detailItem.item_id}</p>
|
||||
<div className="min-w-0">
|
||||
<h3 className="text-lg font-bold text-gray-900">编辑商品</h3>
|
||||
<p className="mt-1 line-clamp-1 text-sm text-gray-500" title={detailItem.item_title}>
|
||||
{detailItem.item_title || detailItem.item_id}
|
||||
</p>
|
||||
</div>
|
||||
<button type="button" onClick={() => setDetailItem(null)} className="rounded-md p-2 hover:bg-gray-100" aria-label="关闭">
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="item-detail">本地商品详情</label>
|
||||
<textarea
|
||||
id="item-detail"
|
||||
value={itemDetail}
|
||||
onChange={event => setItemDetail(event.target.value)}
|
||||
className="ios-input min-h-64 w-full resize-y rounded-md p-3 font-mono text-sm"
|
||||
placeholder="补充商品说明,供自动回复和发货逻辑读取。"
|
||||
/>
|
||||
<div className="flex flex-col gap-4">
|
||||
<ProductFormFields
|
||||
form={detailForm}
|
||||
onChange={updater => setDetailForm(updater)}
|
||||
cookieId={detailItem.cookie_id}
|
||||
itemId={detailItem.item_id}
|
||||
notify={(type, message) => setNotice({ type, message })}
|
||||
>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="item-detail">本地详情</label>
|
||||
<textarea
|
||||
id="item-detail"
|
||||
value={itemDetail}
|
||||
onChange={event => setItemDetail(event.target.value)}
|
||||
className="ios-input min-h-32 w-full resize-y rounded-md p-3 font-mono text-sm"
|
||||
placeholder="补充商品说明,供自动回复和发货逻辑读取。"
|
||||
/>
|
||||
</div>
|
||||
</ProductFormFields>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer flex justify-end gap-2">
|
||||
<button type="button" onClick={() => setDetailItem(null)} className="ios-btn-secondary rounded-md px-4 py-2.5">取消</button>
|
||||
@@ -1487,77 +1556,52 @@ const ItemList: React.FC = () => {
|
||||
<X className="h-5 w-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="modal-body grid grid-cols-1 gap-4 sm:grid-cols-2">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-account">所属账号</label>
|
||||
<select
|
||||
id="manual-account"
|
||||
value={manualForm.cookieId}
|
||||
onChange={event => setManualForm(current => ({ ...current, cookieId: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
<div className="modal-body">
|
||||
<div className="flex flex-col gap-4">
|
||||
<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="manual-account">所属账号</label>
|
||||
<select
|
||||
id="manual-account"
|
||||
value={manualForm.cookieId}
|
||||
onChange={event => setManualForm(current => ({ ...current, cookieId: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
>
|
||||
<option value="">请选择账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountNames.get(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-item-id">商品 ID</label>
|
||||
<input
|
||||
id="manual-item-id"
|
||||
value={manualForm.itemId}
|
||||
onChange={event => setManualForm(current => ({ ...current, itemId: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
placeholder="例如 1070863591807"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ProductFormFields
|
||||
form={manualForm.form}
|
||||
onChange={updater => setManualForm(current => ({ ...current, form: updater(current.form) }))}
|
||||
cookieId={manualForm.cookieId}
|
||||
itemId={manualForm.itemId.trim()}
|
||||
notify={(type, message) => setNotice({ type, message })}
|
||||
>
|
||||
<option value="">请选择账号</option>
|
||||
{accounts.map(account => (
|
||||
<option key={account.id} value={account.id}>{accountNames.get(account.id)}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-item-id">商品 ID</label>
|
||||
<input
|
||||
id="manual-item-id"
|
||||
value={manualForm.itemId}
|
||||
onChange={event => setManualForm(current => ({ ...current, itemId: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
placeholder="例如 1070863591807"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-price">价格</label>
|
||||
<input
|
||||
id="manual-price"
|
||||
value={manualForm.price}
|
||||
onChange={event => setManualForm(current => ({ ...current, price: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
placeholder="例如 80"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-title">商品标题</label>
|
||||
<input
|
||||
id="manual-title"
|
||||
value={manualForm.title}
|
||||
onChange={event => setManualForm(current => ({ ...current, title: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-image">图片 URL</label>
|
||||
<input
|
||||
id="manual-image"
|
||||
value={manualForm.imageUrl}
|
||||
onChange={event => setManualForm(current => ({ ...current, imageUrl: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
placeholder="https://..."
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-description">商品简介</label>
|
||||
<input
|
||||
id="manual-description"
|
||||
value={manualForm.description}
|
||||
onChange={event => setManualForm(current => ({ ...current, description: event.target.value }))}
|
||||
className="ios-input w-full rounded-md px-3 py-2.5"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-detail">本地详情</label>
|
||||
<textarea
|
||||
id="manual-detail"
|
||||
value={manualForm.detail}
|
||||
onChange={event => setManualForm(current => ({ ...current, detail: event.target.value }))}
|
||||
className="ios-input min-h-28 w-full resize-y rounded-md p-3"
|
||||
/>
|
||||
<div>
|
||||
<label className="mb-2 block text-sm font-bold text-gray-700" htmlFor="manual-detail">本地详情</label>
|
||||
<textarea
|
||||
id="manual-detail"
|
||||
value={manualForm.detail}
|
||||
onChange={event => setManualForm(current => ({ ...current, detail: event.target.value }))}
|
||||
className="ios-input min-h-28 w-full resize-y rounded-md p-3"
|
||||
placeholder="补充商品说明,供自动回复和发货逻辑读取。"
|
||||
/>
|
||||
</div>
|
||||
</ProductFormFields>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer flex justify-end gap-2">
|
||||
|
||||
@@ -0,0 +1,593 @@
|
||||
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;
|
||||
Reference in new issue
Block a user