ModelingPanel.tsx 30 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
import {
  GitBranch, Layers, Link2, Loader2, Network, RefreshCw, Search, Sparkles, Table2, Trash2, Wand2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api } from "@/lib/api";
import { go, useHashParams } from "@/lib/nav";
import { onto } from "@/lib/onto";
import { FromTableModal } from "../ontology/BindTools";
import { RelationGraph } from "./RelationGraph";
import { cn } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import { Badge, Card, CardHeader, Empty, ErrorNote, Field, Progress, Segmented, Spinner } from "@/components/ui";
import type { DataSource, JobItem, SmColumn, SmModel, SmRelation, SqlRelationRec } from "@/lib/types";

type Sub = "tables" | "relations";
const TYPE_LABEL: Record<string, string> = { mysql: "MySQL", postgres: "PostgreSQL", sqlite: "本地文件" };

/**
 * 表与字段。头部切数据源;「表与字段」页签左边选表、右边看字段并补业务说明;
 * 「表间关联」页签是内嵌的关系图 + 关联列表(推荐 / 新增 / 删除)。
 * 接入范围在数据源里勾选,读进来的表全部参与问数,这里不再逐张启用。
 */
export function ModelingPanel({ dsId, dsName = "", canEdit = false, sources, onSwitchSource, onSourcesChanged, onOpenSources }: {
  dsId: number; dsName?: string; canEdit?: boolean;
  sources: DataSource[];
  onSwitchSource: (id: number) => void;
  /** 读完表结构后让上层刷新数据源列表(表数会变) */
  onSourcesChanged: () => void;
  onOpenSources: () => void;
}) {
  const params = useHashParams();
  const [sub, setSubState] = useState<Sub>(params.get("sub") === "relations" ? "relations" : "tables");
  const setSub = (v: Sub) => {
    setSubState(v);
    const q = new URLSearchParams(window.location.hash.split("?")[1] || "");
    q.set("sub", v);
    history.replaceState(null, "", `#/data?${q.toString()}`);
  };
  const [map, setMap] = useState<Record<string, { concept_id: string; name: string }[]>>({});
  const [toObject, setToObject] = useState("");
  const [models, setModels] = useState<SmModel[] | null>(null);
  const [relations, setRelations] = useState<SmRelation[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [keyword, setKeyword] = useState("");
  const [activeId, setActiveId] = useState<number | null>(null);
  const [focusId, setFocusId] = useState<number | null>(null);
  const [job, setJob] = useState<JobItem | null>(null);
  const jobKind = useRef<"describe" | "introspect">("describe");

  const curDs = useRef(dsId);
  curDs.current = dsId;
  const load = useCallback(() => {
    // 快速连切数据源时,慢回来的旧响应不能盖掉新数据源的内容
    const stale = () => curDs.current !== dsId;
    Promise.all([api.sqlModels(dsId), api.sqlRelations(dsId)])
      .then(([m, r]) => { if (stale()) return; setModels(m); setRelations(r); setError(null); })
      .catch((e) => { if (!stale()) setError(e instanceof Error ? e.message : String(e)); });
    void onto.mappings(dsId).then((x) => { if (!stale()) setMap(x); }).catch(() => setMap({}));
  }, [dsId]);

  useEffect(load, [load]);

  // 切了数据源:上一个库的选中表、筛选、聚焦、进行中的任务都不作数
  useEffect(() => {
    setModels(null); setRelations([]); setActiveId(null); setFocusId(null);
    setKeyword(""); setJob(null); setError(null);
  }, [dsId]);

  // 起草 / 读表结构都是后台任务,轮询进度。跑完刷新一次表格,让新内容立刻可见。
  useEffect(() => {
    if (!job || job.status === "done" || job.status === "failed") return;
    const t = window.setTimeout(async () => {
      try {
        const j = await api.job(job.id);
        setJob(j);
        if (j.status === "done" || j.status === "failed") {
          const intro = jobKind.current === "introspect";
          const label = intro ? "读取表结构" : "起草";
          toast(j.status === "done" ? "ok" : "error",
                j.status === "done" ? `${label}完成` : `${label}失败`, j.message);
          load();
          if (intro) onSourcesChanged();
        }
      } catch { /* 下一轮再试 */ }
    }, 1500);
    return () => window.clearTimeout(t);
  }, [job, load, onSourcesChanged]);

  const draft = async () => {
    try {
      const { job_id } = await api.describeSchema(dsId);
      jobKind.current = "describe";
      setJob(await api.job(job_id));
      toast("ok", "已开始补说明", "给表和字段补业务说明与别名");
    } catch (e) {
      toast("error", "启动失败", e instanceof Error ? e.message : String(e));
    }
  };

  const readSchema = async () => {
    try {
      const { job_id } = await api.introspect(dsId);
      jobKind.current = "introspect";
      setJob(await api.job(job_id));
      toast("ok", "正在读取表结构", "表多的话要等几分钟");
    } catch (e) {
      toast("error", "读取表结构失败", e instanceof Error ? e.message : String(e));
    }
  };

  // 一步把这个数据源的表都起草成对象和关系:建一次只含这个数据库的 AI 建模,草案在建模页里逐条采纳
  const [proposing, setProposing] = useState(false);
  const toOntology = async () => {
    setProposing(true);
    try {
      const fd = new FormData();
      fd.append("title", `数据库:${dsName || `#${dsId}`}`);
      fd.append("doc_ids", "[]");
      fd.append("ds_ids", JSON.stringify([dsId]));
      const r = await onto.createModelingRun(fd);
      toast("info", "已开始 AI 建模", "表和关联会变成对象与关系草案");
      go("modeling", { run: r.id });
    } catch (e) {
      toast("error", "生成失败", e instanceof Error ? e.message : String(e));
    } finally { setProposing(false); }
  };

  // 每张表参与了几条关联
  const relCount = useMemo(() => {
    const n = new Map<number, number>();
    relations.forEach((r) => {
      n.set(r.from_model_id, (n.get(r.from_model_id) ?? 0) + 1);
      if (r.to_model_id !== r.from_model_id) n.set(r.to_model_id, (n.get(r.to_model_id) ?? 0) + 1);
    });
    return n;
  }, [relations]);

  const shown = useMemo(() => {
    const kw = keyword.trim().toLowerCase();
    return (models ?? []).filter((m) => {
      return !kw
        || m.physical_table.toLowerCase().includes(kw)
        || m.description.toLowerCase().includes(kw)
        || m.columns.some((c) => c.name.toLowerCase().includes(kw) || c.description.toLowerCase().includes(kw));
    });
  }, [models, keyword]);

  // 选中的表被筛掉了就顺势跳到第一条,右栏不要留一片空白
  useEffect(() => {
    if (shown.length === 0) { if (activeId !== null) setActiveId(null); return; }     // 筛空了就别留着上一张表
    if (activeId === null || !shown.some((m) => m.id === activeId)) setActiveId(shown[0].id);
  }, [shown, activeId]);

  const active = shown.find((m) => m.id === activeId) ?? null;
  const busy = !!job && job.status !== "done" && job.status !== "failed";
  const reading = busy && jobKind.current === "introspect";

  const patchModel = (modelId: number, patch: Partial<SmModel>) =>
    setModels((s) => s?.map((x) => (x.id === modelId ? { ...x, ...patch } : x)) ?? null);
  const onColumnSaved = (modelId: number, col: SmColumn) =>
    setModels((s) => s?.map((x) => x.id === modelId
      ? { ...x, columns: x.columns.map((c) => (c.id === col.id ? col : c)) }
      : x) ?? null);

  // 头部:数据源切换 + 二级页签。任何状态下都在,空库、出错时也能切到别的库
  const switcher = (
    <div className="flex flex-wrap items-center gap-2">
      <label className="flex items-center gap-1.5 text-label text-muted">
        数据源
        <select className="input w-auto max-w-[320px] py-1 font-medium text-ink" value={dsId}
                onChange={(e) => onSwitchSource(Number(e.target.value))}>
          {sources.map((s) => (
            <option key={s.id} value={s.id}>
              {s.name}({TYPE_LABEL[s.ds_type] || s.ds_type || "API"} · {s.table_count ?? 0} 张表)
            </option>
          ))}
        </select>
      </label>
      <Segmented<Sub> value={sub} onChange={setSub}
                      options={[
                        { key: "tables", label: "表与字段" },
                        { key: "relations", label: "表间关联",
                          badge: relations.length > 0 ? <span className="text-caption tabular-nums text-muted">{relations.length}</span> : undefined },
                      ]} />
      <button className="btn btn-ghost btn-sm ml-auto" onClick={onOpenSources} title="回到数据源列表(测试连接、选表、编辑)">
        管理数据源
      </button>
    </div>
  );

  if (error) return <div className="space-y-3">{switcher}<ErrorNote onRetry={load}>{error}</ErrorNote></div>;
  if (!models) return <div className="space-y-3">{switcher}<Card className="p-4"><Spinner /></Card></div>;

  if (models.length === 0) {
    return (
      <div className="space-y-3">
        {switcher}
        <Card>
          <Empty icon={<Table2 className="h-6 w-6" />} title={`「${dsName}」还没有读取表结构`}
                 desc="读取一次表结构后,这里会列出它的表、字段和表间关联"
                 action={
                   <div className="flex flex-col items-center gap-2">
                     {reading && job ? (
                       <div className="w-64">
                         <Progress value={job.progress} />
                         <p className="mt-1 text-label text-muted">{job.message || "读取中…"}</p>
                       </div>
                     ) : (
                       <button className="btn btn-primary btn-sm" disabled={busy} onClick={() => void readSchema()}>
                         <RefreshCw className="h-3.5 w-3.5" /> 读取表结构
                       </button>
                     )}
                     <button className="btn btn-ghost btn-sm" onClick={onOpenSources}>去数据源调整接入的表</button>
                   </div>
                 } />
        </Card>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {switcher}
      {toObject && <FromTableModal dsId={dsId} table={toObject} onClose={() => setToObject("")} onDone={load} />}

      {sub === "relations" ? (
        <>
          <RelationGraph dsId={dsId} models={models} relations={relations} onChanged={load}
                         focusId={focusId} onFocus={setFocusId}
                         onOpenTable={(id) => { setActiveId(id); setKeyword(""); setSub("tables"); }} />
          <RelationCard dsId={dsId} models={models} relations={relations} onChanged={load} />
        </>
      ) : (
      <Card className="overflow-hidden">
        <div className="flex flex-wrap items-center gap-2 border-b border-line px-4 py-2.5">
          <span className="text-label text-muted">{models.length} 张表 · {relations.length} 条关联</span>
          <div className="relative ml-2 min-w-[180px] flex-1">
            <Search className="pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
            <input className="input py-1.5 pl-8" placeholder="搜表名、字段或说明"
                   value={keyword} onChange={(e) => setKeyword(e.target.value)} />
          </div>
          {canEdit && (
            <button className="btn btn-sm" disabled={busy} onClick={draft} title="自动给表和字段补业务说明与别名">
              {busy && !reading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Wand2 className="h-3.5 w-3.5" />}
              AI 补说明
            </button>
          )}
          {canEdit && (
            <button className="btn btn-primary btn-sm" disabled={proposing} onClick={() => void toOntology()}>
              {proposing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Layers className="h-3.5 w-3.5" />}
              生成对象和关系
            </button>
          )}
        </div>

        {busy && job && (
          <div className="border-b border-line px-4 py-2">
            <Progress value={job.progress} />
            <p className="mt-1 text-label text-muted">{job.message || (reading ? "读取中…" : "起草中…")}</p>
          </div>
        )}

        {/* 左栏选表、右栏看结构。两边各自滚动 */}
        <div className="grid h-[min(66vh,660px)] grid-cols-1 md:grid-cols-[minmax(0,360px)_minmax(0,1fr)]">
          <div className="flex min-h-0 flex-col border-b border-line md:border-b-0 md:border-r">
            <div className="grid grid-cols-[minmax(0,1fr)_2rem_2rem_6rem] items-center gap-2 border-b border-line px-3 py-1 text-caption text-muted">
              <span>表</span><span className="text-right" title="字段数">列</span>
              <span className="text-right" title="参与的表间关联数">关联</span><span>对象</span>
            </div>
            <div className="min-h-0 flex-1 overflow-auto">
              {shown.length === 0 ? (
                <p className="px-4 py-6 text-center text-body text-muted">没有匹配的表</p>
              ) : shown.map((m) => {
                const obj = (map[m.physical_table] || [])[0];
                return (
                  <div key={m.id} onClick={() => setActiveId(m.id)} title={m.description || m.physical_table}
                       className={cn("grid h-10 cursor-pointer grid-cols-[minmax(0,1fr)_2rem_2rem_6rem] items-center gap-2 border-b border-line px-3",
                         activeId === m.id ? "bg-brand/[0.06]" : "hover:bg-ink/[0.02]")}>
                    <span className="flex min-w-0 items-center gap-1.5">
                      <span className="truncate font-mono text-label">{m.physical_table}</span>
                      {m.kind === "view" && <Badge>视图</Badge>}
                    </span>
                    <span className="text-right text-caption tabular-nums text-muted">{m.columns.length}</span>
                    <span className="text-right text-caption tabular-nums text-muted">{relCount.get(m.id) || "—"}</span>
                    {obj ? (
                      <button className="chip w-full justify-center truncate text-caption text-ok" title={`已建成对象「${obj.name}」,点击查看`}
                              onClick={(e) => { e.stopPropagation(); go("b_object", { id: obj.concept_id }); }}>
                        <Link2 className="h-3 w-3 shrink-0" /><span className="truncate">{obj.name}</span>
                      </button>
                    ) : canEdit ? (
                      <button className="btn btn-ghost btn-sm w-full justify-center text-brand" title="把这张表建成一个对象(字段成属性)"
                              onClick={(e) => { e.stopPropagation(); setToObject(m.physical_table); }}>建成对象</button>
                    ) : <span />}
                  </div>
                );
              })}
            </div>
          </div>

          <div className="min-h-0 overflow-auto">
            {active ? (
              <ModelDetail model={active} models={models} relations={relations}
                           onModelSaved={(p) => patchModel(active.id, p)}
                           onColumnSaved={(c) => onColumnSaved(active.id, c)}
                           onOpenRelations={() => { setFocusId(active.id); setSub("relations"); }} />
            ) : (
              <Empty icon={<Layers className="h-6 w-6" />} title="从左边选一张表" />
            )}
          </div>
        </div>
      </Card>
      )}
    </div>
  );
}

function ModelDetail({ model, models, relations, onModelSaved, onColumnSaved, onOpenRelations }: {
  model: SmModel; models: SmModel[]; relations: SmRelation[];
  onModelSaved: (p: Partial<SmModel>) => void; onColumnSaved: (c: SmColumn) => void;
  onOpenRelations: () => void;
}) {
  const [filter, setFilter] = useState("");
  const [onlyBlank, setOnlyBlank] = useState(false);
  const mine = relations.filter((r) => r.from_model_id === model.id || r.to_model_id === model.id);
  const nameOf = (id: number) => models.find((m) => m.id === id)?.physical_table ?? `#${id}`;
  const filled = model.columns.filter((c) => c.description.trim()).length;
  const [desc, setDesc] = useState(model.description);
  useEffect(() => setDesc(model.description), [model.id, model.description]);
  const empties = model.columns.filter((c) => c.null_ratio >= 0.9999).length;

  const saveDesc = async () => {
    if (desc === model.description) return;
    try { await api.updateSqlModel(model.id, { description: desc }); onModelSaved({ description: desc }); }
    catch (e) { toast("error", "保存失败", e instanceof Error ? e.message : String(e)); setDesc(model.description); }
  };

  const cols = useMemo(() => {
    const kw = filter.trim().toLowerCase();
    return model.columns.filter((c) => (!onlyBlank || !c.description.trim())
      && (!kw || c.name.toLowerCase().includes(kw) || c.description.toLowerCase().includes(kw)));
  }, [model.columns, filter, onlyBlank]);

  return (
    <div>
      <div className="sticky top-0 z-10 space-y-1.5 border-b border-line bg-surface px-4 py-2.5">
        <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
          <span className="font-mono text-body font-medium">{model.physical_table}</span>
          <span className="text-caption text-muted">
            {model.columns.length} 列
            {model.row_count_est > 0 && ` · 约 ${model.row_count_est.toLocaleString()} 行`}
            {model.primary_key && ` · 主键 ${model.primary_key}`}
          </span>
          {empties > 0 && <span className="text-caption text-bad">{empties} 列全空</span>}
          <span className={cn("text-caption", filled === model.columns.length ? "text-ok" : "text-muted")}
                title="已填业务说明的字段数">说明 {filled}/{model.columns.length}</span>
          <span className="flex-1" />
          <label className="flex items-center gap-1 text-caption text-muted" title="只列出还没写业务说明的字段">
            <input type="checkbox" checked={onlyBlank} onChange={(e) => setOnlyBlank(e.target.checked)} />只看未填说明
          </label>
          <div className="relative w-40">
            <Search className="pointer-events-none absolute left-2 top-1/2 h-3 w-3 -translate-y-1/2 text-muted" />
            <input className="input py-1 pl-7 text-label" placeholder="筛选字段"
                   value={filter} onChange={(e) => setFilter(e.target.value)} />
          </div>
        </div>
        <input className="input py-1 text-label" value={desc} placeholder="这张表是做什么的(业务说明)"
               onChange={(e) => setDesc(e.target.value)} onBlur={() => void saveDesc()}
               onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} />
        {model.db_comment && (
          <p className="truncate text-caption text-muted" title={model.db_comment}>
            数据库注释:{model.db_comment}
          </p>
        )}
      </div>

      <table className="w-full table-fixed text-label">
        <thead>
          <tr className="text-left text-muted [&>th]:whitespace-nowrap [&>th]:py-1.5 [&>th]:font-medium">
            <th className="w-[18%] px-4">字段</th>
            <th className="w-[12%] pr-3">类型</th>
            <th className="w-[22%] pr-3" title="数据库里的原始字段注释,自动同步,不可修改">字段描述</th>
            <th className="w-[28%] pr-3">业务说明</th>
            <th className="w-[20%] pr-4">取值样例</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-line">
          {cols.map((c) => (
            <ColumnRow key={c.id} column={c} onSaved={onColumnSaved} />
          ))}
          {cols.length === 0 && (
            <tr><td colSpan={5} className="px-4 py-6 text-center text-muted">
              {onlyBlank && !filter.trim() ? "所有字段都写了说明" : "没有匹配的字段"}
            </td></tr>
          )}
        </tbody>
      </table>

      <div className="border-t border-line px-4 py-3">
        <div className="mb-1.5 flex items-center gap-2">
          <span className="text-label font-medium">这张表的关联</span>
          <span className="text-caption text-muted">{mine.length} 条</span>
          <button className="btn btn-sm ml-auto border-brand/40 text-brand hover:bg-brand/10" onClick={onOpenRelations}>
            <Network className="h-3.5 w-3.5" /> 在关系图中查看
          </button>
        </div>
        {mine.length === 0 ? (
          <p className="text-label text-muted">还没有关联。到「表间关联」里推荐或新增。</p>
        ) : (
          <div className="space-y-1">
            {mine.map((r) => (
              <div key={r.id} className="flex items-center gap-2">
                <code className="min-w-0 flex-1 truncate text-label">
                  {nameOf(r.from_model_id)}.{r.from_column} = {nameOf(r.to_model_id)}.{r.to_column}
                </code>
                <Badge>{r.cardinality}</Badge>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function ColumnRow({ column, onSaved }: { column: SmColumn; onSaved: (c: SmColumn) => void }) {
  const [desc, setDesc] = useState(column.description);
  const [saving, setSaving] = useState(false);
  useEffect(() => setDesc(column.description), [column.description]);

  const save = async () => {
    if (desc === column.description) return;
    setSaving(true);
    try {
      await api.updateSqlColumn(column.id, { description: desc });
      onSaved({ ...column, description: desc });
    } catch (e) {
      toast("error", "保存失败", e instanceof Error ? e.message : String(e));
      setDesc(column.description);
    } finally { setSaving(false); }
  };

  return (
    <tr className={cn("align-middle", !column.enabled && "opacity-50")}>
      <td className="truncate px-4 py-1.5 font-mono" title={column.name}>{column.name}</td>
      <td className="truncate py-1.5 pr-3 text-muted" title={column.data_type}>{column.data_type}</td>
      <td className="py-1.5 pr-3">
        {column.db_comment
          ? <span className="block truncate text-muted" title={`${column.db_comment}(数据库原始注释,只读)`}>{column.db_comment}</span>
          : <span className="text-muted" title="数据库里没有给这个字段写注释">—</span>}
      </td>
      <td className="py-1.5 pr-3">
        <div className="flex items-center gap-1.5">
          <input className="input py-1 text-label" value={desc} placeholder="补一句业务含义"
                 onChange={(e) => setDesc(e.target.value)} onBlur={save}
                 onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); }} />
          {saving && <Loader2 className="h-3 w-3 shrink-0 animate-spin text-muted" />}
        </div>
      </td>
      <td className="py-1.5 pr-4">
        {column.sample_values.length > 0 ? (
          // 一行显示,放不下就省略;完整取值挂在悬浮提示上 —— 换行的标签会把每一行撑得很高
          <span className="block truncate text-muted" title={column.sample_values.map(String).join("、")}>
            {column.sample_values.slice(0, 8).map(String).join("、")}
          </span>
        ) : (
          <span className="text-muted">—</span>
        )}
      </td>
    </tr>
  );
}

function RelationCard({ dsId, models, relations, onChanged }: {
  dsId: number; models: SmModel[]; relations: SmRelation[]; onChanged: () => void;
}) {
  const nameOf = (id: number) =>
    models.find((m) => m.id === id)?.physical_table ?? `#${id}`;
  const [adding, setAdding] = useState(false);
  const [recs, setRecs] = useState<SqlRelationRec[] | null>(null);
  const [scanning, setScanning] = useState(false);
  const [form, setForm] = useState({ from_model_id: 0, from_column: "", to_model_id: 0, to_column: "" });

  const recommend = async () => {
    setScanning(true);
    try {
      const r = await api.recommendRelations(dsId);
      setRecs(r);
      toast(r.length ? "ok" : "warn",
            r.length ? `找到 ${r.length} 条候选关联` : "没有找到可靠的关联路径",
            r.length ? "已按取值重叠率排序,确认后再采纳" : "列名或取值都对不上");
    } catch (e) {
      toast("error", "推荐失败", e instanceof Error ? e.message : String(e));
    } finally { setScanning(false); }
  };

  const accept = async (r: SqlRelationRec) => {
    try {
      await api.upsertSqlRelation(dsId, {
        from_model_id: r.from_model_id, from_column: r.from_column,
        to_model_id: r.to_model_id, to_column: r.to_column,
        join_type: "left", cardinality: r.cardinality,
        description: `按列名与取值推导(重叠率 ${r.overlap},目标唯一度 ${r.target_uniqueness})`,
      });
      setRecs((s) => s?.filter((x) => x !== r) ?? null);
      onChanged();
    } catch (e) {
      toast("error", "采纳失败", e instanceof Error ? e.message : String(e));
    }
  };

  const fromCols = models.find((m) => m.id === form.from_model_id)?.columns ?? [];
  const toCols = models.find((m) => m.id === form.to_model_id)?.columns ?? [];

  const add = async () => {
    try {
      await api.upsertSqlRelation(dsId, { ...form, join_type: "inner", cardinality: "N:1" });
      toast("ok", "已新增关联路径");
      setAdding(false);
      setForm({ from_model_id: 0, from_column: "", to_model_id: 0, to_column: "" });
      onChanged();
    } catch (e) {
      toast("error", "新增失败", e instanceof Error ? e.message : String(e));
    }
  };

  const remove = async (r: SmRelation) => {
    try {
      await api.deleteSqlRelation(r.id);
      onChanged();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
  };

  const ok = form.from_model_id && form.to_model_id && form.from_column && form.to_column;

  return (
    <Card>
      <CardHeader
        title="表间关联"
       
        right={
          <div className="flex items-center gap-1.5">
            <button className="btn btn-sm" disabled={scanning} onClick={recommend}
                    title="这个库没有外键,按列名 + 真实取值重叠率扫一遍候选关联">
              {scanning ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                        : <Sparkles className="h-3.5 w-3.5" />}
              推荐关联
            </button>
            <button className="btn btn-sm" onClick={() => setAdding(!adding)}>
              <GitBranch className="h-3.5 w-3.5" /> {adding ? "取消" : "新增"}
            </button>
          </div>
        } />

      {recs && recs.length > 0 && (
        <div className="border-b border-line bg-brand/[0.03] px-4 py-2.5">
          <p className="mb-1.5 text-label font-medium">
            候选关联(按取值重叠率排序,确认无误再采纳)
          </p>
          <div className="space-y-1">
            {recs.map((r, i) => (
              <div key={i} className="flex flex-wrap items-center gap-2">
                <code className="min-w-0 flex-1 truncate text-label">
                  {r.from_table}.{r.from_column} = {r.to_table}.{r.to_column}
                </code>
                <Badge tone="bg-ok/10 text-ok">重叠 {(r.overlap * 100).toFixed(1)}%</Badge>
                <Badge tone="bg-ink/5 text-muted">目标唯一度 {(r.target_uniqueness * 100).toFixed(0)}%</Badge>
                <button className="btn btn-sm" onClick={() => accept(r)}>采纳</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {adding && (
        <div className="grid grid-cols-2 items-end gap-2 border-b border-line px-4 pb-3
                        sm:grid-cols-[1fr_1fr_auto_1fr_1fr_auto]">
          <Field label="从表">
            <select className="input" value={form.from_model_id}
                    onChange={(e) => setForm({ ...form, from_model_id: Number(e.target.value), from_column: "" })}>
              <option value={0}>选择…</option>
              {models.map((m) => <option key={m.id} value={m.id}>{m.physical_table}</option>)}
            </select>
          </Field>
          <Field label="列">
            <select className="input" value={form.from_column}
                    onChange={(e) => setForm({ ...form, from_column: e.target.value })}>
              <option value="">选择…</option>
              {fromCols.map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
            </select>
          </Field>
          <span className="hidden pb-2 text-muted sm:block">=</span>
          <Field label="到表">
            <select className="input" value={form.to_model_id}
                    onChange={(e) => setForm({ ...form, to_model_id: Number(e.target.value), to_column: "" })}>
              <option value={0}>选择…</option>
              {models.map((m) => <option key={m.id} value={m.id}>{m.physical_table}</option>)}
            </select>
          </Field>
          <Field label="列">
            <select className="input" value={form.to_column}
                    onChange={(e) => setForm({ ...form, to_column: e.target.value })}>
              <option value="">选择…</option>
              {toCols.map((c) => <option key={c.id} value={c.name}>{c.name}</option>)}
            </select>
          </Field>
          <button className="btn btn-primary btn-sm" disabled={!ok} onClick={add}>添加</button>
        </div>
      )}

      {relations.length === 0 ? (
        <p className="px-4 py-5 text-center text-body text-muted">
          还没有表间关联。数据库里有外键的会自动带出来,没有的在这里加。
        </p>
      ) : (
        <div className="divide-y divide-line">
          {relations.map((r) => (
            <div key={r.id} className="flex flex-wrap items-center gap-2 px-4 py-2">
              <code className="min-w-0 flex-1 truncate text-label">
                {nameOf(r.from_model_id)}.{r.from_column} = {nameOf(r.to_model_id)}.{r.to_column}
              </code>
              <Badge>{r.cardinality}</Badge>
              {r.description && (
                <span className="max-w-[40%] truncate text-label text-muted" title={r.description}>
                  {r.description}
                </span>
              )}
              <button className="btn btn-ghost btn-sm text-bad" onClick={() => remove(r)}>
                <Trash2 className="h-3.5 w-3.5" />
              </button>
            </div>
          ))}
        </div>
      )}
    </Card>
  );
}