gongxiangp2/components/department-dashboard/ValueMetricsDashboard.tsx
2026-09-07 16:36:47 +08:00

155 lines
13 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 {
ArrowDownToLine,
BarChart3,
Database,
RefreshCw,
} from 'lucide-react'
import DepartmentShell from './DepartmentShell'
import type { ValueMetricsInsights, ValueMetricsMaterial } from '@/lib/value-metrics'
type ViewState = {
data: ValueMetricsInsights | null
loading: boolean
error: string | null
}
const DETAIL_PAGE_SIZE = 100
function formatRate(rate: number | null) {
if (rate === null) return '—'
return `${Number.isInteger(rate) ? rate.toFixed(0) : rate.toFixed(1)}%`
}
function formatDate(value: string) {
const date = new Date(value)
if (Number.isNaN(date.getTime())) return '—'
return new Intl.DateTimeFormat('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit',
timeZone: 'Asia/Shanghai',
}).format(date)
}
function materialMeta(material: ValueMetricsMaterial) {
return [material.categoryName, material.sceneName, material.platformName].filter(Boolean).join(' · ')
}
function MaterialTable({ materials }: { materials: ValueMetricsMaterial[] }) {
return (
<>
<div className="hidden overflow-x-auto border-t border-slate-200 md:block" tabIndex={0} aria-label="资产下载明细表">
<table className="w-full min-w-[940px] table-fixed text-left text-sm">
<caption className="sr-only">按下载次数从高到低排列的资产明细</caption>
<thead className="bg-slate-50 text-xs font-bold text-slate-500">
<tr>
<th scope="col" className="w-[20%] px-5 py-3">资产ID</th>
<th scope="col" className="w-[25%] px-4 py-3">SPU</th>
<th scope="col" className="w-[15%] px-4 py-3">上传人</th>
<th scope="col" className="w-[17%] px-4 py-3">分类信息</th>
<th scope="col" className="w-[11%] px-4 py-3">上传日期</th>
<th scope="col" className="w-[12%] px-4 py-3 text-right">下载次数</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-200">
{materials.map((material) => (
<tr key={material.id} className="align-top hover:bg-slate-50">
<td className="px-5 py-4"><p className="break-all font-mono text-xs leading-4 text-slate-600" title={material.id}>{material.id}</p></td>
<td className="px-4 py-4"><p className="line-clamp-2 font-bold text-slate-950">{material.title}</p><p className="mt-1 text-xs text-slate-500">{material.materialType}</p></td>
<td className="px-4 py-4 font-semibold text-slate-700">{material.authorName}</td>
<td className="px-4 py-4 text-xs leading-5 text-slate-600">{materialMeta(material) || '—'}</td>
<td className="px-4 py-4 tabular-nums text-slate-600">{formatDate(material.createdAt)}</td>
<td className="px-4 py-4 text-right"><span className="inline-flex items-center gap-1.5 font-bold tabular-nums text-[#1677ff]"><ArrowDownToLine className="h-4 w-4" aria-hidden="true" />{material.downloadCount}</span></td>
</tr>
))}
</tbody>
</table>
</div>
<ul className="divide-y divide-slate-200 md:hidden" aria-label="资产下载明细列表">
{materials.map((material) => (
<li key={material.id} className="p-4">
<div className="flex items-start justify-between gap-3"><div className="min-w-0"><p className="text-xs font-bold text-slate-500">SPU</p><h3 className="mt-1 break-words font-bold text-slate-950">{material.title}</h3><p className="mt-1 text-xs text-slate-500">{material.materialType}</p></div><span className="inline-flex shrink-0 items-center gap-1 text-sm font-bold tabular-nums text-[#1677ff]"><ArrowDownToLine className="h-4 w-4" aria-hidden="true" />{material.downloadCount}</span></div>
<dl className="mt-3 grid grid-cols-2 gap-x-3 gap-y-3 text-sm"><div className="col-span-2"><dt className="text-xs text-slate-500">资产ID</dt><dd className="mt-1 break-all font-mono text-xs leading-4 text-slate-700">{material.id}</dd></div><div><dt className="text-xs text-slate-500">上传人</dt><dd className="mt-1 font-semibold text-slate-800">{material.authorName}</dd></div><div><dt className="text-xs text-slate-500">上传日期</dt><dd className="mt-1 tabular-nums text-slate-700">{formatDate(material.createdAt)}</dd></div><div className="col-span-2"><dt className="text-xs text-slate-500">分类信息</dt><dd className="mt-1 text-slate-700">{materialMeta(material) || '—'}</dd></div></dl>
</li>
))}
</ul>
</>
)
}
export default function ValueMetricsDashboard() {
const [selectedType, setSelectedType] = useState('')
const [state, setState] = useState<ViewState>({ data: null, loading: true, error: null })
const load = useCallback(async (type = '', offset = 0, append = false) => {
setState((current) => ({ ...current, loading: true, error: null }))
try {
const params = new URLSearchParams({ limit: String(DETAIL_PAGE_SIZE), offset: String(offset) })
if (type) params.set('materialType', type)
const query = `?${params.toString()}`
const response = await fetch(`/api/department-dashboard/assets/value-metrics${query}`, { cache: 'no-store' })
const payload = await response.json().catch(() => null)
if (!response.ok || !payload?.success || !payload.data) throw new Error(payload?.error || '价值指标读取失败')
setState((current) => ({
data: append && current.data && current.data.selectedType === payload.data.selectedType
? { ...payload.data, materials: [...current.data.materials, ...payload.data.materials] }
: payload.data,
loading: false,
error: null,
}))
setSelectedType(payload.data.selectedType || '')
} catch (error) {
setState((current) => ({ ...current, loading: false, error: (error as Error).message || '价值指标读取失败' }))
}
}, [])
useEffect(() => { void load() }, [load])
const selectedSummary = useMemo(() => {
if (!state.data) return null
return state.data.types.find((type) => type.key === (selectedType || state.data?.selectedType)) || state.data.selectedTypeSummary
}, [selectedType, state.data])
return (
<DepartmentShell>
<main className="mx-auto max-w-[1600px] px-4 pb-16 pt-7 sm:px-6 lg:px-8">
<header className="flex flex-col gap-4 border-b border-[#dfe4ea] pb-6 lg:flex-row lg:items-end lg:justify-between">
<div>
<h1 className="text-3xl font-bold tracking-[-0.03em] text-[#101828] sm:text-4xl">价值指标</h1>
<p className="mt-3 max-w-3xl text-base leading-7 text-[#66758b]">从素材资产库读取各资产类型的复用情况,并按下载次数查看资产明细。</p>
</div>
<p className="inline-flex items-center gap-2 self-start text-xs font-semibold text-emerald-700 lg:self-auto"><span className="h-2 w-2 rounded-full bg-emerald-500" aria-hidden="true" />实时读取素材资产库</p>
</header>
{state.error && <div role="alert" className="mt-6 flex items-center justify-between gap-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-800"><span>{state.error}</span><button type="button" onClick={() => void load(selectedType)} className="inline-flex min-h-9 items-center gap-2 rounded-lg bg-white px-3 text-xs font-bold text-red-800 ring-1 ring-inset ring-red-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-red-500"><RefreshCw className="h-3.5 w-3.5" aria-hidden="true" />重试</button></div>}
<div className="mt-6 overflow-hidden rounded-lg border border-slate-200 bg-white lg:grid lg:grid-cols-[232px_minmax(0,1fr)]">
<aside aria-label="资产类型导航" className="border-b border-slate-200 bg-slate-50 lg:border-b-0 lg:border-r">
<div className="border-b border-slate-200 px-4 py-4"><p className="text-xs font-bold text-slate-500">素材资产库</p><p className="mt-1 text-sm font-bold text-slate-900">资产类型</p></div>
<nav className="flex gap-1 overflow-x-auto p-2 lg:block lg:space-y-1 lg:overflow-visible" aria-label="选择资产类型">
{state.data?.types.map((type) => (
<button key={type.key} type="button" aria-current={selectedType === type.key ? 'page' : undefined} onClick={() => { setSelectedType(type.key); void load(type.key) }} className={`flex min-h-11 shrink-0 items-center gap-2 rounded-lg px-3 text-left text-sm font-bold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1677ff] lg:w-full ${selectedType === type.key ? 'bg-[#1677ff] text-white' : 'text-slate-600 hover:bg-slate-200/70 hover:text-slate-950'}`}><span className="min-w-0 flex-1 truncate">{type.label}</span><span className={`tabular-nums text-xs ${selectedType === type.key ? 'text-white/80' : 'text-slate-400'}`}>{type.totalCount}</span></button>
))}
{state.loading && !state.data && <div role="status" className="px-3 py-4 text-xs font-semibold text-slate-500">正在读取资产类型…</div>}
{!state.loading && state.data?.types.length === 0 && <div className="px-3 py-4 text-xs font-semibold leading-5 text-slate-500">当前权限范围内暂无素材数据</div>}
</nav>
</aside>
<section className="min-w-0 bg-[#f8fafc]" aria-labelledby="value-metrics-detail-title">
{state.loading && !state.data ? <div role="status" className="px-5 py-16 text-center"><RefreshCw className="mx-auto h-7 w-7 animate-spin text-[#1677ff]" aria-hidden="true" /><p className="mt-4 text-sm font-semibold text-slate-700">正在读取素材资产库</p></div> : !selectedSummary ? <div className="px-5 py-16 text-center"><Database className="mx-auto h-7 w-7 text-slate-400" aria-hidden="true" /><p className="mt-4 text-sm font-semibold text-slate-700">暂无可展示的资产类型</p></div> : (
<>
<header className="flex flex-col gap-3 border-b border-slate-200 bg-white px-5 py-5 sm:px-7 lg:flex-row lg:items-center lg:justify-between"><div className="flex min-w-0 items-center gap-3"><span className="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-[#e8f7f2] text-[#087052]"><BarChart3 className="h-5 w-5" aria-hidden="true" /></span><div className="min-w-0"><h2 id="value-metrics-detail-title" className="truncate text-xl font-bold tracking-[-0.02em] text-slate-950">{selectedSummary.label}</h2><p className="mt-1 text-xs font-semibold text-slate-500">资产复用率 = 下载过的资产数 ÷ 该类型资产总数</p></div></div><span className="inline-flex min-h-8 items-center self-start rounded-lg bg-[#e8f7f2] px-3 text-xs font-bold text-[#087052] lg:self-auto">实时读取</span></header>
<dl className="grid gap-px border-b border-slate-200 bg-slate-200 sm:grid-cols-3"><div className="bg-white px-5 py-4 sm:px-6"><dt className="text-xs font-bold text-slate-500">该类型资产总数</dt><dd className="mt-1 text-2xl font-bold tabular-nums text-slate-950">{selectedSummary.totalCount}</dd></div><div className="bg-white px-5 py-4 sm:px-6"><dt className="text-xs font-bold text-slate-500">下载过的资产</dt><dd className="mt-1 text-2xl font-bold tabular-nums text-[#087052]">{selectedSummary.reusedCount}</dd></div><div className="bg-white px-5 py-4 sm:px-6"><dt className="text-xs font-bold text-slate-500">复用率</dt><dd className="mt-1 text-2xl font-bold tabular-nums text-[#1677ff]">{formatRate(selectedSummary.reuseRate)}</dd></div></dl>
<div className="border-b border-slate-200 bg-white px-5 py-4 sm:px-7"><div className="flex flex-col gap-1 sm:flex-row sm:items-end sm:justify-between"><div><h3 className="font-bold text-slate-950">资产下载明细</h3><p className="mt-1 text-xs text-slate-500">按下载次数从高到低排列 · 共 {state.data?.materialsTotal || 0} 项</p></div>{state.loading && <span className="inline-flex items-center gap-2 text-xs font-semibold text-slate-500"><RefreshCw className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />正在更新</span>}</div></div>
{state.data?.materials.length ? <MaterialTable materials={state.data.materials} /> : <div role="status" className="bg-white px-5 py-14 text-center"><Database className="mx-auto h-6 w-6 text-slate-400" aria-hidden="true" /><p className="mt-3 text-sm font-semibold text-slate-700">该类型暂无资产明细</p></div>}
{state.data?.hasMore && <div className="border-t border-slate-200 bg-white px-5 py-4 text-center sm:px-7"><button type="button" disabled={state.loading} onClick={() => void load(selectedType, state.data?.materials.length || 0, true)} className="inline-flex min-h-10 items-center gap-2 rounded-lg border border-slate-300 bg-white px-4 text-sm font-bold text-slate-700 transition-colors hover:bg-slate-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1677ff] disabled:cursor-wait disabled:opacity-60">{state.loading && <RefreshCw className="h-4 w-4 animate-spin" aria-hidden="true" />}加载更多明细</button></div>}
</>
)}
</section>
</div>
</main>
</DepartmentShell>
)
}