ObjectTable.tsx 7.12 KB
/** 一类对象的表格视图:属性成列,可以按属性筛选、点表头排序、翻页。点一行打开这个对象。 */
import { ArrowDown, ArrowUp, Plus, X } from "lucide-react";
import { useEffect, useState } from "react";
import { Card, Empty, Spinner } from "@/components/ui";
import { errText, onto, type ObjectRec } from "@/lib/onto";
import { cn } from "@/lib/utils";

const OPS: Record<string, string> = { eq: "等于", ne: "不等于", gt: "大于", ge: "大于等于", lt: "小于", le: "小于等于",
  contains: "包含", empty: "为空", not_empty: "不为空" };
const PAGE = 30;

interface Filter { property: string; op: string; value: string }

export function ObjectTable({ type, props, q, onOpen }: {
  type: string;
  props: { name: string; display_name?: string; data_type?: string; enum_values?: string[] }[];
  /** 左边搜索框里的名称关键词 */
  q: string; onOpen: (key: string) => void;
}) {
  const [filters, setFilters] = useState<Filter[]>([]);
  const [sort, setSort] = useState<{ property: string; dir: "asc" | "desc" } | null>(null);
  const [page, setPage] = useState(0);
  const [data, setData] = useState<{ items: ObjectRec[]; total: number } | null>(null);
  const [err, setErr] = useState("");
  const cols = props.slice(0, 7);
  // 表头只要叫法:显示名里常带说明(「状态:待审批/已下单/…」),冒号后面的放到悬浮提示里
  const head = (p: { name: string; display_name?: string }) => (p.display_name || p.name).split(/[::((]/)[0].trim() || p.name;

  useEffect(() => { setFilters([]); setSort(null); setPage(0); }, [type]);
  useEffect(() => { setPage(0); }, [q, JSON.stringify(filters), JSON.stringify(sort)]); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    let alive = true;
    setErr("");
    const h = window.setTimeout(() => {
      const fs = filters.filter((f) => f.property && (f.value !== "" || f.op === "empty" || f.op === "not_empty"))
        .map((f) => {
          const p = props.find((x) => x.name === f.property);
          const num = p && ["number", "integer", "float", "decimal"].includes(p.data_type || "") && f.value !== "" && !Number.isNaN(Number(f.value));
          return { property: f.property, op: f.op, value: num ? Number(f.value) : f.value };
        });
      void onto.queryObjects(type, { filters: fs, sort: sort ? [sort] : [], q, limit: PAGE, offset: page * PAGE })
        .then((r) => { if (alive) setData({ items: r.items, total: r.total }); })
        .catch((e) => { if (alive) { setErr(errText(e)); setData({ items: [], total: 0 }); } });
    }, 250);
    return () => { alive = false; window.clearTimeout(h); };
  }, [type, q, page, JSON.stringify(filters), JSON.stringify(sort)]); // eslint-disable-line react-hooks/exhaustive-deps

  const set = (i: number, p: Partial<Filter>) => setFilters((fs) => fs.map((f, j) => (j === i ? { ...f, ...p } : f)));
  const pages = data ? Math.max(1, Math.ceil(data.total / PAGE)) : 1;
  return (
    <Card className="flex max-h-[calc(100vh-140px)] flex-col">
      <div className="flex flex-wrap items-center gap-1.5 border-b border-line p-2">
        {filters.map((f, i) => (
          <span key={i} className="flex items-center gap-1 rounded-md border border-line p-1">
            <select className="input h-7 w-28 text-label" value={f.property} onChange={(e) => set(i, { property: e.target.value })}>
              <option value="">选属性</option>
              {props.map((p) => <option key={p.name} value={p.name}>{head(p)}</option>)}
            </select>
            <select className="input h-7 w-24 text-label" value={f.op} onChange={(e) => set(i, { op: e.target.value })}>
              {Object.entries(OPS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
            </select>
            {!["empty", "not_empty"].includes(f.op) && (
              <input className="input h-7 w-28 text-label" placeholder="值" value={f.value} onChange={(e) => set(i, { value: e.target.value })} />
            )}
            <button className="text-muted hover:text-bad" title="去掉这个条件" onClick={() => setFilters((fs) => fs.filter((_, j) => j !== i))}><X className="h-3.5 w-3.5" /></button>
          </span>
        ))}
        <button className="btn btn-sm" onClick={() => setFilters((fs) => [...fs, { property: "", op: "eq", value: "" }])}>
          <Plus className="h-3.5 w-3.5" />加筛选条件
        </button>
        <span className="flex-1" />
        {data && <span className="text-caption text-muted">共 {data.total.toLocaleString("zh-CN")} 个</span>}
      </div>
      {err && <p className="p-3 text-label text-bad">{err}</p>}
      <div className="min-h-0 flex-1 overflow-auto">
        {!data ? <div className="p-4"><Spinner /></div> : data.items.length === 0 ? (
          <Empty title="没有符合条件的对象" desc={filters.length || q ? "放宽筛选条件试试。" : "这个类型下还没有数据。"} />
        ) : (
          <table className="w-full text-label">
            <thead className="sticky top-0 bg-surface text-left">
              <tr className="border-b border-line">
                <th className="whitespace-nowrap px-3 py-2 font-medium text-muted">名称</th>
                {cols.map((p) => (
                  <th key={p.name} className="whitespace-nowrap px-3 py-2 font-medium text-muted">
                    <button className="inline-flex items-center gap-1 whitespace-nowrap hover:text-brand" title={`${p.display_name || p.name} · 点击排序`}
                            onClick={() => setSort((s) => (s?.property === p.name ? (s.dir === "asc" ? { property: p.name, dir: "desc" } : null) : { property: p.name, dir: "asc" }))}>
                      {head(p)}
                      {sort?.property === p.name && (sort.dir === "asc" ? <ArrowUp className="h-3 w-3" /> : <ArrowDown className="h-3 w-3" />)}
                    </button>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {data.items.map((o) => (
                <tr key={o.key} className="cursor-pointer border-b border-line/60 hover:bg-ink/[0.03]" onClick={() => onOpen(o.key)}>
                  <td className="whitespace-nowrap px-3 py-1.5 font-medium">{o.label}</td>
                  {cols.map((p) => {
                    const v = (o.properties || {})[p.name];
                    return <td key={p.name} className={cn("max-w-[16rem] truncate whitespace-nowrap px-3 py-1.5", typeof v === "number" && "tabular-nums")} title={v === null || v === undefined ? "" : String(v)}>{v === null || v === undefined ? "" : String(v)}</td>;
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
      {data && data.total > PAGE && (
        <div className="flex items-center justify-end gap-2 border-t border-line p-2 text-label">
          <button className="btn btn-sm" disabled={page === 0} onClick={() => setPage((p) => p - 1)}>上一页</button>
          <span className="text-muted">第 {page + 1} / {pages} 页</span>
          <button className="btn btn-sm" disabled={page + 1 >= pages} onClick={() => setPage((p) => p + 1)}>下一页</button>
        </div>
      )}
    </Card>
  );
}