import { ref } from 'vue' import { useEventBus } from './useEventBus' import type { StructureInfo } from './useEventBus' import { STORAGE_KEYS } from '../constants/storage' import { getTableStructure } from '@/api' class StructureStore { public readonly loading = ref(false) public readonly error = ref('') public readonly data = ref(null) public readonly info = ref(null) private eventBus = useEventBus() setLoading(loading: boolean): void { this.loading.value = loading this.eventBus.emit('structure:loading', { loading }) } setError(error: string): void { this.error.value = error this.eventBus.emit('structure:error', { error }) } setData(data: any, info: StructureInfo): void { this.data.value = data this.info.value = info this.error.value = '' this.loading.value = false try { localStorage.setItem(STORAGE_KEYS.STRUCTURE_INFO, JSON.stringify(info)) } catch {} this.eventBus.emit('structure:data', { data, info }) } clear(): void { this.data.value = null this.info.value = null this.error.value = '' this.loading.value = false try { localStorage.removeItem(STORAGE_KEYS.STRUCTURE_INFO) } catch {} this.eventBus.emit('structure:clear', {}) } restoreStructureInfo(): StructureInfo | null { try { const saved = localStorage.getItem(STORAGE_KEYS.STRUCTURE_INFO) return saved ? JSON.parse(saved) as StructureInfo : null } catch { return null } } async loadStructure( connectionId: number, database: string, tableName: string, dbType: 'mysql' | 'mongo' | 'redis', nodeType: string ): Promise { // 跳过非表节点 if (nodeType === 'connection' || nodeType === 'database' || !tableName) { this.info.value = { connectionId, database, tableName: '', dbType, nodeType } this.data.value = null return } // 检查是否切换到不同的表 const currentInfo = this.info.value const isDifferentTable = !currentInfo || currentInfo.connectionId !== connectionId || currentInfo.database !== database || currentInfo.tableName !== tableName if (isDifferentTable) { this.data.value = null this.error.value = '' } try { this.setLoading(true) const result = await getTableStructure( connectionId, database, tableName ) this.setData(result, { connectionId, database, tableName, dbType, nodeType }) } catch (error: unknown) { const errorMsg = error instanceof Error ? error.message : '加载表结构失败' this.setError(errorMsg) this.data.value = null this.info.value = null } finally { this.setLoading(false) } } async refreshStructure(): Promise { if (!this.info.value) return await this.loadStructure( this.info.value.connectionId, this.info.value.database, this.info.value.tableName, this.info.value.dbType, this.info.value.nodeType ) } } let structureStoreInstance: StructureStore | null = null export function useStructureStore(): StructureStore { if (!structureStoreInstance) { structureStoreInstance = new StructureStore() } return structureStoreInstance } export type { StructureInfo }