// src/hooks/useRemoteSearch.ts
import { ref, reactive, onUnmounted } from 'vue'
import type { Ref } from 'vue'

export interface SearchOption {
  label: string
  value: string | number
  [key: string]: any
}

export interface RemoteSearchConfig {
  type: string
  apiMethod: (params: any) => Promise<any>
  formatResult?: (data: any[]) => SearchOption[]
  cacheKey?: string
  debounceDelay?: number
  defaultOptions?: SearchOption[]
}

export interface RemoteSearchState {
  loading: boolean
  options: SearchOption[]
  cache: Map<string, SearchOption[]>
}

export function useRemoteSearch(config: RemoteSearchConfig) {
  const {
    type,
    apiMethod,
    formatResult = defaultFormatResult,
    cacheKey = type,
    debounceDelay = 500,
    defaultOptions = []
  } = config

  // 状态
  const state = reactive<RemoteSearchState>({
    loading: false,
    options: [...defaultOptions],
    cache: new Map()
  })

  // 防抖相关
  let debounceTimer: NodeJS.Timeout | null = null
  let lastQuery = ''

  // 默认格式化函数
  function defaultFormatResult(data: any[]): SearchOption[] {
    return data.map(item => ({
      label: item.name || item.label || item.text || String(item.value),
      value: item.id || item.value || item.key,
      ...item
    }))
  }

  // 从缓存获取
  function getFromCache(query: string): SearchOption[] | null {
    const cacheKeyWithQuery = `${cacheKey}:${query || 'all'}`
    return state.cache.get(cacheKeyWithQuery) || null
  }

  // 保存到缓存
  function saveToCache(query: string, data: SearchOption[]) {
    const cacheKeyWithQuery = `${cacheKey}:${query || 'all'}`
    state.cache.set(cacheKeyWithQuery, data)
    
    // 限制缓存大小（最多100条记录）
    if (state.cache.size > 100) {
      const firstKey = state.cache.keys().next().value
      state.cache.delete(firstKey)
    }
  }

  // 执行搜索
  async function performSearch(query: string): Promise<SearchOption[]> {
    // 检查缓存
    const cached = getFromCache(query)
    if (cached && cached.length > 0) {
      return cached
    }

    state.loading = true
    
    try {
      // 调用API
      const params = query ? { keyword: query, pageSize: 50 } : { pageSize: 100 }
      const response = await apiMethod(params)
      
      // 格式化结果
      const result = formatResult(response.data || response.list || response.records || [])
      
      // 保存到缓存
      saveToCache(query, result)
      
      return result
    } catch (error) {
      console.error(`远程搜索失败 [${type}]:`, error)
      throw error
    } finally {
      state.loading = false
    }
  }

  // 搜索方法（带防抖）
  async function search(query: string = ''): Promise<SearchOption[]> {
    // 清除之前的定时器
    if (debounceTimer) {
      clearTimeout(debounceTimer)
      debounceTimer = null
    }

    // 如果查询相同，直接返回当前选项
    if (query === lastQuery) {
      return state.options
    }

    lastQuery = query

    // 如果是空查询且有默认选项，直接返回
    if (!query && defaultOptions.length > 0) {
      state.options = defaultOptions
      return defaultOptions
    }

    return new Promise((resolve) => {
      debounceTimer = setTimeout(async () => {
        try {
          const result = await performSearch(query)
          state.options = result
          resolve(result)
        } catch (error) {
          state.options = []
          resolve([])
        }
      }, debounceDelay)
    })
  }

  // 预加载数据（初始化时调用）
  async function preload(): Promise<void> {
    if (state.options.length === 0) {
      await search('')
    }
  }

  // 清空缓存
  function clearCache(): void {
    state.cache.clear()
    state.options = [...defaultOptions]
  }

  // 设置默认选项
  function setDefaultOptions(options: SearchOption[]): void {
    defaultOptions.length = 0
    defaultOptions.push(...options)
    if (state.options.length === 0) {
      state.options = [...options]
    }
  }

  // 组件卸载时清理
  onUnmounted(() => {
    if (debounceTimer) {
      clearTimeout(debounceTimer)
    }
  })

  return {
    state,
    search,
    preload,
    clearCache,
    setDefaultOptions,
    loading: () => state.loading,
    options: () => state.options
  }
}

// 创建多搜索实例的管理器
export function useRemoteSearchManager() {
  const instances = new Map<string, ReturnType<typeof useRemoteSearch>>()

  function getInstance(config: RemoteSearchConfig) {
    const { type } = config
    
    if (!instances.has(type)) {
      instances.set(type, useRemoteSearch(config))
    }
    
    return instances.get(type)!
  }

  function clearAllCache() {
    instances.forEach(instance => {
      instance.clearCache()
    })
  }

  return {
    getInstance,
    clearAllCache
  }
}