DataSourcePanel.tsx 32.4 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
import {
  AlertTriangle, ArrowRight, CheckCircle2, Database, FileSpreadsheet, FileUp, Globe, ListChecks, Loader2,
  Plug, RefreshCw, Search, ShieldCheck, Trash2,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, ApiError } from "@/lib/api";
import { cn, formatTime } from "@/lib/utils";
import { toast } from "@/store/useAppStore";
import {
  Badge, Card, CardHeader, Confirm, Empty, ErrorNote, Field, Modal, Progress, Spinner,
} from "@/components/ui";
import type { DataSource, JobItem, ProbeResult } from "@/lib/types";

const BLANK = { name: "", ds_type: "mysql", host: "", port: 3306, db_name: "", username: "", password: "", schema: "public", tables: "", writeback: false };

/** 新建连接时可选的类型。键是后端的 ds_type(= SQL 方言);MariaDB 走 MySQL 协议。 */
const KINDS: { key: string; ds_type: string; label: string; desc: string; port: number; group: string; soon?: boolean }[] = [
  { key: "mysql", ds_type: "mysql", label: "MySQL", desc: "5.7 / 8.x", port: 3306, group: "关系型数据库" },
  { key: "mariadb", ds_type: "mysql", label: "MariaDB", desc: "10.x / 11.x", port: 3306, group: "关系型数据库" },
  { key: "postgres", ds_type: "postgres", label: "PostgreSQL", desc: "13 / 14 / 15 / 16", port: 5432, group: "关系型数据库" },
  { key: "api", ds_type: "", label: "REST API", desc: "HTTP GET / POST · JSON 响应", port: 0, group: "API" },
  { key: "file", ds_type: "sqlite", label: "本地文件", desc: "CSV · Excel · JSON", port: 0, group: "文件" },
  { key: "nosql", ds_type: "", label: "MongoDB · Redis · ClickHouse · Elasticsearch", desc: "非关系型数据库", port: 0, group: "即将上线", soon: true },
];
const TYPE_LABEL: Record<string, string> = { mysql: "MySQL", postgres: "PostgreSQL", sqlite: "本地文件" };

