SqlPage.tsx 5.63 KB
import { BookmarkCheck, Boxes, Database, Gauge, Globe, MessagesSquare, Table2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { api } from "@/lib/api";
import { go, useHashParams } from "@/lib/nav";
import { errText, onto, type Me } from "@/lib/onto";
import { toast } from "@/store/useAppStore";
import { cn } from "@/lib/utils";
import { Card, Empty, Segmented, Spinner } from "@/components/ui";
import type { DataSource } from "@/lib/types";
import { CapabilityPage } from "../capability/CapabilityPage";
import { AskPanel } from "./AskPanel";
import { DataSourcePanel } from "./DataSourcePanel";
import { LibraryPanel } from "./LibraryPanel";
import { MappingPanel } from "./MappingPanel";
import { ModelingPanel } from "./ModelingPanel";
import { RulesPanel } from "./RulesPanel";

type Tab = "ask" | "sources" | "mapping" | "modeling" | "metrics" | "library" | "api";

// 数据连接:数据库 / 文件数据源、表 → 实体映射、外部系统 / API。
// 业务提问统一在「提问」页;「SQL 调试台」保留给实施人员直接调试取数。
const TABS: { key: Tab; label: string; icon: React.ReactNode }[] = [
  { key: "sources", label: "数据源", icon: <Database className="h-3.5 w-3.5" /> },
  { key: "mapping", label: "实体映射", icon: <Boxes className="h-3.5 w-3.5" /> },
  { key: "modeling", label: "表结构", icon: <Table2 className="h-3.5 w-3.5" /> },
  { key: "metrics", label: "取数规则", icon: <Gauge className="h-3.5 w-3.5" /> },
  { key: "library", label: "沉淀库", icon: <BookmarkCheck className="h-3.5 w-3.5" /> },
  { key: "ask", label: "SQL 调试台", icon: <MessagesSquare className="h-3.5 w-3.5" /> },
  { key: "api", label: "外部系统 / API", icon: <Globe className="h-3.5 w-3.5" /> },
];

export function SqlPage({ me }: { me: Me | null }) {
  const params = useHashParams();
  const [tab, setTab] = useState<Tab>((params.get("tab") as Tab) || "sources");
  useEffect(() => { const t = params.get("tab") as Tab | null; if (t && TABS.some((x) => x.key === t)) setTab(t); }, [params]);
  const [sources, setSources] = useState<DataSource[] | null>(null);
  const [dsId, setDsId] = useState<number | null>(null);

  const load = useCallback(() => {
    api.datasources().then((d) => {
      setSources(d);
      setDsId((cur) => (cur && d.some((x) => x.id === cur) ? cur : d[0]?.id ?? null));
    }).catch(() => setSources([]));
  }, []);

  useEffect(load, [load]);

  // 一个数据源都没有时,直接把人带到数据源页 —— 其余几个页签这时都是空的
  useEffect(() => {
    if (sources && sources.length === 0) setTab((t) => (t === "api" ? t : "sources"));
  }, [sources]);

  const current = sources?.find((s) => s.id === dsId) ?? null;

  return (
    <div className="flex h-full min-h-0 flex-col gap-3">
      <div className="flex flex-wrap items-center gap-2">
        <Segmented<Tab> value={tab} onChange={setTab}
                        options={TABS.map((t) => ({
                          key: t.key,
                          label: <span className="inline-flex items-center gap-1.5">{t.icon}{t.label}</span>,
                        }))} />

        <span className="flex-1" />

        {sources && sources.length > 0 && (
          <label className="flex items-center gap-1.5 text-label text-muted">
            数据源
            <select className="input w-auto py-1" value={dsId ?? ""}
                    onChange={(e) => setDsId(Number(e.target.value))}>
              {sources.map((s) => (
                <option key={s.id} value={s.id}>{s.name}</option>
              ))}
            </select>
          </label>
        )}
        {current && (
          <button className="btn btn-sm" title="把已启用的表与关联翻译成本体提议(对象 + 关系),进入审核队列"
                  onClick={async () => {
                    try {
                      const r = await onto.proposeFromDatasource(current.id);
                      toast("ok", `提议 ${r.proposed} 块积木`, `冲突 ${r.conflicts},补充 ${r.enriched}。到业务建模里审核`);
                      go("modeling");
                    } catch (e) { toast("error", "提议失败", errText(e)); }
                  }}>提议到本体</button>
        )}
      </div>

      {/* 问答页自己管滚动(对话区滚、输入框钉在底下),别再套一层外部滚动条 */}
      <div className={cn("min-h-0 flex-1", tab === "ask" ? "overflow-hidden" : "overflow-auto")}>
        {!sources ? (
          <Card className="p-4"><Spinner /></Card>
        ) : tab === "api" ? (
          <CapabilityPage me={me} />
        ) : tab === "sources" ? (
          <DataSourcePanel selectedId={dsId} onSelect={setDsId} onChanged={load} onOpenApi={() => setTab("api")} />
        ) : !current ? (
          <Card>
            <Empty icon={<Database className="h-6 w-6" />} title="还没有数据源"
                   desc="先到「数据源」页添加一个数据库连接或上传表格文件。"
                   action={
                     <button className="btn btn-primary btn-sm" onClick={() => setTab("sources")}>
                       去添加
                     </button>
                   } />
          </Card>
        ) : tab === "ask" ? (
          <AskPanel dsId={current.id} dsName={current.name} />
        ) : tab === "mapping" ? (
          <MappingPanel dsId={current.id} canEdit={!!me?.permissions.includes("build")} />
        ) : tab === "modeling" ? (
          <ModelingPanel dsId={current.id} />
        ) : tab === "metrics" ? (
          <RulesPanel dsId={current.id} />
        ) : (
          <LibraryPanel dsId={current.id} />
        )}
      </div>
    </div>
  );
}