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

492 lines
20 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,
ExternalLink,
Loader2,
RefreshCw,
Sparkles,
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);
};
/** 秒级时间戳 → "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()}日`;
};
/** 相似度/参考价值徽章:高分绿、中分蓝、低分灰 */
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-100 text-emerald-700'
: pct >= 0.4
? 'bg-sky-100 text-sky-700'
: 'bg-[var(--surface-subtle)] text-[var(--text-soft)]';
return (
<span className={`inline-flex min-w-[3rem] justify-center rounded-full px-2 py-0.5 text-xs font-semibold ${cls}`}>
{value}
{suffix}
</span>
);
};
/** 信用等级:5 星样式(level 1-5),无数据时显示搜索信号文案 */
const CreditCell: React.FC<{ level: number; fallback: string }> = ({ level, fallback }) => {
if (!level) {
return (
<span className="text-xs text-[var(--text-soft)]" title={fallback}>
{fallback || '—'}
</span>
);
}
return (
<span className="inline-flex items-center gap-1 text-xs font-medium text-amber-600" title={`信用等级 ${level} 级`}>
{'★'.repeat(level)}
<span className="text-[var(--text-soft)] font-normal">{level}级</span>
</span>
);
};
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="section-panel flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-[var(--text-soft)]">
<span>您的店铺:已同步 {user.items_count} 件商品</span>
{user.med_price > 0 && <span>价格中位数 ¥{user.med_price}</span>}
{user.categories?.length > 0 && <span>类目:{user.categories.slice(0, 3).join('、')}</span>}
{data?.keywords?.length > 0 && <span>匹配关键词:{data.keywords.slice(0, 5).join('、')}</span>}
</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-white 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-[860px] text-sm">
<thead>
<tr className="border-b border-[var(--border)] text-left text-xs text-[var(--text-soft)]">
<th className="py-2 pr-3 font-medium">排名</th>
<th className="py-2 pr-3 font-medium">店铺</th>
<th className="py-2 pr-3 text-right font-medium">销量</th>
<th className="py-2 pr-3 font-medium">信用</th>
<th className="py-2 pr-3 text-right font-medium">评论数</th>
<th className="py-2 pr-3 text-right font-medium">相似度</th>
<th className="py-2 pr-3 text-right font-medium">参考价值</th>
<th className="py-2 text-right font-medium">操作</th>
</tr>
</thead>
<tbody>
{shops.map(shop => {
const reviews = Math.max(0, shop.good) + Math.max(0, shop.mid) + Math.max(0, shop.bad);
return (
<tr
key={shop.seller_id || shop.url}
className="border-b border-[var(--border)] last:border-0 hover:bg-[var(--surface-subtle)]"
>
<td className="py-2.5 pr-3">
<span
className={`inline-flex h-6 w-6 items-center justify-center rounded-full text-xs font-bold ${
shop.rank === 1
? 'bg-amber-400 text-white'
: shop.rank === 2
? 'bg-gray-300 text-gray-700'
: shop.rank === 3
? 'bg-orange-300 text-orange-900'
: 'bg-[var(--surface-subtle)] text-[var(--text-soft)]'
}`}
>
{shop.rank}
</span>
</td>
<td className="py-2.5 pr-3">
<a
href={shop.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 font-medium text-[var(--text)] hover:text-[#ff4400] hover:underline"
title={`在闲鱼查看「${shop.nick}」的店铺详情与全部商品`}
>
{shop.nick}
<ExternalLink className="h-3.5 w-3.5 shrink-0 text-[var(--text-soft)]" />
</a>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-[var(--text-soft)]">
{shop.city && <span>{shop.city}</span>}
{shop.tags?.slice(0, 2).map(t => (
<span key={t} className="rounded bg-[var(--surface-subtle)] px-1.5 py-0.5">
{t}
</span>
))}
{shop.price_avg > 0 && <span>均价 ¥{shop.price_avg}</span>}
{!!shop.keywords_hit?.length && (
<span
className="rounded bg-[var(--surface-subtle)] px-1.5 py-0.5 text-[var(--text-soft)]"
title={`命中类型关键词:${shop.keywords_hit.join('、')}`}
>
命中{shop.keywords_hit.length}词
</span>
)}
</div>
</td>
<td className="py-2.5 pr-3 text-right font-semibold">{formatNum(shop.sold)}</td>
<td className="py-2.5 pr-3">
<CreditCell level={shop.credit_level} fallback={shop.search_credit} />
</td>
<td className="py-2.5 pr-3 text-right" title={`好评 ${shop.good} / 中评 ${shop.mid} / 差评 ${shop.bad}`}>
<span className="font-medium">{formatNum(reviews)}</span>
{shop.good_rate > 0 && (
<span className="ml-1 text-xs text-emerald-600">{shop.good_rate}%</span>
)}
</td>
<td className="py-2.5 pr-3 text-right">
<ScoreBadge value={shop.similarity} />
</td>
<td className="py-2.5 pr-3 text-right">
<ScoreBadge value={shop.value_score} />
</td>
<td className="py-2.5 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 py-1 text-xs 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 py-1 text-xs hover:border-[#ff4400] hover:text-[#ff4400]"
>
商品
</a>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
<p className="mt-3 text-xs leading-5 text-[var(--text-soft)]">
相似度 = 与您店铺商品词集的重合度(含价格带接近度);参考价值 = 相似度 40% + 销量 25% + 信用 20% + 好评率 15%。
数据来自闲鱼实时搜索,每次抓取约 1 分钟,可点「重新抓取」更新。
</p>
</div>
)}
</div>
);
};
export default PeerShops;