BindingEditor.tsx 9.55 KB
import { Database, Play, Plus, 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 { promptText } from "@/lib/dialog";
import { toast } from "@/store/useAppStore";
import { DataTable } from "../ask/AskAnswer";

// 只有对象、关系、聚合函数需要绑定数据
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(() => setDss([]));
  }, []); // eslint-disable-line react-hooks/exhaustive-deps
  useEffect(() => {
    if (!dsId) return;
    void api.sqlModels(dsId, true).then(setModels).catch(() => setModels([]));
  }, [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 cols = useMemo(() => models.find((m) => tableName(m) === table)?.columns?.map((c: any) => c.physical_column || c.name) || [],
    [models, table]);

  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.map((b) => (
          <Badge key={b.id} tone="bg-ok/10 text-ok">
            <Database className="h-3 w-3" /> 数据源 {b.ds_id}:{b.ref.table || b.ref.base_table || `${b.ref.from_column}→${b.ref.to_column}`}
            {canEdit && <button onClick={() => void remove(b)} title="删除绑定"><Trash2 className="h-3 w-3" /></button>}
          </Badge>
        ))}
      </div>

      {kind !== "join" && (
        <Field label={kind === "table" ? "对应的表" : "基表"}>
          <select className="input" value={table || ""} disabled={!canEdit}
                  onChange={(e) => setRef({ ...ref, [kind === "table" ? "table" : "base_table"]: e.target.value })}>
            <option value="">选择表</option>
            {models.map((m) => <option key={m.id} value={tableName(m)}>{tableName(m)}{m.description ? ` · ${m.description.slice(0, 20)}` : ""}</option>)}
          </select>
        </Field>
      )}

      {kind === "table" && table && (
        <>
          <div className="grid grid-cols-2 gap-3">
            {colSelect("key_column", "主键列", "对象唯一标识")}
            {colSelect("label_column", "显示列", "问句里用它识别对象,如名称")}
          </div>
          <Field label="属性 → 列" hint="只读属性映射到列;可写属性可以不映射,修改记在本系统写回层">
            <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" && table && (
        <>
          <Field label="取数表达式" hint="聚合表达式,如 SUM(amount) 或 SUM(a)/NULLIF(SUM(b),0)。系统会据此确定性生成 SQL,不让模型自由发挥">
            <input className="input font-mono" value={ref.expression || ""} disabled={!canEdit}
                   onChange={(e) => setRef({ ...ref, expression: e.target.value })} />
          </Field>
          <div className="grid grid-cols-2 gap-3">
            {colSelect("time_column", "时间列", "按统计周期过滤用")}
            {colSelect("object_key_column", "对象键列", "按单个对象取值用")}
          </div>
          <Field label="固定过滤条件(每行一条 SQL 条件)">
            <textarea className="input min-h-[48px] font-mono text-label" value={(ref.filters || []).join("\n")} disabled={!canEdit}
                      onChange={(e) => setRef({ ...ref, filters: e.target.value.split("\n").filter((x) => x.trim()) })} />
          </Field>
          <Field label="可拆分维度(维度名 → 列)">
            <div className="space-y-1.5">
              {Object.entries(ref.dimensions || {}).map(([k, v]) => (
                <div key={k} className="flex items-center gap-2">
                  <input className="input h-8 w-32" value={k} disabled />
                  <select className="input h-8" value={v as string} disabled={!canEdit}
                          onChange={(e) => setRef({ ...ref, dimensions: { ...ref.dimensions, [k]: e.target.value } })}>
                    {cols.map((c: string) => <option key={c}>{c}</option>)}
                  </select>
                  {canEdit && <button className="btn btn-ghost btn-sm" onClick={() => {
                    const d = { ...ref.dimensions }; delete d[k]; setRef({ ...ref, dimensions: d });
                  }}><Trash2 className="h-3.5 w-3.5" /></button>}
                </div>
              ))}
              {canEdit && <button className="btn btn-sm" onClick={async () => {
                const name = await promptText("维度名", { desc: "问句里怎么说这个维度,如 区域、品牌" });
                if (name) setRef({ ...ref, dimensions: { ...(ref.dimensions || {}), [name]: cols[0] || "" } });
              }}><Plus className="h-3.5 w-3.5" />加维度</button>}
            </div>
          </Field>
        </>
      )}

      {kind === "join" && (
        <div className="grid grid-cols-2 gap-3">
          <Field label="起点对象的列"><input className="input" value={ref.from_column || ""} disabled={!canEdit}
                                        onChange={(e) => setRef({ ...ref, from_column: e.target.value })} /></Field>
          <Field label="终点对象的列"><input className="input" value={ref.to_column || ""} disabled={!canEdit}
                                        onChange={(e) => setRef({ ...ref, to_column: e.target.value })} /></Field>
        </div>
      )}

      <div className="flex flex-wrap gap-2">
        {canEdit && <button className="btn btn-primary btn-sm" disabled={busy || !dsId} onClick={() => void save()}>
          {busy && <Spinner className="h-3.5 w-3.5" />}保存绑定</button>}
        {concept.kind === "object_type" && (
          <button className="btn btn-sm" onClick={async () => {
            try { const r = await onto.objects(concept.id, "", 20); setTest({ columns: ["主键", "名称"], rows: r.items.map((o) => [o.key, o.label]) }); }
            catch (e) { toast("error", "读取失败(对象要先发布)", errText(e)); }
          }}><Play className="h-3.5 w-3.5" />预览对象实例</button>
        )}
      </div>
      {test && (
        <div className="space-y-2">
          {test.sql && <pre className="rounded bg-ink/5 p-2 font-mono text-caption">{test.sql}</pre>}
          <DataTable columns={test.columns} rows={test.rows} max={20} />
        </div>
      )}
    </div>
  );
}