SqlPage.tsx 6.11 KB
import { Database, Globe, Library, MessagesSquare, Table2 } from "lucide-react";
import { useCallback, useEffect, useState } from "react";
import { api } from "@/lib/api";
import { useHashParams } from "@/lib/nav";
import type { Me } from "@/lib/onto";
import { Card, Empty, Segmented, Spinner } from "@/components/ui";
import { cn } from "@/lib/utils";
import type { DataSource } from "@/lib/types";
import { CapabilityPage } from "../capability/CapabilityPage";
import { AskPanel } from "./AskPanel";
import { DataSourcePanel } from "./DataSourcePanel";
import { KnowledgePanel } from "./KnowledgePanel";
import { ModelingPanel } from "./ModelingPanel";
import { loadFailed } from "@/store/useAppStore";

type Tab = "sources" | "modeling" | "console" | "knowledge" | "api";

// 数据连接:数据源、表与字段(含表间关联)、SQL 调试台、知识库(问答示例 / 取数规则 / 指标)、外部系统 / API。
// 业务提问统一在「提问」页;调试台给实施人员看清一句话是怎么变成 SQL 的,并就地纠正、沉淀进知识库。
const TABS: { key: Tab; label: string; icon: React.ReactNode }[] = [
  { key: "sources", label: "数据源", icon: <Database className="h-3.5 w-3.5" /> },
  { key: "modeling", label: "表与字段", icon: <Table2 className="h-3.5 w-3.5" /> },
  { key: "console", label: "SQL 调试台", icon: <MessagesSquare className="h-3.5 w-3.5" /> },
  { key: "knowledge", label: "知识库", icon: <Library className="h-3.5 w-3.5" /> },
  { key: "api", label: "外部系统 / API", icon: <Globe className="h-3.5 w-3.5" /> },
];

const DS_KEY = "data.dsId";
const rememberedDs = (): number | null => {
  try { return Number(localStorage.getItem(DS_KEY)) || null; } catch { return null; }
};

/** 把页签 / 数据源 / 二级页签写进 hash(不产生历史记录):刷新、复制链接都回到同一处 */
function syncHash(tab: Tab, ds: number | null) {
  const q = new URLSearchParams(window.location.hash.split("?")[1] || "");
  q.set("tab", tab);
  if (ds) q.set("ds", String(ds)); else q.delete("ds");
  if (tab !== "modeling") q.delete("sub");
  history.replaceState(null, "", `#/data?${q.toString()}`);
}

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>(Number(params.get("ds")) || rememberedDs());

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

  useEffect(load, [load]);

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

  useEffect(() => {
    if (!sources) return;      // 还没确定数据源时别把 hash 里的 ds 抹掉
    syncHash(tab, dsId);
    try { if (dsId) localStorage.setItem(DS_KEY, String(dsId)); } catch { /* 记不住不影响使用 */ }
  }, [tab, dsId, sources]);

  const current = sources?.find((s) => s.id === dsId) ?? null;
  const canEdit = !!me?.permissions.includes("build");
  // 表与字段自己带数据源切换(和表放在一起看更顺手);数据源页、API 页用不到
  const showGlobalPicker = !!sources && sources.length > 0 && tab !== "sources" && tab !== "api" && tab !== "modeling";

  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" />

        {showGlobalPicker && (
          <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>
        )}
      </div>

      {/* 调试台自己管滚动(对话区滚、输入框钉在底下),别再套一层外部滚动条 */}
      <div className={cn("min-h-0 flex-1", tab === "console" ? "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")}
                           onOpenTables={(id) => { setDsId(id); setTab("modeling"); }} />
        ) : !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 === "console" ? (
          <AskPanel dsId={current.id} dsName={current.name} />
        ) : tab === "knowledge" ? (
          <KnowledgePanel dsId={current.id} canEdit={canEdit} onOpenConsole={() => setTab("console")} />
        ) : (
          <ModelingPanel dsId={current.id} dsName={current.name} canEdit={canEdit}
                         sources={sources} onSwitchSource={setDsId} onSourcesChanged={load}
                         onOpenSources={() => setTab("sources")} />
        )}
      </div>
    </div>
  );
}