"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([]); const [rangeSessions, setRangeSessions] = useState([]); const [loading, setLoading] = useState(false); const [error, setError] = useState(""); const [selected, setSelected] = useState(null); const [focusSlot, setFocusSlot] = useState(null); const [tag, setTag] = useState(""); const [platform, setPlatform] = useState("douyin"); const [tagOptions, setTagOptions] = useState([]); 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[] = 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 = {}; 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 (

🕐 开播时段规律

一天拆成 6 个 4 小时段,按 开播时刻 归类;可看单日明细或近 7 天稳定规律。

{error ? (
{error}
) : null}
s.room_id || s.id)).size} hint="同一房间多次开播只计一次" accent="sky" /> n + (Number(s.duration_seconds) || 0), 0))} hint="下方时间轴始终展示锚点日明细" accent="amber" />

{rangeMode === "7d" ? "近 7 天六段开播分布(规律)" : "六段开播分布"}

{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 ( ); })}
{rangeMode === "7d" ? (

日 × 时段热力(开播次数)

{SLOTS.map((s) => ( ))} {heat.dates.map((d) => ( {heat.map[d].map((n, i) => { const intensity = n / heat.max; return ( ); })} ))}
日期 {s.label}
{d.slice(5)} {d === date ? 锚点 : null}

点击格子可跳到该日该时段明细。

) : null} {!loading && dayTotalOpens === 0 ? ( ) : (
时间轴:{date} 开播明细
{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 (

{slot.label} {slot.range}

{slot.hint} {isPeak ? ( 今日高峰 ) : null} {isNow ? : null}

开播 {st.opens} 场 · {st.uniqueRooms} 个直播间 · 占当日 {pct}% {st.live > 0 ? ` · 仍在播 ${st.live}` : ""} {st.duration > 0 ? ` · 时长合计 ${fmtDuration(st.duration)}` : ""}

{list.length === 0 ? (
该时段无人开播
) : (
{list.map((session) => (
{fmtClock(session.started_at)} 开播 {session.status === "active" || !session.ended_at ? ( ) : ( {fmtDuration(session.duration_seconds)} )}
{session.title ? (

{session.title}

) : null}
void load({ silent: true })} onError={(m) => setError(m)} />
))}
)}
); })}
)} setSelected(null)} extraRows={ selected ? [ { label: "所属时段", value: (() => { const idx = slotIndexFromStartedAt(selected.started_at); if (idx == null) return "—"; return `${SLOTS[idx].label}(${SLOTS[idx].range})`; })(), }, ] : undefined } /> ); }