import { ref } from 'vue'

export interface SearchOptions {
  debounceTime?: number
  minLength?: number
  maxHistoryCount?: number
}

export function useSearch(options: SearchOptions = {}) {
  const { debounceTime = 300, minLength = 1, maxHistoryCount = 10 } = options

  const isSearching = ref(false)
  const searchHistory = ref<string[]>([])
  const searchTimer = ref<ReturnType<typeof setTimeout> | null>(null)

  // 搜索处理
  const handleSearch = (keyword: string) => {
    const searchText = keyword.trim()

    if (searchText.length < minLength) {
      uni.showToast({
        title: `请输入至少${minLength}个字符`,
        icon: 'none',
        duration: 1500,
      })
      return
    }

    // 添加到搜索历史
    addToHistory(searchText)

    // 执行搜索
    performSearch(searchText)
  }

  // 执行搜索
  const performSearch = async (keyword: string) => {
    isSearching.value = true

    try {
      // 这里可以调用搜索API
      console.log('执行搜索:', keyword)

      // 模拟搜索延迟
      await new Promise((resolve) => setTimeout(resolve, 500))

      // 搜索成功回调
      // uni.showToast({
      //   title: '搜索完成',
      //   icon: 'success',
      //   duration: 1000,
      // })
    } catch (error) {
      console.error('搜索失败:', error)
      uni.showToast({
        title: '搜索失败',
        icon: 'error',
        duration: 1500,
      })
    } finally {
      isSearching.value = false
    }
  }

  // 添加到搜索历史
  const addToHistory = (keyword: string) => {
    console.log('addToHistory', keyword)
    if (!keyword.trim()) return

    // 移除重复项
    const index = searchHistory.value.indexOf(keyword)
    if (index > -1) {
      searchHistory.value.splice(index, 1)
    }

    // 添加到开头
    searchHistory.value.unshift(keyword)

    // 限制历史记录数量
    if (searchHistory.value.length > maxHistoryCount) {
      searchHistory.value = searchHistory.value.slice(0, maxHistoryCount)
    }

    // 保存到本地存储
    saveSearchHistory()
  }

  // 清空搜索历史
  const clearSearchHistory = () => {
    searchHistory.value = []
    saveSearchHistory()
  }

  // 保存搜索历史到本地
  const saveSearchHistory = () => {
    try {
      uni.setStorageSync('searchHistory', searchHistory.value)
    } catch (error) {
      console.error('保存搜索历史失败:', error)
    }
  }

  // 从本地加载搜索历史
  const loadSearchHistory = () => {
    try {
      const history = uni.getStorageSync('searchHistory')
      if (history && Array.isArray(history)) {
        searchHistory.value = history
      }
    } catch (error) {
      console.error('加载搜索历史失败:', error)
    }
  }

  // 防抖搜索
  const debounceSearch = (callback: () => void) => {
    if (searchTimer.value) {
      clearTimeout(searchTimer.value)
    }

    searchTimer.value = setTimeout(() => {
      callback()
    }, debounceTime)
  }

  // 初始化时加载搜索历史
  loadSearchHistory()

  return {
    // 状态
    isSearching,
    searchHistory,

    // 方法
    handleSearch,
    performSearch,
    addToHistory,
    clearSearchHistory,
    debounceSearch,
    loadSearchHistory,
  }
}
