douyinWEB/frontend/src/app/slots/page.tsx

580 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.

"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { Loader2, RefreshCw } from "lucide-react";
import { Shell } from "@/components/Shell";
import { SessionDetailModal } from "@/components/SessionDetailModal";
import { RoomQuickActions } from "@/components/RoomQuickActions";
import { EmptyState, LivePulse, StatTile, PlatformBadge } from "@/components/ui";
import { fetchJson, fmtDuration, sessionCoverSrc, todayBeijingISO, shiftBeijingISO, beijingHourFromTs, fmtClock, beijingDateFromTs, beijingParts, detectPlatform } from "@/lib/api";
import { useAutoRefresh, type RefreshOpts } from "@/lib/realtime";
type Session = {
id: string;
anchor_name?: string;
source_url?: string;
room_id?: string;
room_pk?: string;
title?: string;
started_at?: number;
ended_at?: number | null;
duration_seconds?: number;
push_date?: string;
cover_url?: string;
status?: string;
end_reason?: string;
cover_proxy_url?: string;
};
const SLOTS = [
{ id: 0, label: "凌晨", range: "00:00 – 04:00", hint: "深夜 / 凌晨档" },
{ id: 1, label: "清晨", range: "04:00 – 08:00", hint: "早市 / 早餐档" },
{ id: 2, label: "上午", range: "08:00 – 12:00", hint: "上午营业档" },
{ id: 3, label: "午后", range: "12:00 – 16:00", hint: "午市 / 下午档" },
{ id: 4, label: "傍晚", range: "16:00 – 20:00", hint: "傍晚高峰前" },
{ id: 5, label: "夜间", range: "20:00 – 24:00", hint: "晚间主峰档" },
] as const;
const SLOT_ACCENT = [
"border-violet-400/30 bg-violet-500/10 text-violet-100",
"border-sky-400/30 bg-sky-500/10 text-sky-100",
"border-teal-400/30 bg-teal-500/10 text-teal-100",
"border-amber-400/30 bg-amber-500/10 text-amber-100",
"border-orange-400/30 bg-orange-500/10 text-orange-100",
"border-rose-400/30 bg-rose-500/10 text-rose-100",
] as const;
function todayLocalISO(): string {
return todayBeijingISO();
}
function shiftDateISO(iso: string, days: number): string {
return shiftBeijingISO(iso, days);
}
function slotIndexFromStartedAt(ts?: number): number | null {
if (!ts) return null;
return Math.min(5, Math.floor(beijingHourFromTs(ts) / 4));
}
export default function SlotsPage() {
const [date, setDate] = useState(todayLocalISO);
const [rangeMode, setRangeMode] = useState<"day" | "7d">("day");
const [daySessions, setDaySessions] = useState<Session[]>([]);
const [rangeSessions, setRangeSessions] = useState<Session[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [selected, setSelected] = useState<Session | null>(null);
const [focusSlot, setFocusSlot] = useState<number | null>(null);
const [tag, setTag] = useState("");
const [platform, setPlatform] = useState("douyin");
const [tagOptions, setTagOptions] = useState<string[]>([]);
const rangeFrom = useMemo(() => (rangeMode === "7d" ? shiftDateISO(date, -6) : date), [date, rangeMode]);
useEffect(() => {
if (typeof window === "undefined") return;
const params = new URLSearchParams(window.location.search);
const d = params.get("date");
const f = params.get("focus");
const t = params.get("tag");
if (d && /^\d{4}-\d{2}-\d{2}$/.test(d)) setDate(d);
if (f != null && f !== "" && !Number.isNaN(Number(f))) {
const n = Number(f);
if (n >= 0 && n <= 5) setFocusSlot(n);
}
if (t) setTag(t);
const pf = params.get("platform");
if (pf) setPlatform(pf);
// default to douyin if not specified in URL
}, []);
useEffect(() => {
void fetchJson("/api/rooms/tags")
.then((d) => setTagOptions(d.tags || []))
.catch(() => undefined);
}, []);
const load = useCallback(async (opts?: RefreshOpts) => {
const silent = Boolean(opts?.silent);
if (!silent) {
setLoading(true);
setError("");
}
try {
const dayParams = new URLSearchParams({
date_from: date,
date_to: date,
limit: "2000",
offset: "0",
});
if (tag) dayParams.set("tag", tag);
if (platform) dayParams.set("platform", platform);
const dayData = await fetchJson(`/api/sessions?${dayParams}`);
setDaySessions(dayData.sessions || []);
if (rangeMode === "7d") {
const rangeParams = new URLSearchParams({
date_from: shiftDateISO(date, -6),
date_to: date,
limit: "2000",
offset: "0",
});
if (tag) rangeParams.set("tag", tag);
if (platform) rangeParams.set("platform", platform);
const rangeData = await fetchJson(`/api/sessions?${rangeParams}`);
setRangeSessions(rangeData.sessions || []);
} else {
setRangeSessions(dayData.sessions || []);
}
} catch (e) {
if (!silent) setError((e as Error).message);
} finally {
if (!silent) setLoading(false);
}
}, [date, rangeMode, tag, platform]);
useAutoRefresh(load, { intervalMs: 20000 });
const patternSessions = rangeMode === "7d" ? rangeSessions : daySessions;
const buckets = useMemo(() => {
const groups: Session[][] = Array.from({ length: 6 }, () => []);
for (const s of daySessions) {
const idx = slotIndexFromStartedAt(s.started_at);
if (idx == null) continue;
groups[idx].push(s);
}
for (const g of groups) g.sort((a, b) => (a.started_at || 0) - (b.started_at || 0));
return groups;
}, [daySessions]);
const daySlotStats = useMemo(() => {
return buckets.map((list) => {
const rooms = new Set(list.map((s) => s.room_id || s.anchor_name || s.id));
const duration = list.reduce((sum, s) => sum + (Number(s.duration_seconds) || 0), 0);
const live = list.filter((s) => s.status === "active" || !s.ended_at).length;
return { opens: list.length, uniqueRooms: rooms.size, duration, live };
});
}, [buckets]);
const patternSlotStats = useMemo(() => {
const opens = Array(6).fill(0) as number[];
const rooms: Set<string>[] = Array.from({ length: 6 }, () => new Set());
for (const s of patternSessions) {
const idx = slotIndexFromStartedAt(s.started_at);
if (idx == null) continue;
opens[idx] += 1;
rooms[idx].add(String(s.room_id || s.anchor_name || s.id));
}
return opens.map((n, i) => ({ opens: n, uniqueRooms: rooms[i].size }));
}, [patternSessions]);
const heat = useMemo(() => {
const dates: string[] = [];
for (let i = 6; i >= 0; i -= 1) dates.push(shiftDateISO(date, -i));
const map: Record<string, number[]> = {};
for (const d of dates) map[d] = [0, 0, 0, 0, 0, 0];
for (const s of rangeSessions) {
const d = s.push_date || beijingDateFromTs(s.started_at);
const idx = slotIndexFromStartedAt(s.started_at);
if (!d || idx == null || !map[d]) continue;
map[d][idx] += 1;
}
const max = Math.max(1, ...dates.flatMap((d) => map[d]));
return { dates, map, max };
}, [date, rangeSessions]);
const dayTotalOpens = useMemo(() => daySlotStats.reduce((n, s) => n + s.opens, 0), [daySlotStats]);
const patternTotal = useMemo(() => patternSlotStats.reduce((n, s) => n + s.opens, 0), [patternSlotStats]);
const peakSlot = useMemo(() => {
const stats = rangeMode === "7d" ? patternSlotStats : daySlotStats;
let best = 0;
for (let i = 1; i < stats.length; i += 1) {
if (stats[i].opens > stats[best].opens) best = i;
}
return stats[best].opens > 0 ? best : null;
}, [daySlotStats, patternSlotStats, rangeMode]);
const currentSlot =
date === todayLocalISO() ? Math.min(5, Math.floor(beijingParts().hour / 4)) : null;
const visibleSlots = focusSlot == null ? SLOTS : SLOTS.filter((s) => s.id === focusSlot);
const displayStats = daySlotStats;
return (
<Shell>
<div className="mb-4 flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="font-display text-2xl font-semibold">🕐 开播时段规律</h2>
<p className="text-sm text-slate-400">
一天拆成 6 个 4 小时段,按
<span className="mx-1 text-teal-200/90">开播时刻</span>
归类;可看单日明细或近 7 天稳定规律。
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex rounded-xl border border-white/10 bg-black/30 p-0.5 text-sm">
<button
type="button"
onClick={() => setRangeMode("day")}
className={`rounded-lg px-3 py-1.5 ${rangeMode === "day" ? "bg-white/15 text-white" : "text-slate-400"}`}
>
单日
</button>
<button
type="button"
onClick={() => setRangeMode("7d")}
className={`rounded-lg px-3 py-1.5 ${rangeMode === "7d" ? "bg-white/15 text-white" : "text-slate-400"}`}
>
近 7 天
</button>
</div>
<select
value={platform}
onChange={(e) => setPlatform(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-white"
>
<option value="">全部平台</option>
<option value="douyin">抖音</option>
<option value="youtube">YouTube</option>
</select>
<select
value={tag}
onChange={(e) => setTag(e.target.value)}
className="rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-white"
>
<option value="">全部标签</option>
<option value="收藏">收藏</option>
<option value="重点">重点</option>
{tagOptions.filter((t) => t !== "重点" && t !== "收藏").map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
<label className="text-xs text-slate-400">
锚点日
<input
type="date"
value={date}
onChange={(e) => setDate(e.target.value || todayLocalISO())}
className="ml-2 rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm text-white"
/>
</label>
<button
type="button"
onClick={() => setDate(todayLocalISO())}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-sm hover:bg-white/10"
>
今天
</button>
<button
type="button"
onClick={() => void load()}
className="btn-glow inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-3 py-2 text-sm"
>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
刷新
</button>
</div>
</div>
{error ? (
<div className="mb-4 rounded-xl border border-rose-500/30 bg-rose-500/10 px-4 py-3 text-sm">{error}</div>
) : null}
<div className="mb-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<StatTile
emoji="📡"
label={rangeMode === "7d" ? "7 日开播场次" : "当日开播场次"}
value={rangeMode === "7d" ? patternTotal : dayTotalOpens}
hint={rangeMode === "7d" ? `${rangeFrom} → ${date}` : date}
accent="teal"
/>
<StatTile
emoji="🏠"
label="独立直播间"
value={new Set((rangeMode === "7d" ? patternSessions : daySessions).map((s) => s.room_id || s.id)).size}
hint="同一房间多次开播只计一次"
accent="sky"
/>
<StatTile
emoji="🔥"
label={rangeMode === "7d" ? "稳定高峰时段" : "当日高峰时段"}
value={peakSlot == null ? "—" : SLOTS[peakSlot].label}
hint={
peakSlot == null
? "暂无数据"
: `${SLOTS[peakSlot].range} · ${(rangeMode === "7d" ? patternSlotStats : daySlotStats)[peakSlot].opens} 场`
}
accent="rose"
/>
<StatTile
emoji="⏱️"
label="当日累计时长"
value={fmtDuration(daySessions.reduce((n, s) => n + (Number(s.duration_seconds) || 0), 0))}
hint="下方时间轴始终展示锚点日明细"
accent="amber"
/>
</div>
<div className="mb-6 glass-panel rounded-2xl p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2">
<h3 className="font-display text-sm font-semibold text-slate-200">
{rangeMode === "7d" ? "近 7 天六段开播分布(规律)" : "六段开播分布"}
</h3>
<button
type="button"
onClick={() => setFocusSlot(null)}
className={`rounded-lg px-2.5 py-1 text-xs ${
focusSlot == null ? "bg-white/15 text-white" : "bg-white/5 text-slate-400 hover:bg-white/10"
}`}
>
看全天明细
</button>
</div>
<div className="grid gap-2 sm:grid-cols-3 lg:grid-cols-6">
{SLOTS.map((slot) => {
const st = (rangeMode === "7d" ? patternSlotStats : daySlotStats)[slot.id];
const total = rangeMode === "7d" ? patternTotal : dayTotalOpens;
const pct = total > 0 ? Math.round((st.opens / total) * 100) : 0;
const isPeak = peakSlot === slot.id;
const isNow = currentSlot === slot.id;
const active = focusSlot === slot.id;
return (
<button
key={slot.id}
type="button"
onClick={() => setFocusSlot(active ? null : slot.id)}
className={`rounded-xl border px-3 py-3 text-left transition ${
active || isPeak
? "border-teal-400/40 bg-teal-500/10"
: "border-white/10 bg-black/20 hover:bg-white/[0.04]"
}`}
>
<div className="flex items-center justify-between gap-1">
<span className="text-xs font-medium text-white">{slot.label}</span>
{isNow ? <LivePulse label="当前" /> : null}
</div>
<div className="mt-0.5 text-[10px] text-slate-500">{slot.range}</div>
<div className="mt-2 font-display text-xl font-semibold text-white">{st.opens}</div>
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-white/5">
<div
className="h-full rounded-full bg-gradient-to-r from-teal-400/80 to-rose-400/70"
style={{ width: `${pct}%` }}
/>
</div>
<div className="mt-1 flex justify-between text-[10px] text-slate-500">
<span>{st.uniqueRooms} 间</span>
<span>{pct}%</span>
</div>
</button>
);
})}
</div>
</div>
{rangeMode === "7d" ? (
<div className="mb-6 glass-panel rounded-2xl p-4">
<h3 className="mb-3 font-display text-sm font-semibold text-slate-200">日 × 时段热力(开播次数)</h3>
<div className="overflow-x-auto">
<table className="min-w-full text-center text-xs">
<thead>
<tr className="text-slate-500">
<th className="px-2 py-2 text-left font-normal">日期</th>
{SLOTS.map((s) => (
<th key={s.id} className="px-2 py-2 font-normal">
{s.label}
</th>
))}
</tr>
</thead>
<tbody>
{heat.dates.map((d) => (
<tr key={d} className={d === date ? "bg-teal-500/5" : undefined}>
<td className="whitespace-nowrap px-2 py-1.5 text-left text-slate-300">
{d.slice(5)}
{d === date ? <span className="ml-1 text-teal-300">锚点</span> : null}
</td>
{heat.map[d].map((n, i) => {
const intensity = n / heat.max;
return (
<td key={`${d}-${i}`} className="px-1 py-1">
<button
type="button"
title={`${d} ${SLOTS[i].label}: ${n}`}
onClick={() => {
setDate(d);
setFocusSlot(i);
setRangeMode("day");
}}
className="mx-auto flex h-9 w-full min-w-[2.5rem] items-center justify-center rounded-md border border-white/5 tabular-nums"
style={{
background: `rgba(45, 212, 191, ${0.08 + intensity * 0.55})`,
color: intensity > 0.55 ? "#ecfeff" : "#94a3b8",
}}
>
{n || "·"}
</button>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
<p className="mt-2 text-[11px] text-slate-500">点击格子可跳到该日该时段明细。</p>
</div>
) : null}
{!loading && dayTotalOpens === 0 ? (
<EmptyState
emoji="🕐"
title="这一天还没有开播记录"
desc="换一天看看,或切到「近 7 天」查看整体开播规律。"
/>
) : (
<div className="relative space-y-0 pl-2">
<div className="mb-3 text-xs text-slate-500">时间轴:{date} 开播明细</div>
<div className="pointer-events-none absolute bottom-4 left-[22px] top-10 w-0.5 bg-gradient-to-b from-teal-400/50 via-amber-400/25 to-rose-400/20" />
{visibleSlots.map((slot) => {
const list = buckets[slot.id];
const st = displayStats[slot.id];
const pct = dayTotalOpens > 0 ? Math.round((st.opens / dayTotalOpens) * 100) : 0;
const isPeak = peakSlot === slot.id && rangeMode === "day";
const isNow = currentSlot === slot.id;
return (
<section key={slot.id} className="relative pb-8 pl-10">
<div
className={`absolute left-3 top-3 flex h-5 w-5 items-center justify-center rounded-full border-2 ${
isPeak
? "border-rose-400 bg-rose-500/40"
: isNow
? "border-teal-300 bg-teal-400/50"
: "border-white/30 bg-slate-900"
}`}
>
<span className="h-1.5 w-1.5 rounded-full bg-white" />
</div>
<div className="glass-panel rounded-2xl p-4">
<div className="mb-3 flex flex-wrap items-end justify-between gap-3">
<div>
<div className="flex flex-wrap items-center gap-2">
<h3 className="font-display text-lg font-semibold text-white">
{slot.label}
<span className="ml-2 font-mono text-sm font-normal text-slate-400">{slot.range}</span>
</h3>
<span className={`rounded-md border px-2 py-0.5 text-[11px] ${SLOT_ACCENT[slot.id]}`}>
{slot.hint}
</span>
{isPeak ? (
<span className="rounded-md border border-rose-400/40 bg-rose-500/15 px-2 py-0.5 text-[11px] text-rose-100">
今日高峰
</span>
) : null}
{isNow ? <LivePulse label="当前时段" /> : null}
</div>
<p className="mt-1 text-xs text-slate-500">
开播 {st.opens} 场 · {st.uniqueRooms} 个直播间 · 占当日 {pct}%
{st.live > 0 ? ` · 仍在播 ${st.live}` : ""}
{st.duration > 0 ? ` · 时长合计 ${fmtDuration(st.duration)}` : ""}
</p>
</div>
</div>
{list.length === 0 ? (
<div className="rounded-xl border border-dashed border-white/10 bg-black/20 px-4 py-8 text-center text-sm text-slate-500">
该时段无人开播
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{list.map((session) => (
<article
key={session.id}
className="hover-lift flex gap-3 rounded-xl border border-white/10 bg-black/25 p-2.5"
>
<button type="button" className="shrink-0" onClick={() => setSelected(session)} title="查看详情">
{sessionCoverSrc(session) ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={sessionCoverSrc(session)}
alt=""
className="h-20 w-14 rounded-lg object-cover ring-1 ring-white/10"
/>
) : (
<div className="flex h-20 w-14 items-center justify-center rounded-lg bg-slate-900 text-[10px] text-slate-500 ring-1 ring-white/10">
无图
</div>
)}
</button>
<div className="min-w-0 flex-1">
<button
type="button"
onClick={() => setSelected(session)}
className="block max-w-full truncate text-left text-sm font-medium text-teal-100 hover:text-white hover:underline"
>
{session.anchor_name || session.room_id || "未命名直播间"}
</button>
<div className="mt-1 flex flex-wrap items-center gap-1.5 text-[11px] text-slate-500">
<PlatformBadge platform={detectPlatform(session)} />
<span className="font-mono text-slate-400">{fmtClock(session.started_at)} 开播</span>
{session.status === "active" || !session.ended_at ? (
<LivePulse />
) : (
<span>{fmtDuration(session.duration_seconds)}</span>
)}
</div>
{session.title ? (
<p className="mt-1 line-clamp-2 text-[11px] text-slate-500">{session.title}</p>
) : null}
<div className="mt-2">
<RoomQuickActions
compact
room={{
room_pk: session.room_pk,
room_id: session.room_id,
source_url: session.source_url,
anchor_name: session.anchor_name,
}}
onDone={() => void load({ silent: true })}
onError={(m) => setError(m)}
/>
</div>
</div>
</article>
))}
</div>
)}
</div>
</section>
);
})}
</div>
)}
<SessionDetailModal
session={selected}
onClose={() => setSelected(null)}
extraRows={
selected
? [
{
label: "所属时段",
value: (() => {
const idx = slotIndexFromStartedAt(selected.started_at);
if (idx == null) return "—";
return `${SLOTS[idx].label}(${SLOTS[idx].range})`;
})(),
},
]
: undefined
}
/>
</Shell>
);
}