export function DataSourcePanel({ selectedId, onSelect, onChanged, onOpenApi, onOpenTables }: {
  selectedId: number | null;
  onSelect: (id: number) => void;
  onChanged: () => void;
  /** 选了 REST API:跳到「外部系统 / API」页签登记端点 */
  onOpenApi?: () => void;
  /** 点数据源 / 「查看表」:带着这个数据源去「表与字段」 */
  onOpenTables: (id: number) => void;
}) {
  const [items, setItems] = useState<DataSource[] | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [cryptoReady, setCryptoReady] = useState(true);
  const [editing, setEditing] = useState<DataSource | null>(null);
  const [creating, setCreating] = useState(false);
  const [pickTables, setPickTables] = useState(false);
  const [picking, setPicking] = useState(false);
  const [fileDs, setFileDs] = useState<DataSource | "new" | null>(null);
  const [confirmDel, setConfirmDel] = useState<DataSource | null>(null);
  const [busy, setBusy] = useState<number | null>(null);
  const [job, setJob] = useState<{ dsId: number; item: JobItem | null } | null>(null);
  const [kw, setKw] = useState("");
  // 第一次读表结构的数据源:读完直接带人去看表,不用再自己找
  const jumpAfter = useRef<number | null>(null);

  const load = useCallback(() => {
    api.datasources().then((d) => { setItems(d); setError(null); })
      .catch((e) => setError(e instanceof Error ? e.message : String(e)));
    api.sqlMeta().then((m) => setCryptoReady(m.crypto_ready)).catch(() => undefined);
  }, []);

  useEffect(load, [load]);

  // 内省是后台任务,轮询它的进度。也可以走 /api/jobs/{id}/events 的 SSE,
  // 但这里只需要一个进度条,轮询代码短得多。
  const jobId = job?.item?.id ?? null;
  const timer = useRef<number>();
  useEffect(() => {
    if (jobId === null) return;
    const tick = async () => {
      try {
        const j = await api.job(jobId);
        setJob((s) => (s ? { ...s, item: j } : s));
        if (j.status === "done" || j.status === "failed") {
          toast(j.status === "done" ? "ok" : "error",
                j.status === "done" ? "表结构读取完成" : "表结构读取失败", j.message);
          const jump = j.status === "done" ? jumpAfter.current : null;
          jumpAfter.current = null;
          setJob(null);
          load();
          onChanged();
          if (jump) onOpenTables(jump);
          return;     // 不再排下一次
        }
      } catch { /* 任务还没落库,下一轮再看 */ }
      timer.current = window.setTimeout(tick, 1200);
    };
    timer.current = window.setTimeout(tick, 800);
    return () => window.clearTimeout(timer.current);
  }, [jobId, load, onChanged, onOpenTables]);

  const test = async (ds: DataSource) => {
    setBusy(ds.id);
    try {
      const info = await api.testDatasource(ds.id);
      toast(info.warning ? "warn" : "ok", `连接成功:${info.database}`,
            info.warning ?? `${info.version},${info.table_count} 张表`);
      load();
    } catch (e) {
      toast("error", "连接失败", e instanceof Error ? e.message : String(e));
      load();
    } finally { setBusy(null); }
  };

  const introspect = async (ds: DataSource, resample = false) => {
    setBusy(ds.id);
    try {
      const { job_id } = await api.introspect(ds.id, resample);
      jumpAfter.current = ds.table_count ? null : ds.id;
      const j = await api.job(job_id);
      setJob({ dsId: ds.id, item: j });
      toast("ok", "正在读取表结构", "表多的话要等几分钟");
    } catch (e) {
      toast("error", "读取表结构失败", e instanceof Error ? e.message : String(e));
    } finally { setBusy(null); }
  };

  const remove = async (ds: DataSource) => {
    try {
      await api.deleteDatasource(ds.id);
      toast("ok", `已删除数据源「${ds.name}」`);
      load();
      onChanged();
    } catch (e) {
      toast("error", "删除失败", e instanceof Error ? e.message : String(e));
    }
    setConfirmDel(null);
  };

  const shownItems = useMemo(() => {
    const k = kw.trim().toLowerCase();
    const rank = (d: DataSource) => (d.status === "error" ? 0 : d.status === "new" ? 1 : 2);
    return (items ?? [])
      .filter((d) => !k || d.name.toLowerCase().includes(k) || d.db_name.toLowerCase().includes(k) || d.host.toLowerCase().includes(k))
      .sort((a, b) => rank(a) - rank(b));       // 异常的、没测过的排前面,一眼看到要处理的
  }, [items, kw]);

  if (error) return <ErrorNote onRetry={load}>{error}</ErrorNote>;
  if (!items) return <Card className="p-4"><Spinner /></Card>;

  const nOk = items.filter((d) => d.status === "ok").length;
  const nBad = items.filter((d) => d.status === "error").length;

  return (
    <div className="space-y-3">
      {!cryptoReady && (
        <div className="card flex items-start gap-2.5 border-warn/40 bg-warn/5 p-3">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-warn" />
          <div className="text-body leading-relaxed">
            <p className="font-medium">未配置 SECRET_KEY,暂时不能添加数据源。</p>
            <p className="mt-0.5 text-muted">
              业务库口令必须加密存储。请在 <code className="rounded bg-ink/[0.07] px-1">.env</code> 里加一行
              <code className="mx-1 rounded bg-ink/[0.07] px-1">SECRET_KEY=(一串足够长的随机字符)</code>
              后重启服务。
            </p>
          </div>
        </div>
      )}

      <Card>
        <CardHeader
          title="数据源"
          desc={items.length > 0 ? (
            <>{items.length} 个 · <span className="text-ok">{nOk} 个已连通</span>
              {nBad > 0 && <> · <span className="text-bad">{nBad} 个异常</span></>}
              <span className="ml-2">点一行进入它的表与字段</span></>
          ) : undefined}
          right={
            <>
              {items.length > 4 && (
                <div className="relative w-44">
                  <Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
                  <input className="input py-1 pl-7 text-label" placeholder="搜名称 / 主机 / 库名"
                         value={kw} onChange={(e) => setKw(e.target.value)} />
                </div>
              )}
              <button className="btn btn-primary btn-sm" onClick={() => setPicking(true)}>
                <Database className="h-3.5 w-3.5" /> 新建连接
              </button>
            </>
          } />

        {items.length === 0 ? (
          <Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
                 desc="接入业务数据库、上传 Excel / CSV,或登记外部 API,系统才有数据可问"
                 action={<button className="btn btn-primary btn-sm" onClick={() => setPicking(true)}>新建连接</button>} />
        ) : shownItems.length === 0 ? (
          <p className="px-4 py-6 text-center text-body text-muted">没有匹配的数据源</p>
        ) : (
          <div className="divide-y divide-line">
            {shownItems.map((ds) => (
              <div key={ds.id}
                   className={cn("px-4 py-3 transition-colors",
                     selectedId === ds.id ? "bg-brand/[0.04]" : "hover:bg-ink/[0.015]")}>
                <div className="flex flex-col gap-2 sm:flex-row sm:items-start">
                  <button className="min-w-0 flex-1 text-left" title="进入这个数据源的表与字段"
                          onClick={() => { onSelect(ds.id); onOpenTables(ds.id); }}>
                    <span className="flex flex-wrap items-center gap-1.5">
                      <span className="truncate text-body font-medium">{ds.name}</span>
                      {selectedId === ds.id && <Badge tone="bg-brand/10 text-brand">当前</Badge>}
                      {ds.status === "ok" && <Badge tone="bg-ok/10 text-ok">已连通</Badge>}
                      {ds.status === "error" && <Badge tone="bg-bad/10 text-bad">连接异常</Badge>}
                      {ds.status === "new" && <Badge tone="bg-warn/10 text-warn">未测试</Badge>}
                      {ds.read_only && (
                        <span title="按只读方式使用"><ShieldCheck className="h-3.5 w-3.5 text-ok" /></span>
                      )}
                    </span>
                    <span className="mt-0.5 block truncate font-mono text-label text-muted">
                      <Badge className="mr-1.5 font-sans">{TYPE_LABEL[ds.ds_type] || ds.ds_type}</Badge>
                      {ds.ds_type === "sqlite" ? "上传文件导入的只读库" : `${ds.username}@${ds.host}:${ds.port}/${ds.db_name}`}
                    </span>
                    {ds.ds_type !== "sqlite" && (
                      <span className="mt-0.5 block truncate text-label text-muted" title={String((ds.extra as any)?.tables || "")}>
                        接入范围:{(ds.extra as any)?.tables
                          ? (String((ds.extra as any).tables).match(/[*?]/)
                            ? <span className="font-mono">{String((ds.extra as any).tables)}</span>
                            : `${splitScope(String((ds.extra as any).tables)).length} 张表`)
                          : "整个库"}
                      </span>
                    )}
                    <span className="mt-0.5 block text-label text-muted">
                      {ds.last_introspect_at
                        ? <><span className="font-medium text-ink">{ds.table_count ?? 0} 张表</span> · 上次读取表结构 {formatTime(ds.last_introspect_at)}</>
                        : "还没有读取表结构"}
                    </span>
                    {ds.status === "error" && ds.last_error && (
                      <span className="mt-0.5 block truncate text-label text-bad" title={ds.last_error}>
                        {ds.last_error}
                      </span>
                    )}
                  </button>

                  {/* 按钮成组靠右,小屏换行到下一行整体左对齐,不跟文字挤在一起 */}
                  <div className="flex shrink-0 flex-wrap items-center gap-1 sm:justify-end">
                    <button className="btn btn-sm" disabled={busy === ds.id}
                            onClick={() => test(ds)} title="测试连接是否可用">
                      {busy === ds.id ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                      : <Plug className="h-3.5 w-3.5" />}
                      测试
                    </button>
                    <button className={cn("btn btn-sm", !ds.last_introspect_at && "btn-primary")}
                            disabled={busy === ds.id || !!job}
                            onClick={() => introspect(ds)} title="抓取表结构并采样枚举列">
                      <RefreshCw className="h-3.5 w-3.5" /> {ds.last_introspect_at ? "重新读取" : "读取表结构"}
                    </button>
                    {!!ds.table_count && (
                      <button className="btn btn-primary btn-sm" onClick={() => onOpenTables(ds.id)}
                              title="查看这个数据源的表与字段">
                        查看表 <ArrowRight className="h-3.5 w-3.5" />
                      </button>
                    )}
                    {ds.ds_type === "sqlite"
                      ? <button className="btn btn-ghost btn-sm" title="追加文件或改名" onClick={() => setFileDs(ds)}>
                          <FileUp className="h-3.5 w-3.5" />追加 / 改名</button>
                      : <>
                          <button className="btn btn-ghost btn-sm" title="连上库,重新勾选要接入的表"
                                  onClick={() => { setEditing(ds); setCreating(false); setPickTables(true); }}>
                            <ListChecks className="h-3.5 w-3.5" />选表</button>
                          <button className="btn btn-ghost btn-sm"
                                  onClick={() => { setEditing(ds); setCreating(false); setPickTables(false); }}>编辑</button>
                        </>}
                    <button className="btn btn-ghost btn-sm text-bad" onClick={() => setConfirmDel(ds)}
                            title="删除数据源及其全部建模">
                      <Trash2 className="h-3.5 w-3.5" />
                    </button>
                  </div>
                </div>

                {job?.dsId === ds.id && job.item && (
                  <div className="mt-2.5">
                    <Progress value={job.item.progress} />
                    <p className="mt-1 text-label text-muted">{job.item.message || "处理中…"}</p>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </Card>

      <Modal open={picking} onClose={() => setPicking(false)} title="新建连接" width="max-w-2xl"
            >
        <div className="space-y-3">
          {[...new Set(KINDS.map((k) => k.group))].map((g) => (
            <div key={g}>
              <p className="mb-1.5 text-label font-medium text-muted">{g}</p>
              <div className="grid gap-2 sm:grid-cols-2">
                {KINDS.filter((k) => k.group === g).map((k) => (
                  <button key={k.key} disabled={k.soon || (!cryptoReady && !!k.port)}
                          className="flex items-center gap-2.5 rounded-lg border border-line p-2.5 text-left hover:border-brand/40 disabled:opacity-50"
                          onClick={() => {
                            setPicking(false);
                            if (k.key === "api") { onOpenApi?.(); return; }
                            if (k.key === "file") { setFileDs("new"); return; }
                            setEditing({ ...BLANK, ds_type: k.ds_type, port: k.port } as unknown as DataSource); setCreating(true); setPickTables(false);
                          }}>
                    <span className="grid h-8 w-8 shrink-0 place-items-center rounded-lg bg-brand/10 text-brand">
                      {k.key === "api" ? <Globe className="h-4 w-4" /> : k.key === "file" ? <FileSpreadsheet className="h-4 w-4" /> : <Database className="h-4 w-4" />}</span>
                    <span className="min-w-0"><span className="block text-body font-medium">{k.label}</span>
                      <span className="block text-label text-muted">{k.desc}{k.port ? ` · 默认端口 ${k.port}` : ""}</span></span>
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </Modal>

      {fileDs && <FileSourceForm ds={fileDs === "new" ? null : fileDs} onClose={() => setFileDs(null)}
                                 onSaved={(id) => { setFileDs(null); load(); onChanged(); onSelect(id); }} />}

      <DataSourceForm
        open={!!editing} creating={creating} initial={editing} pickTables={pickTables}
        onClose={() => setEditing(null)}
        onSaved={() => { setEditing(null); load(); onChanged(); }} />

      <Confirm
        open={!!confirmDel} danger title="删除数据源?"
        body={`将同时删除「${confirmDel?.name ?? ""}」下的全部建模、关系与指标定义。沉淀的问答对也会失去关联。此操作不可撤销。`}
        confirmText="删除" onConfirm={() => confirmDel && remove(confirmDel)}
        onClose={() => setConfirmDel(null)} />
    </div>
  );
}

/** 老数据的表范围可能是通配符(otlg_dm_*):回填勾选时按它匹配。和后端 fnmatch 一致:不分大小写 */
function globMatch(patterns: string[], name: string): boolean {
  return patterns.some((p) => new RegExp(
    `^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i").test(name));
}
const splitScope = (raw: string) => raw.split(/[,\n,]/).map((x) => x.trim()).filter(Boolean);

function DataSourceForm({ open, creating, initial, pickTables, onClose, onSaved }: {
  open: boolean; creating: boolean; initial: DataSource | null;
  /** 从列表行的「选表」进来:打开就去连一下、列出表 */
  pickTables?: boolean;
  onClose: () => void; onSaved: () => void;
}) {
  const [form, setForm] = useState({ ...BLANK });
  const [password, setPassword] = useState("");
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");
  const [probe, setProbe] = useState<ProbeResult | null>(null);
  const [probing, setProbing] = useState(false);
  const [probeErr, setProbeErr] = useState("");
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [kw, setKw] = useState("");
  const tablesRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!initial) return;
    setForm({
      name: initial.name ?? "", ds_type: initial.ds_type ?? "mysql", host: initial.host ?? "",
      port: initial.port ?? 3306, db_name: initial.db_name ?? "",
      username: initial.username ?? "", password: "",
      schema: String((initial.extra as any)?.schema || "public"),
      tables: String((initial.extra as any)?.tables || ""),
      writeback: !!(initial.extra as any)?.writeback,
    });
    setPassword("");
    setErr("");
    setProbe(null); setProbeErr(""); setKw("");
  }, [initial]);

  // 改了连接信息,上一次的测试结果就不作数了
  const set = (k: string, v: string | number | boolean) => {
    setForm((f) => ({ ...f, [k]: v }));
    if (["host", "port", "db_name", "username", "schema"].includes(k)) { setProbe(null); setProbeErr(""); }
  };

  const connOk = !!(form.host.trim() && form.db_name.trim() && form.username.trim() && (password || !creating));

  const runProbe = async () => {
    setProbing(true); setProbeErr("");
    try {
      const r = await api.probeDatasource({
        ds_id: creating ? 0 : initial?.id ?? 0, ds_type: form.ds_type, host: form.host.trim(), port: form.port,
        db_name: form.db_name.trim(), username: form.username.trim(), password,
        extra: form.ds_type === "postgres" ? { schema: form.schema || "public" } : {},
      });
      setProbe(r);
      // 新建:一张都不勾,自己挑;编辑:按现有范围回填(空范围 = 整库)
      const scope = splitScope(form.tables);
      setSelected(new Set(creating ? [] : r.tables.filter((t) => !scope.length || globMatch(scope, t.name)).map((t) => t.name)));
      window.setTimeout(() => tablesRef.current?.scrollIntoView({ behavior: "smooth", block: "nearest" }), 50);
    } catch (e) {
      setProbe(null);
      setProbeErr(e instanceof Error ? e.message : String(e));
    } finally { setProbing(false); }
  };

  // 从「选表」进来:口令已存,表单回填完(host 对上了)就直接连
  useEffect(() => {
    if (open && pickTables && initial && !creating && form.host === initial.host && !probe && !probing && !probeErr) void runProbe();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, pickTables, initial, form.host]);

  const shown = useMemo(() => {
    const k = kw.trim().toLowerCase();
    return (probe?.tables ?? []).filter((t) => !k || t.name.toLowerCase().includes(k) || t.comment.toLowerCase().includes(k));
  }, [probe, kw]);

  const toggleAll = (on: boolean) => setSelected((cur) => {
    const next = new Set(cur);
    for (const t of shown) { if (on) next.add(t.name); else next.delete(t.name); }
    return next;
  });

  /** 最终写进 extra.tables 的值。全选 = 空(整库,以后新增的表也算进来) */
  const scopeValue = (): string => {
    if (!probe) return form.tables.trim();
    if (selected.size === probe.tables.length) return "";
    return probe.tables.filter((t) => selected.has(t.name)).map((t) => t.name).join(",");
  };

  const save = async () => {
    if (creating && !probe) { setErr("先测试连接,再选要接入的表"); return; }
    if (probe && selected.size === 0) { setErr("至少选一张表"); return; }
    setSaving(true);
    setErr("");
    try {
      const { schema, tables: _t, writeback, ...rest } = form;
      const tables = scopeValue();
      const extra: Record<string, string | boolean> = form.ds_type === "postgres" ? { schema: schema || "public" } : {};
      if (tables) extra.tables = tables;
      if (writeback) extra.writeback = true;
      if (creating) {
        const ds = await api.createDatasource({ ...rest, password, extra });
        // 建完直接测连通、连通就读表结构:用户不必再回列表点两下
        try {
          await api.testDatasource(ds.id);
          await api.introspect(ds.id);
          toast("ok", "数据源已创建", "正在读取所选表的结构");
        } catch (e) {
          toast("error", "数据源已保存,但连接失败", e instanceof Error ? e.message : String(e));
        }
        onSaved();
        return;
      } else if (initial) {
        const body: Record<string, unknown> = { ...rest, extra };
        delete body.ds_type;
        // 留空 = 不改口令。前端不回显明文,所以必须能表达"没动过"
        if (password) body.password = password;
        else delete body.password;
        await api.updateDatasource(initial.id, body);
        // 表范围变了:重新读一遍表结构,新勾的表才进得来,取消勾选的表会移出
        if (tables !== String((initial.extra as any)?.tables || "")) {
          await api.introspect(initial.id).catch(() => undefined);
          toast("ok", "数据源已更新", "接入的表变了,正在重新读取表结构");
          onSaved();
          return;
        }
      }
      toast("ok", creating ? "数据源已创建" : "数据源已更新");
      onSaved();
    } catch (e) {
      setErr(e instanceof ApiError ? e.message : e instanceof Error ? e.message : String(e));
    } finally { setSaving(false); }
  };

  const ok = form.name.trim() && form.host.trim() && form.db_name.trim() && form.username.trim() && (password || !creating);

  return (
    <Modal
      open={open} onClose={onClose} width="max-w-2xl"
      title={`${creating ? "新建" : "编辑"}${TYPE_LABEL[form.ds_type] || ""}数据源`}
      footer={
        <>
          {err && <p className="mr-auto min-w-0 flex-1 text-label text-bad">{err}</p>}
          <button className="btn btn-sm" onClick={onClose}>取消</button>
          <button className="btn btn-primary btn-sm" disabled={!ok || saving} onClick={save}>
            {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
            保存
          </button>
        </>
      }>
      <div className="space-y-4">
        <Field label="名称" required>
          <input className="input" value={form.name} placeholder="如:门店运营库"
                 onChange={(e) => set("name", e.target.value)} />
        </Field>

        <div className="space-y-3 rounded-lg border border-line bg-elevated/50 p-3">
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
            <Field label="主机" required>
              <input className="input" value={form.host} placeholder="192.168.x.x"
                     onChange={(e) => set("host", e.target.value)} />
            </Field>
            <Field label="端口" required>
              <input className="input" type="number" value={form.port}
                     onChange={(e) => set("port", Number(e.target.value) || 3306)} />
            </Field>
          </div>
          <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
            {form.ds_type === "postgres" && (
              <Field label="Schema">
                <input className="input" value={form.schema} onChange={(e) => set("schema", e.target.value)} />
              </Field>
            )}
            <Field label="数据库" required>
              <input className="input" value={form.db_name} placeholder="库名"
                     onChange={(e) => set("db_name", e.target.value)} />
            </Field>
            <Field label="用户名" required>
              <input className="input" value={form.username} autoComplete="off"
                     onChange={(e) => set("username", e.target.value)} />
            </Field>
          </div>
          {/* 口令和「测试连接」一行:填完最后一项顺手就测 */}
          <div className="grid grid-cols-1 items-end gap-3 sm:grid-cols-[minmax(0,1fr)_auto]">
            <Field label={<>口令{!creating && <span className="ml-1 font-normal text-muted">留空不修改</span>}</>} required={creating}>
              <input className="input" type="password" value={password} autoComplete="new-password"
                     placeholder={creating ? "" : "••••••••"}
                     onChange={(e) => { setPassword(e.target.value); setProbe(null); setProbeErr(""); }} />
            </Field>
            <button className={cn("btn h-[38px]", probe ? "" : "btn-primary")} disabled={!connOk || probing}
                    onClick={() => void runProbe()}>
              {probing ? <Loader2 className="h-3.5 w-3.5 animate-spin" />
                : probe ? <CheckCircle2 className="h-3.5 w-3.5 text-ok" /> : <Plug className="h-3.5 w-3.5" />}
              {probe ? "重新测试" : "测试连接"}
            </button>
          </div>

          {probeErr && (
            <p className="flex items-start gap-1.5 text-label text-bad">
              <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
              <span className="min-w-0 break-words">{probeErr}</span>
            </p>
          )}
          {probe && (
            <p className="flex items-center gap-1.5 text-label">
              <CheckCircle2 className="h-3.5 w-3.5 shrink-0 text-ok" />
              <span className="text-ok">连接成功</span>
              <span className="text-muted">· {probe.database} · {probe.version}</span>
              {probe.warning && <span className="text-warn" title={probe.warning}>· 账号有写权限</span>}
            </p>
          )}
        </div>

        {probe && (
          <div ref={tablesRef} className="rounded-lg border border-line">
            <div className="flex flex-wrap items-center gap-2 border-b border-line px-2.5 py-2">
              <span className="text-label font-medium">接入的表</span>
              <div className="relative min-w-[160px] flex-1">
                <Search className="pointer-events-none absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted" />
                <input className="input py-1 pl-7 text-label" placeholder="筛选" value={kw}
                       onChange={(e) => setKw(e.target.value)} />
              </div>
              <button className="btn btn-ghost btn-sm" onClick={() => toggleAll(true)}>全选</button>
              <button className="btn btn-ghost btn-sm" onClick={() => toggleAll(false)}>全不选</button>
              <span className="text-label tabular-nums text-muted">
                <span className="font-medium text-ink">{selected.size}</span> / {probe.tables.length}
              </span>
            </div>
            <div className="max-h-[300px] overflow-auto">
              {shown.length === 0 ? (
                <p className="px-3 py-4 text-center text-label text-muted">{probe.tables.length ? "没有匹配的表" : "这个库里没有表"}</p>
              ) : shown.map((t) => (
                <label key={t.name} title={t.comment || t.name}
                       className="flex h-8 cursor-pointer items-center gap-2 border-b border-line px-2.5 last:border-0 hover:bg-ink/[0.02]">
                  <input type="checkbox" checked={selected.has(t.name)}
                         onChange={(e) => setSelected((cur) => {
                           const next = new Set(cur);
                           if (e.target.checked) next.add(t.name); else next.delete(t.name);
                           return next;
                         })} />
                  <span className="max-w-[45%] shrink-0 truncate font-mono text-label">{t.name}</span>
                  {t.kind === "view" && <Badge tone="bg-brand2/10 text-brand2">视图</Badge>}
                  <span className="min-w-0 flex-1 truncate text-label text-muted">{t.comment}</span>
                  <span className="w-20 shrink-0 text-right text-caption tabular-nums text-muted">
                    {t.kind !== "view" && `${t.row_count_est.toLocaleString()} 行`}
                  </span>
                </label>
              ))}
            </div>
          </div>
        )}

        <label className="flex items-center gap-2 text-label"
               title="打开后,审批通过的动作(如新建采购单、改状态)会直接写进业务表,可撤销;需要账号有写权限">
          <input type="checkbox" checked={form.writeback} onChange={(e) => set("writeback", e.target.checked)} />
          允许审批通过的动作写回业务库
        </label>
      </div>
    </Modal>
  );
}

/** 本地文件:CSV / Excel(每个工作表一张表)/ JSON 导入成只读库,之后和数据库一样内省、映射、提问。 */
function FileSourceForm({ ds, onClose, onSaved }: { ds: DataSource | null; onClose: () => void; onSaved: (id: number) => void }) {
  const [name, setName] = useState(ds?.name || "");
  const [files, setFiles] = useState<File[]>([]);
  const [busy, setBusy] = useState(false);
  const renamed = !!ds && name.trim() !== "" && name.trim() !== ds.name;
  const save = async () => {
    setBusy(true);
    try {
      if (renamed && ds) await api.updateDatasource(ds.id, { name: name.trim() });
      if (!files.length && ds) { toast("ok", "已改名"); onSaved(ds.id); return; }
      const r = await api.createFileDatasource(name || files[0]?.name || "本地文件", files, ds?.id || 0);
      toast("ok", `已导入 ${r.imported.length} 张表`, r.imported.map((t) => `${t.table}(${t.rows} 行)`).join("、"));
      await api.introspect(r.id).catch(() => undefined);
      onSaved(r.id);
    } catch (e) { toast("error", "保存失败", e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }
  };
  return (
    <Modal open onClose={onClose} title={ds ? `「${ds.name}」追加文件 / 改名` : "本地文件数据源"}
           desc="同名文件再传会覆盖原来的"
           footer={<><button className="btn btn-sm" onClick={onClose}>取消</button>
             <button className="btn btn-primary btn-sm" disabled={busy || (!files.length && !renamed)} onClick={() => void save()}>
               {busy && <Loader2 className="h-3.5 w-3.5 animate-spin" />}{files.length ? "导入" : "保存"}</button></>}>
      <div className="space-y-3">
        <Field label="名称"><input className="input" placeholder="如:产线日报(Excel)" value={name} onChange={(e) => setName(e.target.value)} /></Field>
        <Field label="文件" hint="支持 csv、tsv、xlsx、json;第一行是表头">
          <input type="file" multiple accept=".csv,.tsv,.xlsx,.xlsm,.json" className="input"
                 onChange={(e) => setFiles(Array.from(e.target.files || []))} />
        </Field>
        {files.map((f) => <p key={f.name} className="text-label text-muted">{f.name} · {Math.ceil(f.size / 1024)} KB</p>)}
      </div>
    </Modal>
  );
}