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

605 lines
24 KiB
TypeScript
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.
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
Building2,
Coins,
ExternalLink,
Layers,
Loader2,
Package,
RefreshCw,
Search,
Sparkles,
Store,
TrendingUp,
} from 'lucide-react';
import { PeerShop, PeerShopsData } from '../types';
import {
analyzePeerShops,
getAccountDetails,
getPeerShops,
refreshPeerShops,
} from '../services/api';
import { EmptyState, NoticeBanner, PageHeader, PageLoading } from './ui';
type Notice = { type: 'success' | 'error' | 'info'; message: string } | null;
type SortKey = 'sold' | 'similarity' | 'credit' | 'reviews';
/** 刷新中轮询间隔(毫秒) */
const POLL_INTERVAL = 2500;
const SORT_OPTIONS: { id: SortKey; label: string }[] = [
{ id: 'sold', label: '按销量' },
{ id: 'similarity', label: '按相似度' },
{ id: 'credit', label: '按信用' },
{ id: 'reviews', label: '按评论数' },
];
/** 4225 → "4225",26000 → "2.6万" */
const formatNum = (n: number): string => {
if (!n || n < 0) return '0';
return n >= 10000 ? `${(n / 10000).toFixed(1).replace(/\.0$/, '')}万` : String(n);
};
/** 闲鱼昵称里的 HTML 实体(&hellip; 等)解码成可读字符。 */
const decodeEntities = (s: string): string =>
s.replace(/&(hellip|nbsp|amp|lt|gt|quot|#39);/g, m => {
const map: Record<string, string> = {
'&hellip;': '…',
'&nbsp;': ' ',
'&amp;': '&',
'&lt;': '<',
'&gt;': '>',
'&quot;': '"',
'&#39;': "'",
};
return map[m] ?? m;
});
/** 秒级时间戳 → "3天前" / "2小时前" */
const formatAge = (ts: number): string => {
if (!ts) return '—';
const diff = Date.now() - ts * 1000;
if (diff < 60_000) return '刚刚';
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}分钟前`;
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}小时前`;
if (diff < 7 * 86_400_000) return `${Math.floor(diff / 86_400_000)}天前`;
const d = new Date(ts * 1000);
return `${d.getMonth() + 1}月${d.getDate()}日`;
};
/** 相似度/参考价值徽章(0-100):高分绿、中分蓝、低分灰,统一百分号与等宽。 */
const ScoreBadge: React.FC<{ value: number; max?: number; suffix?: string }> = ({
value,
max = 100,
suffix = '%',
}) => {
const pct = max > 0 ? value / max : 0;
const cls =
pct >= 0.7
? 'bg-emerald-50 text-emerald-700 border-emerald-200'
: pct >= 0.4
? 'bg-sky-50 text-sky-700 border-sky-200'
: 'bg-[var(--surface-subtle)] text-[var(--text-soft)] border-[var(--border)]';
return (
<span
className={`inline-flex min-w-[3.5rem] justify-center rounded-full border px-2 py-0.5 text-xs font-semibold tabular-nums ${cls}`}
title={`${value} / ${max}`}
>
{value}
{suffix}
</span>
);
};
/** 信用等级:固定 5 格星级(★填充 + ☆衬底,宽度不跳动),无数据时显示搜索信号文案。 */
const CreditCell: React.FC<{ level: number; fallback: string }> = ({ level, fallback }) => {
if (!level) {
return (
<span className="text-xs text-gray-300 dark:text-gray-600" title={fallback || '未获取到信用数据'}>
{fallback || '—'}
</span>
);
}
return (
<span
className="inline-flex flex-col items-center gap-0.5"
title={`信用等级 ${level} 级${fallback ? `(${fallback})` : ''}`}
>
<span className="text-xs leading-none tracking-tight text-amber-500">
{'★'.repeat(level)}
<span className="text-[var(--border)]">{'☆'.repeat(5 - level)}</span>
</span>
<span className="text-[11px] leading-none text-[var(--text-soft)]">
{fallback || `${level}级`}
</span>
</span>
);
};
/** 评论数 + 好评率:两行分开,避免「0 96%」数字粘连。 */
const ReviewsCell: React.FC<{ reviews: number; goodRate: number; detail: string }> = ({
reviews,
goodRate,
detail,
}) => (
<span className="inline-flex flex-col items-end gap-0.5" title={detail}>
<span className="text-sm font-semibold tabular-nums text-[var(--text)]">
{formatNum(reviews)}
</span>
{goodRate > 0 && (
<span className="text-[11px] leading-none tabular-nums text-emerald-600">
{goodRate}% 好评
</span>
)}
</span>
);
/** 信息条统计卡:图标 + 标签 + 值,替代原来挤成一行的小灰字。 */
const StatCard: React.FC<{
icon: React.ElementType;
label: string;
children: React.ReactNode;
title?: string;
}> = ({ icon: Icon, label, children, title }) => (
<div
className="rounded-xl border border-[var(--border)] bg-[var(--surface-subtle)] px-3.5 py-3"
title={title}
>
<div className="flex items-center gap-1.5 text-xs text-[var(--text-soft)]">
<Icon className="h-3.5 w-3.5" />
{label}
</div>
<div className="mt-1.5 truncate text-sm font-semibold text-[var(--text)]">{children}</div>
</div>
);
const PeerShops: React.FC = () => {
const [loading, setLoading] = useState(true);
const [cookieId, setCookieId] = useState('');
const [data, setData] = useState<PeerShopsData | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [progress, setProgress] = useState<{ done: number; total: number; stage: string } | null>(null);
const [sortKey, setSortKey] = useState<SortKey>('sold');
const [notice, setNotice] = useState<Notice>(null);
const [aiText, setAiText] = useState('');
const [aiModel, setAiModel] = useState('');
const [aiLoading, setAiLoading] = useState(false);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const stopPolling = useCallback(() => {
if (pollRef.current) {
clearInterval(pollRef.current);
pollRef.current = null;
}
setRefreshing(false);
setProgress(null);
}, []);
const load = useCallback(async (id: string) => {
try {
const res = await getPeerShops(id);
if (res.data) setData(res.data);
if (res.refreshing) {
setRefreshing(true);
setProgress({
done: res.progress?.done ?? 0,
total: res.progress?.total ?? 0,
stage: res.progress?.stage || '抓取中',
});
}
if (res.progress?.state === 'error' && res.progress.error) {
setNotice({ type: 'error', message: res.progress.error });
}
} catch (err) {
console.error('加载同行店铺失败:', err);
}
}, []);
// 初始化:取第一个账号
useEffect(() => {
let alive = true;
(async () => {
try {
const accounts = await getAccountDetails();
const first = accounts[0];
if (!alive) return;
if (!first) {
setNotice({ type: 'info', message: '请先在「账号管理」添加账号并同步商品,再回到本页。' });
setLoading(false);
return;
}
setCookieId(first.id);
await load(first.id);
} catch (err) {
console.error('初始化同行店铺失败:', err);
} finally {
if (alive) setLoading(false);
}
})();
return () => {
alive = false;
if (pollRef.current) clearInterval(pollRef.current);
};
}, [load]);
// 刷新轮询
useEffect(() => {
if (!refreshing || !cookieId) return;
pollRef.current = setInterval(async () => {
try {
const res = await getPeerShops(cookieId);
setProgress({
done: res.progress?.done ?? 0,
total: res.progress?.total ?? 0,
stage: res.progress?.stage || '抓取中',
});
if (res.progress?.state === 'done') {
stopPolling();
if (res.data) setData(res.data);
setNotice({ type: 'success', message: '同行店铺数据已更新。' });
} else if (res.progress?.state === 'error') {
stopPolling();
setNotice({ type: 'error', message: res.progress.error || '抓取失败,请稍后重试。' });
}
} catch (err) {
console.error('轮询同行店铺失败:', err);
}
}, POLL_INTERVAL);
return () => {
if (pollRef.current) clearInterval(pollRef.current);
};
}, [refreshing, cookieId, stopPolling]);
const triggerRefresh = useCallback(async () => {
if (!cookieId || refreshing) return;
setNotice(null);
setAiText('');
try {
const res = await refreshPeerShops(cookieId);
if (res.status === 'running') {
setRefreshing(true);
return;
}
setRefreshing(true);
setProgress({ done: 0, total: 0, stage: '准备抓取' });
} catch (err: any) {
const msg = err?.response?.data?.detail || err?.message || '触发刷新失败';
setNotice({ type: 'error', message: String(msg) });
}
}, [cookieId, refreshing]);
const runAiAnalyze = useCallback(async () => {
if (!cookieId || aiLoading) return;
setAiLoading(true);
setNotice(null);
try {
const res = await analyzePeerShops(cookieId);
if (res.status === 'ok' && res.analysis) {
setAiText(res.analysis);
setAiModel(res.model || '');
} else if (res.status === 'need_api_key') {
setNotice({
type: 'info',
message: res.message || '尚未配置模型 KEY,请先在「AI 回复设置」填写模型 KEY。',
});
} else {
setNotice({ type: 'error', message: res.message || 'AI 分析失败,请稍后重试。' });
}
} catch (err: any) {
const msg = err?.response?.data?.detail || err?.message || 'AI 分析失败';
setNotice({ type: 'error', message: String(msg) });
} finally {
setAiLoading(false);
}
}, [cookieId, aiLoading]);
const shops = useMemo(() => {
const list = [...(data?.shops || [])];
const bySort: Record<SortKey, (a: PeerShop, b: PeerShop) => number> = {
sold: (a, b) => b.sold - a.sold || b.search_deals - a.search_deals,
similarity: (a, b) => b.similarity - a.similarity || b.value_score - a.value_score,
credit: (a, b) => (b.credit_sort ?? b.credit_level) - (a.credit_sort ?? a.credit_level) || b.good_rate - a.good_rate,
reviews: (a, b) => b.good + b.mid + b.bad - (a.good + a.mid + a.bad) || b.good - a.good,
};
return list.sort(bySort[sortKey]);
}, [data, sortKey]);
if (loading) return <PageLoading label="正在加载同行店铺" />;
const user = data?.user;
const updatedLabel = data?.updated_at ? formatAge(data.updated_at) : '尚未生成';
return (
<div className="flex flex-col gap-4">
<PageHeader
title="同行热卖店铺"
description="按您店铺的类型,从闲鱼实时搜索聚合同类型销量最好的 50 家店铺,给出与您店铺的相似度和参考价值。"
icon={Building2}
badge={
<span className="rounded-full bg-[var(--surface-subtle)] px-2 py-0.5 text-xs text-[var(--text-soft)]">
{data ? `更新于 ${updatedLabel}` : '待生成'}
</span>
}
actions={
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
className="ios-btn-secondary flex items-center gap-1.5 rounded-md px-3 py-2 text-sm"
onClick={() => void runAiAnalyze()}
disabled={aiLoading || !data?.shops?.length}
title={data?.shops?.length ? '用模型 KEY 一键分析最适合您店铺的同行' : '先抓取数据后再分析'}
>
{aiLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />}
{aiLoading ? 'AI 分析中…' : 'AI 一键分析'}
</button>
<button
type="button"
className="ios-btn-primary flex items-center gap-1.5 rounded-md px-3 py-2 text-sm"
onClick={() => void triggerRefresh()}
disabled={refreshing || !cookieId}
>
{refreshing ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
{refreshing ? '抓取中…' : data ? '重新抓取' : '开始分析'}
</button>
</div>
}
/>
{notice && (
<NoticeBanner
type={notice.type === 'info' ? 'success' : notice.type}
message={notice.message}
onClose={() => setNotice(null)}
/>
)}
{refreshing && (
<div className="section-panel">
<div className="flex items-center gap-3 text-sm text-[var(--text-soft)]">
<Loader2 className="h-4 w-4 animate-spin text-[#ff4400]" />
<span>
{progress?.stage || '抓取中…'}
{progress && progress.total > 0 ? `(${progress.done}/${progress.total})` : ''}
</span>
</div>
{progress && progress.total > 0 && (
<div className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]">
<div
className="h-full rounded-full bg-[#ff4400] transition-all"
style={{ width: `${Math.min(100, Math.round((progress.done / progress.total) * 100))}%` }}
/>
</div>
)}
<p className="mt-2 text-xs text-[var(--text-soft)]">
约需 1 分钟:按店铺类型搜索 → 聚合高销量店铺 → 逐店补齐销量/信用/主页。
</p>
</div>
)}
{user && (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
<StatCard icon={Package} label="已同步商品">
{user.items_count} 件
</StatCard>
<StatCard icon={Coins} label="价格中位数">
{user.med_price > 0 ? `¥${user.med_price}` : '—'}
</StatCard>
<StatCard
icon={Layers}
label="店铺类目"
title={(user.categories || []).join('、') || undefined}
>
{(() => {
const uniq = Array.from(new Set((user.categories || []).map(c => String(c).trim()).filter(Boolean)));
if (!uniq.length) return '—';
const named = uniq.filter(c => !/^\d+$/.test(c));
// 纯数字是闲鱼类目 ID,对用户没意义 → 显示去重后的数量
return named.length ? named.slice(0, 2).join('、') : `${uniq.length} 个类目`;
})()}
</StatCard>
<StatCard icon={Search} label="匹配关键词" title={(data?.keywords || []).join('、')}>
{data?.keywords?.length ? (
<span className="flex flex-wrap gap-1">
{data.keywords.slice(0, 4).map(k => (
<span
key={k}
className="rounded bg-[var(--surface-strong)] px-1.5 py-0.5 text-[11px] font-medium"
>
{k}
</span>
))}
{data.keywords.length > 4 && (
<span className="text-[11px] font-normal text-[var(--text-soft)]">
+{data.keywords.length - 4}
</span>
)}
</span>
) : (
'—'
)}
</StatCard>
</div>
)}
{aiText && (
<div className="section-panel">
<div className="mb-2 flex items-center gap-2 text-sm font-semibold">
<Sparkles className="h-4 w-4 text-amber-500" />
AI 分析结果
{aiModel && <span className="text-xs font-normal text-[var(--text-soft)]">({aiModel})</span>}
</div>
<div className="whitespace-pre-wrap text-sm leading-6 text-[var(--text)]">{aiText}</div>
</div>
)}
{!data && !refreshing && (
<EmptyState
title="还没有同行店铺数据"
description="点击右上角「开始分析」,将按您店铺的类型搜索闲鱼同类型高销量店铺,并计算相似度与参考价值。需要先在账号管理添加账号并同步商品。"
icon={TrendingUp}
/>
)}
{data && shops.length === 0 && !refreshing && (
<EmptyState
title={data.error || '没有拿到同类型店铺'}
description="可能是搜索命中风控或关键词过窄,稍后点「重新抓取」再试。"
icon={Building2}
/>
)}
{shops.length > 0 && (
<div className="section-panel">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-1 rounded-lg bg-[var(--surface-subtle)] p-1">
{SORT_OPTIONS.map(opt => (
<button
key={opt.id}
type="button"
onClick={() => setSortKey(opt.id)}
className={`rounded-md px-3 py-1.5 text-xs font-medium transition ${
sortKey === opt.id
? 'bg-[var(--surface)] text-[var(--text)] shadow-sm'
: 'text-[var(--text-soft)] hover:text-[var(--text)]'
}`}
>
{opt.label}
</button>
))}
</div>
<span className="text-xs text-[var(--text-soft)]">
共 {shops.length} 家 · 点击店铺名打开闲鱼主页
</span>
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-sm">
<thead>
<tr className="border-b border-[var(--border-strong)] text-xs text-[var(--text-soft)]">
<th className="w-14 py-2.5 pr-3 text-center font-semibold">排名</th>
<th className="py-2.5 pr-3 text-left font-semibold">店铺</th>
<th className="w-24 py-2.5 pr-3 text-right font-semibold">销量</th>
<th className="w-20 py-2.5 pr-3 text-center font-semibold">信用</th>
<th className="w-24 py-2.5 pr-3 text-right font-semibold">评论数</th>
<th className="w-24 py-2.5 pr-3 text-center font-semibold">相似度</th>
<th className="w-24 py-2.5 pr-3 text-center font-semibold">参考价值</th>
<th className="w-24 py-2.5 text-right font-semibold">操作</th>
</tr>
</thead>
<tbody>
{shops.map(shop => {
const reviews = Math.max(0, shop.good) + Math.max(0, shop.mid) + Math.max(0, shop.bad);
const rankCls =
shop.rank === 1
? 'bg-gradient-to-b from-amber-300 to-amber-500 text-amber-950 shadow-[0_1px_3px_rgba(245,158,11,0.45)]'
: shop.rank === 2
? 'bg-gradient-to-b from-gray-200 to-gray-400 text-gray-700 shadow-[0_1px_3px_rgba(156,163,175,0.45)]'
: shop.rank === 3
? 'bg-gradient-to-b from-orange-300 to-orange-500 text-orange-950 shadow-[0_1px_3px_rgba(249,115,22,0.45)]'
: 'bg-[var(--surface-subtle)] text-[var(--text-soft)]';
return (
<tr
key={shop.seller_id || shop.url}
className={`border-b border-[var(--border)] align-middle transition-colors last:border-0 even:bg-[var(--surface-subtle)] hover:bg-[var(--surface-strong)]`}
>
<td className="py-3 pr-3 text-center">
<span
className={`inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-bold tabular-nums ${rankCls}`}
>
{shop.rank}
</span>
</td>
<td className="py-3 pr-3">
<a
href={shop.url}
target="_blank"
rel="noopener noreferrer"
className="group flex max-w-[280px] items-center gap-1.5 font-semibold text-[var(--text)] hover:text-[#ff4400]"
title={`在闲鱼查看「${shop.nick}」的店铺详情与全部商品`}
>
<span className="truncate">{decodeEntities(shop.nick)}</span>
<ExternalLink className="h-3.5 w-3.5 shrink-0 text-[var(--text-soft)] transition-colors group-hover:text-[#ff4400]" />
</a>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-xs text-[var(--text-soft)]">
{shop.city && <span>{shop.city}</span>}
{shop.price_avg > 0 && <span>均价 ¥{shop.price_avg}</span>}
{shop.tags?.slice(0, 2).map(t => (
<span
key={t}
className="rounded bg-[var(--surface-strong)] px-1.5 py-0.5 leading-4"
>
{t}
</span>
))}
{!!shop.keywords_hit?.length && (
<span
className="rounded bg-amber-500/10 px-1.5 py-0.5 leading-4 text-amber-600 ring-1 ring-inset ring-amber-500/30"
title={`命中类型关键词:${shop.keywords_hit.join('、')}`}
>
命中 {shop.keywords_hit.length} 词
</span>
)}
</div>
</td>
<td className="py-3 pr-3 text-right font-semibold tabular-nums">
{formatNum(shop.sold)}
</td>
<td className="py-3 pr-3 text-center">
<CreditCell level={shop.credit_level} fallback={shop.search_credit} />
</td>
<td className="py-3 pr-3 text-right">
<ReviewsCell
reviews={reviews}
goodRate={shop.good_rate}
detail={`好评 ${shop.good} / 中评 ${shop.mid} / 差评 ${shop.bad}`}
/>
</td>
<td className="py-3 pr-3 text-center">
<ScoreBadge value={shop.similarity} label="与您店铺商品词集的重合度" />
</td>
<td className="py-3 pr-3 text-center">
<ScoreBadge
value={shop.value_score}
label="相似度 40% + 销量 25% + 信用 20% + 好评率 15%"
/>
</td>
<td className="py-3 text-right">
<div className="flex items-center justify-end gap-2">
<a
href={shop.url}
target="_blank"
rel="noopener noreferrer"
className="rounded-md border border-[var(--border)] px-2.5 py-1 text-xs font-medium text-[var(--text-soft)] transition-colors hover:border-[#ff4400] hover:text-[#ff4400]"
>
店铺
</a>
<a
href={shop.item_url}
target="_blank"
rel="noopener noreferrer"
className="rounded-md border border-[var(--border)] px-2.5 py-1 text-xs font-medium text-[var(--text-soft)] transition-colors hover:border-[#ff4400] hover:text-[#ff4400]"
>
商品
</a>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<p className="mt-3 border-t border-[var(--border)] pt-3 text-xs leading-5 text-[var(--text-soft)]">
相似度 = 与您店铺商品词集的重合度(含价格带接近度);参考价值 = 相似度 40% + 销量 25% + 信用 20% + 好评率 15%。
数据来自闲鱼实时搜索,每次抓取约 1 分钟,可点「重新抓取」更新。
</p>
</div>
)}
</div>
);
};
export default PeerShops;