import React, { useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { selectActivePublishBatch } from './itemPublishBatchState'; import { Item, AccountDetail, ShippingRule } from '../types'; import { getItems, getAccountDetails, syncItemsFromAccount, createItem, publishItem, recommendPublishCategory, previewItemPublishBatch, startItemPublishBatch, getItemPublishBatch, getItemPublishBatches, deleteItemPublishBatch, cancelItemPublishBatch, retryFailedItemPublishBatch, updateItem, deleteItem, getShippingRules } from '../services/api'; import type { PublishLocation } from '../services/api'; import { getPublishLocations } from '../services/amapLocation'; import { ArrowRight, Box, CheckCircle2, CircleDashed, Edit, Filter, Link2, LocateFixed, PackagePlus, Plus, RefreshCw, Save, Search, ShoppingBag, Trash2, UploadCloud, User, X } from 'lucide-react'; interface ItemListProps { onConfigureDelivery: (item: Item) => void; } type BatchPhase = 'upload' | 'preview' | 'running' | 'done'; interface PublishCategory { cat_id: string; cat_name: string; channel_cat_id?: string; tb_cat_id?: string; } interface PublishBatchPreviewRow { row_no: number; valid: boolean; errors?: string[]; cookie_id: string; title: string; price: string; quantity: number; images: string[]; category: PublishCategory; } interface PublishBatchDetailRow { id: number; row_no: number; cookie_id: string; title: string; price: string; quantity: number; status: string; item_id: string; item_url: string; error_message: string; failure_kind: string; images?: string[]; category: PublishCategory; } interface PublishBatchDetail { id: string; status: string; filename: string; total: number; success: number; failed: number; pending: number; running: number; retryable: number; rows: PublishBatchDetailRow[]; } const formatItemPrice = (price?: string) => { const value = String(price || '').trim(); if (!value) return '-'; return /^[¥¥]/.test(value) ? value : `¥${value}`; }; const ItemList: React.FC = ({ onConfigureDelivery }) => { const [items, setItems] = useState([]); const [shippingRules, setShippingRules] = useState([]); const [accounts, setAccounts] = useState([]); const [selectedAccount, setSelectedAccount] = useState(''); const [accountFilter, setAccountFilter] = useState(''); const [loading, setLoading] = useState(false); const [publishing, setPublishing] = useState(false); const [batchLoading, setBatchLoading] = useState(false); const [showEditModal, setShowEditModal] = useState(false); const [showAddModal, setShowAddModal] = useState(false); const [showPublishModal, setShowPublishModal] = useState(false); const [showBatchModal, setShowBatchModal] = useState(false); const [batchPhase, setBatchPhase] = useState('upload'); const [batchFile, setBatchFile] = useState(null); const [batchImagesZip, setBatchImagesZip] = useState(null); const [batchCategoryKeyword, setBatchCategoryKeyword] = useState(''); const [batchCategoryLoading, setBatchCategoryLoading] = useState(false); const [locationLoading, setLocationLoading] = useState(false); const [publishLocations, setPublishLocations] = useState([]); const [publishLocation, setPublishLocation] = useState(null); const [batchLocations, setBatchLocations] = useState([]); const [batchLocation, setBatchLocation] = useState(null); const [batchFallbackCategory, setBatchFallbackCategory] = useState({ catId: '', catName: '', channelCatId: '', tbCatId: '', }); const [batchPreview, setBatchPreview] = useState<{ preview_id: string; total: number; valid: number; invalid: number; rows: PublishBatchPreviewRow[]; } | null>(null); const [batchDetail, setBatchDetail] = useState(null); const [recentBatch, setRecentBatch] = useState(null); const batchPollInFlight = useRef(false); const [selectedItem, setSelectedItem] = useState(null); const [editForm, setEditForm] = useState>({}); const [addForm, setAddForm] = useState({ cookie_id: '', item_id: '', item_title: '', item_price: '', item_image: '' }); const [publishForm, setPublishForm] = useState({ cookie_id: '', title: '', description: '', price: '', original_price: '', quantity: '1', postage_mode: 'free', postage: '', images: [] as File[], }); const [publishImagePreviews, setPublishImagePreviews] = useState<{ key: string; url: string }[]>([]); useEffect(() => { if (!showPublishModal || publishForm.images.length === 0) { setPublishImagePreviews([]); return; } const previews = publishForm.images.map((file, index) => ({ key: file.name + index, url: URL.createObjectURL(file), })); setPublishImagePreviews(previews); return () => { previews.forEach(preview => URL.revokeObjectURL(preview.url)); }; }, [showPublishModal, publishForm.images]); const loadItems = async () => { const itemsList = await getItems(); setItems(itemsList); }; const loadShippingRules = async () => { setShippingRules(await getShippingRules()); }; useEffect(() => { Promise.all([getAccountDetails(), getItems(), getShippingRules(), getItemPublishBatches(20)]) .then(([accountList, itemList, ruleList, batches]) => { setAccounts(accountList); setItems(itemList); setShippingRules(ruleList); const recoverable = batches.find(batch => ['running', 'canceling'].includes(batch.status)) || batches.find(batch => batch.status !== 'preview'); setRecentBatch(recoverable || null); }) .catch((e) => console.error('加载商品配置失败:', e)); }, []); useEffect(() => { if (!showBatchModal || !batchDetail?.id || !['running', 'canceling'].includes(batchDetail.status)) return; const timer = window.setInterval(async () => { if (batchPollInFlight.current) return; batchPollInFlight.current = true; try { const detail = await getItemPublishBatch(batchDetail.id); setBatchDetail(detail); setRecentBatch(detail); if (!['running', 'canceling'].includes(detail.status)) { setBatchPhase('done'); await loadItems(); await loadShippingRules(); } } catch (error) { console.error('刷新批量铺货进度失败:', error); } finally { batchPollInFlight.current = false; } }, 3000); return () => { window.clearInterval(timer); }; }, [showBatchModal, batchDetail?.id, batchDetail?.status]); const handleSync = async () => { if (!selectedAccount) return alert('请先选择账号'); setLoading(true); try { const result = await syncItemsFromAccount(selectedAccount); await loadItems(); alert(result?.message || '商品同步完成'); } catch (error: any) { console.error('同步商品失败:', error); alert(error?.message || '同步失败,请重试'); } finally { setLoading(false); } }; const handleEdit = (item: Item) => { setSelectedItem(item); setEditForm({ ...item }); setShowEditModal(true); }; const handleSaveEdit = async () => { if (!selectedItem) return; try { await updateItem(selectedItem.cookie_id, selectedItem.item_id, { item_title: editForm.item_title || '', item_description: editForm.item_description || '', item_category: editForm.item_category || '', item_price: editForm.item_price || '', item_detail: editForm.item_detail || selectedItem.item_detail || '', }); await loadItems(); await loadShippingRules(); setShowEditModal(false); setSelectedItem(null); } catch (error) { console.error('更新商品失败:', error); alert('更新失败,请重试'); } }; const handleDelete = async (item: Item) => { if (confirm(`确认删除商品"${item.item_title}"吗?`)) { try { await deleteItem(item.cookie_id, item.item_id); setItems(prev => prev.filter(i => !(i.cookie_id === item.cookie_id && i.item_id === item.item_id))); } catch (error) { console.error('删除商品失败:', error); alert('删除失败,请重试'); } } }; const handleAddItem = async () => { try { if (!addForm.cookie_id || !addForm.item_id) { alert('请选择账号并填写商品ID'); return; } await createItem(addForm.cookie_id, { item_id: addForm.item_id, item_title: addForm.item_title, item_price: addForm.item_price, item_detail: addForm.item_image ? JSON.stringify({ item_image: addForm.item_image }) : '', }); await loadItems(); setShowAddModal(false); setAddForm({ cookie_id: '', item_id: '', item_title: '', item_price: '', item_image: '' }); } catch (error) { console.error('添加商品失败:', error); alert('添加失败,请重试'); } }; const handlePublishItem = async () => { if (!publishForm.cookie_id) return alert('请选择发布账号'); if (!publishForm.title.trim()) return alert('请填写商品标题'); if (!publishForm.price.trim()) return alert('请填写商品价格'); if (!publishForm.quantity || Number(publishForm.quantity) <= 0) return alert('库存数量必须大于 0'); if (publishForm.images.length === 0) return alert('至少上传 1 张商品图片'); if (publishForm.postage_mode === 'fixed' && !publishForm.postage.trim()) return alert('请填写一口价邮费'); setPublishing(true); try { const result = await publishItem({ ...publishForm, location: publishLocation || undefined }); await loadItems(); setShowPublishModal(false); setPublishForm({ cookie_id: selectedAccount || '', title: '', description: '', price: '', original_price: '', quantity: '1', postage_mode: 'free', postage: '', images: [], }); setPublishLocations([]); setPublishLocation(null); if (result?.item_id) { const publishedItem: Item = { id: result.item_id, cookie_id: publishForm.cookie_id, item_id: result.item_id, item_title: result.item_title || publishForm.title, item_price: result.item_price || publishForm.price, item_image: result.item_image, }; onConfigureDelivery(publishedItem); alert('商品发布成功,ID: ' + result.item_id + ',已为你打开发货规则配置'); } else { alert('商品发布成功'); } } catch (error: any) { console.error('发布商品失败:', error); const payload = error?.payload as any; if (payload?.code === 'stock_permission_missing') { alert('发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。'); return; } alert(error?.message || '发布失败,请重试'); } finally { setPublishing(false); } }; const openBatchModal = async () => { setBatchPhase('upload'); setBatchPreview(null); setBatchDetail(null); setBatchFile(null); setBatchImagesZip(null); setBatchCategoryKeyword(''); setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' }); setBatchLocations([]); setBatchLocation(null); setShowBatchModal(true); setBatchLoading(true); try { const batches = await getItemPublishBatches(20); const recoverable = selectActivePublishBatch(batches); if (recoverable?.id) { const detail = await getItemPublishBatch(recoverable.id); setRecentBatch(detail); setBatchDetail(detail); setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done'); } } catch (error) { console.error('恢复最近批量铺货任务失败:', error); } finally { setBatchLoading(false); } }; const handleRecommendBatchCategory = async () => { const keyword = batchCategoryKeyword.trim(); if (!selectedAccount) return alert('请先选择默认发布账号'); if (!keyword) return alert('请输入类目关键词'); setBatchCategoryLoading(true); try { const result = await recommendPublishCategory(selectedAccount, keyword); const category = result.category; setBatchFallbackCategory({ catId: category.cat_id, catName: category.cat_name, channelCatId: category.channel_cat_id, tbCatId: category.tb_cat_id || '', }); } catch (error: any) { console.error('获取推荐类目失败:', error); alert(error?.message || '没有匹配到类目,请换一个更具体的关键词'); } finally { setBatchCategoryLoading(false); } }; const openRecentBatchResult = async () => { if (!recentBatch?.id) return; setBatchLoading(true); setShowBatchModal(true); try { const detail = await getItemPublishBatch(recentBatch.id); setBatchDetail(detail); setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done'); } catch (error) { console.error('加载最近批量铺货结果失败:', error); } finally { setBatchLoading(false); } }; const handlePreviewBatch = async () => { if (!batchFile) return alert('请先上传商品表格'); if (!selectedAccount) return alert('请先选择默认发布账号'); setBatchLoading(true); try { const result = await previewItemPublishBatch({ file: batchFile, imagesZip: batchImagesZip, defaultCookieId: selectedAccount, fallbackCategory: batchFallbackCategory, location: batchLocation || undefined, }); setBatchPreview(result); setBatchDetail(null); setBatchPhase('preview'); } catch (error: any) { console.error('批量铺货预检失败:', error); alert(error?.message || '预检失败,请检查表格和图片 zip'); } finally { setBatchLoading(false); } }; const handleStartBatch = async () => { if (!batchPreview?.preview_id) return; if (batchPreview.valid <= 0) return alert('没有可发布的商品行'); setBatchLoading(true); try { const started = await startItemPublishBatch(batchPreview.preview_id); const detail = await getItemPublishBatch(started.batch_id || batchPreview.preview_id); setBatchDetail(detail); setRecentBatch(detail); setBatchPhase(detail.status === 'running' ? 'running' : 'done'); } catch (error: any) { console.error('启动批量铺货失败:', error); alert(error?.message || '启动发布任务失败'); } finally { setBatchLoading(false); } }; const handleCancelBatch = async () => { if (!batchDetail?.id) return; if (!confirm('确认取消当前批量铺货任务吗?正在发布的单个商品可能会继续完成。')) return; setBatchLoading(true); try { const result = await cancelItemPublishBatch(batchDetail.id); const detail = await getItemPublishBatch(batchDetail.id); setBatchDetail(detail); setBatchPhase(result?.status === 'canceling' || detail.status === 'canceling' ? 'running' : 'done'); } catch (error: any) { alert(error?.message || '取消失败'); } finally { setBatchLoading(false); } }; const abandonBatchPreview = async () => { const previewId = batchPreview?.preview_id; if (previewId && batchPhase === 'preview') { try { await deleteItemPublishBatch(previewId); } catch (error) { console.error('清理批量铺货预检失败:', error); } } setBatchPreview(null); setBatchPhase('upload'); }; const closeBatchModal = async () => { await abandonBatchPreview(); setShowBatchModal(false); }; const handleRetryBatchFailed = async () => { if (!batchDetail?.id) return; setBatchLoading(true); try { await retryFailedItemPublishBatch(batchDetail.id); setBatchDetail(await getItemPublishBatch(batchDetail.id)); setBatchPhase('running'); } catch (error: any) { alert(error?.message || '重试失败'); } finally { setBatchLoading(false); } }; const downloadPublishTemplate = () => { const headers = [ '账号ID', '标题', '描述', '价格', '原价', '库存', '邮费模式', '邮费', '图片', '类目ID', '类目名称', '频道类目ID', '淘宝类目ID', '付款发货启用', '付款发货内容', '评价赠品启用', '评价赠品内容', '求评价启用', '求评价等待小时', '求评价文案', '求评价最多次数', ]; const rows = [ ['', '会员组合包自动发货', '下单后发送主卡和附赠卡。', '19.90', '29.90', '10', 'free', '', 'images/bundle-1.jpg;images/bundle-2.jpg', '', '', '', '', '是', '101:1;102:1', '是', '201:1;202:2', '是', '72', '亲,满意的话麻烦给个评价,谢谢~', '1'], ['', '普通商品', '仅发布商品,不创建自动化规则。', '49.90', '', '10', 'fixed', '8.00', 'https://example.com/product.jpg', '', '', '', '', '否', '', '否', '', '否', '', '', ''], ]; const csv = [headers, ...rows] .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')) .join('\n'); const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8' }); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = '批量铺货模板.csv'; document.body.appendChild(link); link.click(); link.remove(); URL.revokeObjectURL(url); }; const openAddModal = () => { setAddForm(prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id })); setShowAddModal(true); }; const openPublishModal = () => { setPublishForm(prev => ({ ...prev, cookie_id: selectedAccount || prev.cookie_id })); setShowPublishModal(true); }; const locateForPublish = async (batch: boolean) => { const cookieId = batch ? selectedAccount : publishForm.cookie_id; if (!cookieId) return alert('请先选择发布账号'); if (!navigator.geolocation) return alert('当前浏览器不支持定位'); setLocationLoading(true); navigator.geolocation.getCurrentPosition(async position => { try { const locations = await getPublishLocations(position.coords.longitude, position.coords.latitude); if (!locations.length) throw new Error('当前位置附近没有可用的高德发货地,请稍后重试'); if (batch) { setBatchLocations(locations); setBatchLocation(locations[0]); } else { setPublishLocations(locations); setPublishLocation(locations[0]); } } catch (error: any) { alert(error?.message || '获取发货地失败'); } finally { setLocationLoading(false); } }, error => { setLocationLoading(false); alert(error.code === error.PERMISSION_DENIED ? '定位权限被拒绝,请在浏览器设置中允许定位' : '无法获取当前位置,请稍后重试'); }, { enableHighAccuracy: true, timeout: 15000, maximumAge: 60000 }); }; const rulesForItem = (item: Item) => shippingRules.filter(rule => rule.cookie_id === item.cookie_id && rule.item_id === item.item_id ).length > 0 ? shippingRules.filter(rule => rule.cookie_id === item.cookie_id && rule.item_id === item.item_id) : shippingRules.filter(rule => rule.cookie_id === item.cookie_id && !rule.item_id); const batchStatusText = (status?: string) => { switch (status) { case 'preview': return '待确认'; case 'pending': return '等待中'; case 'running': return '发布中'; case 'canceling': return '正在安全取消'; case 'success': return '成功'; case 'failed': return '失败'; case 'completed': return '已完成'; case 'partially_failed': return '部分失败'; case 'canceled': return '已取消'; default: return status || '-'; } }; const batchStatusClass = (status?: string) => { switch (status) { case 'success': case 'completed': return 'bg-emerald-50 text-emerald-700 border-emerald-100'; case 'partially_failed': case 'failed': return 'bg-red-50 text-red-700 border-red-100'; case 'running': return 'bg-blue-50 text-blue-700 border-blue-100'; case 'canceled': return 'bg-gray-100 text-gray-600 border-gray-200'; default: return 'bg-amber-50 text-amber-700 border-amber-100'; } }; const accountMap = useMemo( () => new Map(accounts.map(account => [account.id, account])), [accounts], ); const visibleItems = useMemo( () => accountFilter ? items.filter(item => item.cookie_id === accountFilter) : items, [accountFilter, items], ); const accountName = (cookieId: string) => { const account = accountMap.get(cookieId); const name = account?.remark || account?.nickname; return name ? `${name} · ${cookieId.slice(0, 6)}` : `账号 ${cookieId.slice(0, 8)}`; }; const accountNickname = (cookieId: string) => { const account = accountMap.get(cookieId); return account?.remark || account?.nickname || '未命名账号'; }; return (

商品管理

监控并管理所有账号下的闲鱼商品。

{recentBatch && !['running', 'canceling'].includes(recentBatch.status) && ( )}
{visibleItems.map(item => { const linkedRules = rulesForItem(item); const hasRule = linkedRules.length > 0; return (
{item.item_image ? ( ) : (
)}
{formatItemPrice(item.item_price)}

{item.item_title}

{accountNickname(item.cookie_id)}
ID: {item.item_id} {hasRule ? : } {hasRule ? `${linkedRules.length} 规则` : '未配置'}
); })} {visibleItems.length === 0 && (
{accountFilter ? '该账号暂无商品数据' : '暂无商品数据,请选择账号进行同步'}
)}
{showEditModal && selectedItem && createPortal(

编辑商品

ID: {selectedItem.item_id}

setEditForm({...editForm, item_title: e.target.value})} /> setEditForm({...editForm, item_price: e.target.value})} /> setEditForm({...editForm, item_category: e.target.value})} />