catalog.ts 2.41 KB
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import type { CaseItem, DatasetItem, DatasetState, IntentItem } from "../types";
import { fetchCases, fetchDatasets, fetchIntents, setDataset } from "../api/intentFusion";

export const useCatalogStore = defineStore("catalog", () => {
  const intents = ref<IntentItem[]>([]);
  const cases = ref<CaseItem[]>([]);
  const datasets = ref<DatasetItem[]>([]);
  const currentDataset = ref<DatasetState | null>(null);
  const loading = ref(false);
  const datasetLoading = ref(false);
  const error = ref<string | null>(null);

  const domains = computed(() => {
    const map = new Map<string, IntentItem[]>();
    for (const i of intents.value) {
      const arr = map.get(i.domain) ?? [];
      arr.push(i);
      map.set(i.domain, arr);
    }
    return Array.from(map.entries()).map(([domain, items]) => ({
      domain,
      items: items.slice().sort((a, b) => a.name.localeCompare(b.name)),
    }));
  });

  const datasetKey = computed(() => currentDataset.value?.key ?? "");

  async function refreshDatasets(): Promise<void> {
    datasetLoading.value = true;
    error.value = null;
    try {
      const res = await fetchDatasets();
      datasets.value = res.items;
      currentDataset.value = res.current;
    } catch (e: any) {
      error.value = e?.message ? String(e.message) : "加载失败";
    } finally {
      datasetLoading.value = false;
    }
  }

  async function refresh(): Promise<void> {
    loading.value = true;
    error.value = null;
    try {
      const [i, c] = await Promise.all([fetchIntents(), fetchCases()]);
      intents.value = i;
      cases.value = c;
    } catch (e: any) {
      error.value = e?.message ? String(e.message) : "加载失败";
    } finally {
      loading.value = false;
    }
  }

  async function switchDataset(key: string): Promise<void> {
    if (!key || key === currentDataset.value?.key) return;
    datasetLoading.value = true;
    error.value = null;
    try {
      const res = await setDataset(key);
      currentDataset.value = res.current;
      await refresh();
    } catch (e: any) {
      error.value = e?.message ? String(e.message) : "切换失败";
    } finally {
      datasetLoading.value = false;
    }
  }

  return {
    intents,
    cases,
    domains,
    datasets,
    currentDataset,
    datasetKey,
    loading,
    datasetLoading,
    error,
    refresh,
    refreshDatasets,
    switchDataset,
  };
});