BindingEditor.tsx 14.1 KB
import { Database, Play, Trash2 } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { Badge, Field, Spinner } from "@/components/ui";
import { api } from "@/lib/api";
import { errText, onto, type Binding, type Concept } from "@/lib/onto";
import type { DataSource, SmModel } from "@/lib/types";
import { toast, loadFailed } from "@/store/useAppStore";
import { ResultGrid, Select } from "@/components/kit";
import { DimensionList, ExprBuilder, FilterList } from "./MetricBuilder";

// 只有对象、关系、聚合函数需要绑定数据
const TARGET: Record<string, string> = { object_type: "table", function: "metric_expr", link_type: "join" };

/**
 * 数据绑定:把概念落到某个数据源的表/列/表达式上。一个概念可以在多个数据源各绑一条。
 * 下拉里的表和列来自数据源内省结果,不用手敲物理名。
 */
export function BindingEditor({ concept, canEdit, onChanged }: { concept: Concept; canEdit: boolean; onChanged: () => void }) {
  const kind = TARGET[concept.kind];
  const [dss, setDss] = useState<DataSource[]>([]);
  const [dsId, setDsId] = useState<number>(concept.bindings[0]?.ds_id || 0);
  const [models, setModels] = useState<SmModel[]>([]);
  const existing = concept.bindings.find((b) => b.ds_id === dsId && b.target_kind === kind);
  const [ref, setRef] = useState<any>(existing?.ref || {});
  const [busy, setBusy] = useState(false);
  const [test, setTest] = useState<any>(null);

  useEffect(() => {
    void api.datasources().then((d) => { setDss(d); if (!dsId && d[0]) setDsId(d[0].id); }).catch((e) => { setDss([]); loadFailed(e); });
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (!dsId) return;
    void api.sqlModels(dsId, true).then(setModels).catch((e) => { setModels([]); loadFailed(e); });
  }, [dsId]);
  useEffect(() => {
    setRef(concept.bindings.find((b) => b.ds_id === dsId && b.target_kind === kind)?.ref || {});
    setTest(null);
  }, [concept.id, dsId]); // eslint-disable-line react-hooks/exhaustive-deps

  const tableName = (m: SmModel) => m.physical_table || m.name;
  const table = kind === "table" ? ref.table : ref.base_table;
  // 指标可以建在「一类对象」上(推荐:能用算出来的属性、每个属性都能当维度),也可以直接建在一张表上
  const onObject = kind === "metric_expr" && (!!ref.base_object || !ref.base_table);
  const [objProps, setObjProps] = useState<{ name: string; label: string }[]>([]);
  useEffect(() => {
    if (kind !== "metric_expr" || !ref.base_object) { setObjProps([]); return; }
    let alive = true;
    void onto.concepts({ kind: "object_type" }).then(async (all) => {
      const hit = all.find((x) => x.id === ref.base_object || x.name === ref.base_object);
      if (!hit) return;
      const c = await onto.concept(hit.id);
      if (alive) setObjProps(((c.spec?.properties || []) as any[]).map((p) => ({ name: p.name, label: p.display_name || p.name })));
    }).catch(() => undefined);
    return () => { alive = false; };
  }, [kind, ref.base_object]);
  const tableCols = useMemo(() => models.find((m) => tableName(m) === table)?.columns?.map((c: any) => c.physical_column || c.name) || [],
    [models, table]);
  const cols: string[] = onObject ? objProps.map((p) => p.name) : tableCols;
  const labels: Record<string, string> = onObject ? Object.fromEntries(objProps.map((p) => [p.name, p.label])) : {};

  // 关系两端的对象各绑在哪张表上:选关联列时直接从那张表的列里挑
  const [objects, setObjects] = useState<{ id: string; name: string }[]>([]);
  const [ends, setEnds] = useState<Record<"from" | "to", { name: string; table: string; key: string; cols: string[] } | null>>({ from: null, to: null });
  useEffect(() => {
    if (kind === "metric_expr") {
      void onto.concepts({ kind: "object_type" }).then((r) => setObjects(r.map((x) => ({ id: x.id, name: x.name })))).catch((e) => { setObjects([]); loadFailed(e); });
    }
  }, [kind]);
  useEffect(() => {
    if (kind !== "join") return;
    let alive = true;
    const one = async (refId: string) => {
      if (!refId) return null;
      try {
        const all = await onto.concepts({ kind: "object_type" });
        const hit = all.find((x) => x.id === refId || x.name === refId);
        if (!hit) return null;
        const c = await onto.concept(hit.id);
        const b = c.bindings.find((x) => x.target_kind === "table");
        const t = b?.ref.table || "";
        const ms = b ? await api.sqlModels(b.ds_id, true) : [];
        const m = ms.find((x) => (x.physical_table || x.name) === t);
        return { name: c.name, table: t, key: b?.ref.key_column || "", cols: (m?.columns || []).map((x: any) => x.physical_column || x.name) };
      } catch { return null; }
    };
    void Promise.all([one(concept.spec?.from_type), one(concept.spec?.to_type)]).then(([f, t]) => { if (alive) setEnds({ from: f, to: t }); });
    return () => { alive = false; };
  }, [kind, concept.spec?.from_type, concept.spec?.to_type]);

  if (!kind) return null;
  const save = async () => {
    setBusy(true);
    try {
      await onto.setBinding(concept.id, { ds_id: dsId, target_kind: kind, ref });
      toast("ok", "已保存", "发布后才会生效");
      onChanged();
    } catch (e) { toast("error", "保存失败", errText(e)); } finally { setBusy(false); }
  };
  const remove = async (b: Binding) => {
    await onto.deleteBinding(b.id);
    onChanged();
  };
  const colSelect = (key: string, label: string, hint?: string) => (
    <Field label={label} hint={hint}>
      <Select className="input" value={ref[key] || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, [key]: e.target.value })}>
        <option value="">不设置</option>
        {cols.map((c: string) => <option key={c}>{c}</option>)}
      </Select>
    </Field>
  );
  const props: string[] = (concept.spec?.properties || []).map((p: any) => p.name);

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-end gap-3">
        <Field label="数据源" className="w-56">
          <Select className="input" value={dsId} onChange={(e) => setDsId(Number(e.target.value))}>
            {!dss.length && <option value={0}>还没有接入数据源</option>}
            {dss.map((d) => <option key={d.id} value={d.id}>{d.name}</option>)}
          </Select>
        </Field>
        {concept.bindings.filter((b) => b.ds_id !== dsId).map((b) => (
          <Badge key={b.id} variant="ok">
            <Database className="h-3 w-3" />{dss.find((d) => d.id === b.ds_id)?.name || "另一个数据源"}里也接了
            {canEdit && <button onClick={() => void remove(b)} title="去掉"><Trash2 className="h-3 w-3" /></button>}
          </Badge>
        ))}
      </div>

      {kind === "metric_expr" && (
        <Field label="统计什么">
          <div className="flex flex-wrap items-center gap-2">
            <Select className="input w-40" value={onObject ? "object" : "table"} disabled={!canEdit}
                    onChange={(e) => setRef(e.target.value === "object" ? { ...ref, base_table: "", base_object: ref.base_object || concept.spec?.object_type || "" }
                      : { ...ref, base_object: "", base_table: ref.base_table || tableName(models[0] || ({} as SmModel)) || "" })}>
              <option value="object">一类对象</option><option value="table">一张数据表</option>
            </Select>
            {onObject ? (
              <Select className="input w-56" value={objects.find((o) => o.id === ref.base_object || o.name === ref.base_object)?.id || ""} disabled={!canEdit}
                      onChange={(e) => setRef({ ...ref, base_object: e.target.value })}>
                <option value="">选对象</option>
                {objects.map((o) => <option key={o.id} value={o.id}>{o.name}</option>)}
              </Select>
            ) : (
              <Select className="input w-72" value={table || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, base_table: e.target.value })}>
                <option value="">选表</option>
                {models.map((m) => <option key={m.id} value={tableName(m)}>{m.description ? `${m.description.slice(0, 20)}(${tableName(m)})` : tableName(m)}</option>)}
              </Select>
            )}
          </div>
        </Field>
      )}
      {kind === "table" && (
        <Field label="对应的表">
          <Select className="input" value={table || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, table: e.target.value })}>
            <option value="">选表</option>
            {models.map((m) => <option key={m.id} value={tableName(m)}>{m.description ? `${m.description.slice(0, 24)}(${tableName(m)})` : tableName(m)}</option>)}
          </Select>
        </Field>
      )}

      {kind === "table" && table && (
        <>
          <div className="grid grid-cols-2 gap-3">
            {colSelect("key_column", "主键是哪一列")}
            {colSelect("label_column", "名称是哪一列")}
          </div>
          <Field label="每个属性对应哪一列">
            <div className="grid gap-1.5 sm:grid-cols-2">
              {props.map((p) => (
                <div key={p} className="flex items-center gap-2">
                  <span className="w-24 shrink-0 truncate text-label">{p}</span>
                  <Select className="input h-8" value={ref.columns?.[p] || ""} disabled={!canEdit}
                          onChange={(e) => setRef({ ...ref, columns: { ...(ref.columns || {}), [p]: e.target.value } })}>
                    <option value="">不对应</option>
                    {cols.map((c: string) => <option key={c}>{c}</option>)}
                  </Select>
                </div>
              ))}
              {!props.length && <p className="text-label text-muted">先在「定义」里加属性</p>}
            </div>
          </Field>
        </>
      )}

      {kind === "metric_expr" && (onObject ? !!ref.base_object : !!table) && (
        <>
          <Field label="怎么算">
            <ExprBuilder value={ref.expression || ""} cols={cols} labels={labels} disabled={!canEdit}
                         onChange={(expression) => setRef((r: any) => ({ ...r, expression }))} />
          </Field>
          <Field label="只算哪些" hint="不加就是全部都算">
            <FilterList value={ref.filters || []} cols={cols} labels={labels} disabled={!canEdit}
                        onChange={(filters) => setRef((r: any) => ({ ...r, filters }))} />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            <Field label="按哪个日期统计" hint="问「上周」「本月」时按它算;不随时间变的指标不用选">
              <Select className="input" value={ref.time_column || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, time_column: e.target.value })}>
                <option value="">不设置</option>
                {cols.map((c) => <option key={c} value={c}>{labels[c] || c}</option>)}
              </Select>
            </Field>
          </div>
          {onObject ? <p className="hint">这类对象的每个属性都可以用来拆开看,不用另外设置。</p> : (
            <Field label="可以按什么拆开看">
              <DimensionList dims={ref.dimensions || {}} types={ref.dimension_types || {}} cols={cols} objects={objects} disabled={!canEdit}
                             onChange={(dimensions, dimension_types) => setRef((r: any) => ({ ...r, dimensions, dimension_types }))} />
            </Field>
          )}
        </>
      )}

      {kind === "join" && (
        <div className="grid grid-cols-2 gap-3">
          {(["from", "to"] as const).map((side) => {
            const end = ends[side];
            const key = `${side}_column`;
            return (
              <Field key={side} label={`${end ? `「${end.name}」` : side === "from" ? "起点对象" : "终点对象"}的哪一列`}
                     hint={end?.table ? undefined : "这个对象还没接数据,先去接"}>
                {end?.cols.length ? (
                  <Select className="input" value={ref[key] || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, [key]: e.target.value })}>
                    <option value="">选一列</option>
                    {ref[key] && !end.cols.includes(ref[key]) && <option value={ref[key]}>{ref[key]}</option>}
                    {end.cols.map((x) => <option key={x} value={x}>{x}{x === end.key ? "(主键)" : ""}</option>)}
                  </Select>
                ) : (
                  <input className="input" value={ref[key] || ""} disabled={!canEdit} onChange={(e) => setRef({ ...ref, [key]: e.target.value })} />
                )}
              </Field>
            );
          })}
          <p className="col-span-2 hint">两边这两列的值相等,就算有这条关系。</p>
        </div>
      )}

      <div className="flex flex-wrap gap-2">
        {canEdit && <button className="btn btn-primary" disabled={busy || !dsId} onClick={() => void save()}>
          {busy && <Spinner className="h-3.5 w-3.5" />}保存</button>}
        {kind === "metric_expr" && (
          <button className="btn" disabled={!existing} title={existing ? "" : "先保存"}
                  onClick={async () => {
                    try {
                      const dims = Object.keys(existing?.ref.dimensions || {}).slice(0, 1);
                      const r = await onto.metricQuery({ metric: concept.id, dimensions: dims, limit: 20, draft: true });
                      setTest(dims.length ? r : { columns: [(r as any).value_label || "结果"], rows: r.rows });
                    } catch (e) { toast("error", "算不出来", errText(e)); }
                  }}><Play className="h-3.5 w-3.5" />算一次看看</button>
        )}
        {concept.kind === "object_type" && (
          <button className="btn" onClick={async () => {
            try { setTest(await onto.queryObjects(concept.id, { limit: 10 })); }
            catch (e) { toast("error", "读不到(对象要先发布)", errText(e)); }
          }}><Play className="h-3.5 w-3.5" />看几条数据</button>
        )}
      </div>
      {test && (
        <div className="space-y-2">
          <ResultGrid data={test} max={20} />
        </div>
      )}
    </div>
  );
}