DataSourcePanel.tsx 14.2 KB
import {
  AlertTriangle, Database, Loader2, Plug, RefreshCw, ShieldCheck, Trash2,
} from "lucide-react";
import { useCallback, useEffect, 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 } from "@/lib/types";

const BLANK = { name: "", ds_type: "mysql", host: "", port: 3306, db_name: "", username: "", password: "" };

export function DataSourcePanel({ selectedId, onSelect, onChanged }: {
  selectedId: number | null;
  onSelect: (id: number) => void;
  onChanged: () => 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 [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 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);
          setJob(null);
          load();
          onChanged();
          return;     // 不再排下一次
        }
      } catch { /* 任务还没落库,下一轮再看 */ }
      timer.current = window.setTimeout(tick, 1200);
    };
    timer.current = window.setTimeout(tick, 800);
    return () => window.clearTimeout(timer.current);
  }, [jobId, load, onChanged]);

  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);
      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);
  };

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

  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-[13px] 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="建议使用只读账号连接业务库。口令加密存储,不会明文落库,也不会回显。"
          right={
            <button className="btn btn-primary btn-sm" disabled={!cryptoReady}
                    onClick={() => { setEditing({ ...BLANK } as unknown as DataSource); setCreating(true); }}>
              <Database className="h-3.5 w-3.5" /> 新建
            </button>
          } />

        {items.length === 0 ? (
          <Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
                 desc="添加一个 MySQL 连接,做一次内省,就能开始用自然语言提问了。" />
        ) : (
          <div className="divide-y divide-line">
            {items.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" onClick={() => onSelect(ds.id)}>
                    <span className="flex flex-wrap items-center gap-1.5">
                      <span className="truncate text-[13.5px] 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-[11.5px] text-muted">
                      {ds.username}@{ds.host}:{ds.port}/{ds.db_name}
                    </span>
                    <span className="mt-0.5 block text-[11.5px] text-muted">
                      {ds.last_introspect_at
                        ? `上次内省 ${formatTime(ds.last_introspect_at)}`
                        : "还没有内省过 —— 内省一次才能开始提问"}
                    </span>
                    {ds.status === "error" && ds.last_error && (
                      <span className="mt-0.5 block truncate text-[11.5px] 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" /> 内省
                    </button>
                    <button className="btn btn-ghost btn-sm"
                            onClick={() => { setEditing(ds); setCreating(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-[11.5px] text-muted">{job.item.message || "处理中…"}</p>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </Card>

      <DataSourceForm
        open={!!editing} creating={creating} initial={editing}
        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>
  );
}

function DataSourceForm({ open, creating, initial, onClose, onSaved }: {
  open: boolean; creating: boolean; initial: DataSource | null;
  onClose: () => void; onSaved: () => void;
}) {
  const [form, setForm] = useState({ ...BLANK });
  const [password, setPassword] = useState("");
  const [saving, setSaving] = useState(false);
  const [err, setErr] = useState("");

  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: "",
    });
    setPassword("");
    setErr("");
  }, [initial]);

  const set = (k: string, v: string | number) => setForm((f) => ({ ...f, [k]: v }));

  const save = async () => {
    setSaving(true);
    setErr("");
    try {
      if (creating) {
        await api.createDatasource({ ...form, password });
      } else if (initial) {
        const body: Record<string, unknown> = { ...form };
        delete body.ds_type;
        // 留空 = 不改口令。前端不回显明文,所以必须能表达"没动过"
        if (password) body.password = password;
        else delete body.password;
        await api.updateDatasource(initial.id, body);
      }
      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();

  return (
    <Modal
      open={open} onClose={onClose} width="max-w-xl"
      title={creating ? "新建数据源" : "编辑数据源"}
      desc="连上业务库之后,还要做一次内省才能开始提问。"
      footer={
        <>
          {err && <p className="mr-auto min-w-0 flex-1 text-[12.5px] 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
               hint="给人看的名字,问答页的数据源下拉里显示的就是它。">
          <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">
          <p className="text-[12px] font-medium text-muted">连接信息</p>
          <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">
            <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>
          <Field
            label={<>口令{!creating && <span className="ml-1 font-normal">(留空表示不修改)</span>}</>}
            required={creating}
            hint="加密后存库,任何接口都不会把它回显出来。强烈建议使用只读账号。">
            <input className="input" type="password" value={password} autoComplete="new-password"
                   placeholder={creating ? "" : "••••••••"}
                   onChange={(e) => setPassword(e.target.value)} />
          </Field>
        </div>

        <p className="text-[11.5px] leading-relaxed text-muted">
          目前只支持 MySQL。保存后回到列表点「测试」确认连得通,再点「内省」抓表结构。
        </p>
      </div>
    </Modal>
  );
}