LogsTab.tsx

3.0 KB v1.0
import { useEffect, useState } from 'react'
import { api } from '../../api'
import type { OperationLog } from '../../types'
import { LOG_ACTION_LABELS } from '../../types'

export function LogsTab() {
  const [list, setList] = useState<OperationLog[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [action, setAction] = useState('')
  const [operator, setOperator] = useState('')
  const [busy, setBusy] = useState(false)

  useEffect(() => {
    setBusy(true)
    const q = new URLSearchParams({ page: String(page), page_size: '30' })
    if (action) q.set('action', action)
    if (operator) q.set('operator', operator)
    api<{ list: OperationLog[]; total: number }>(`/api/admin/logs?${q}`)
      .then(r => { setList(r.list); setTotal(r.total) })
      .catch(() => {})
      .finally(() => setBusy(false))
  }, [page, action, operator])

  function detail(log: OperationLog) {
    if (!log.detail) return '-'
    try { return JSON.stringify(JSON.parse(log.detail)) } catch { return log.detail }
  }

  return (
    <div>
      <div className="panel-head">
        <h3>操作日志</h3>
        <div className="toolbar" style={{ padding: 0, border: 0 }}>
          <input className="search" placeholder="搜索操作人…" value={operator}
            onChange={e => { setOperator(e.target.value); setPage(1) }} />
          <select value={action} onChange={e => { setAction(e.target.value); setPage(1) }}>
            <option value="">全部操作</option>
            {Object.entries(LOG_ACTION_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
          </select>
        </div>
      </div>
      <div className="table-wrap">
        <table className="table">
          <thead><tr>
            <th>时间</th><th>操作人</th><th>操作</th><th>对象</th><th>详情</th><th>IP</th>
          </tr></thead>
          <tbody>
            {busy && <tr><td colSpan={6} className="td-center">加载中…</td></tr>}
            {!busy && list.length === 0 && <tr><td colSpan={6} className="td-center empty">暂无日志</td></tr>}
            {list.map(l => (
              <tr key={l.id}>
                <td className="nowrap">{new Date(l.created_at).toLocaleString('zh-CN')}</td>
                <td>{l.operator_name}</td>
                <td><span className="action-tag">{LOG_ACTION_LABELS[l.action] || l.action}</span></td>
                <td>{l.target_name || '-'}</td>
                <td className="detail-cell" title={detail(l)}>{detail(l)}</td>
                <td className="muted">{l.ip || '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <div className="pagination">
        <span>共 {total} 条</span>
        <button className="btn btn-ghost btn-sm" disabled={page <= 1} onClick={() => setPage(p => p - 1)}>上一页</button>
        <span>第 {page} 页</span>
        <button className="btn btn-ghost btn-sm" disabled={page * 30 >= total} onClick={() => setPage(p => p + 1)}>下一页</button>
      </div>
    </div>
  )
}