import { ref, computed, nextTick } from 'vue'

export interface RefreshLoadOptions {
  // 刷新成功提示
  showRefreshSuccess?: boolean
  // 加载失败提示
  showLoadError?: boolean
}

export function useRefreshLoad(options: RefreshLoadOptions = {}) {
  const { showRefreshSuccess = true, showLoadError = true } = options

  // 响应式状态
  const isRefreshing = ref(false)
  const isLoading = ref(false)
  const hasMore = ref(true)
  const currentPage = ref(1)

  // 下拉刷新处理
  const handleRefresh = async (refreshCallback?: () => Promise<void>) => {
    if (isRefreshing.value) return

    isRefreshing.value = true
    currentPage.value = 1
    hasMore.value = true

    try {
      if (refreshCallback) {
        await refreshCallback()
      }

      if (showRefreshSuccess) {
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500,
        })
      }
    } catch (error) {
      console.error('刷新失败:', error)
      if (showLoadError) {
        uni.showToast({
          title: '刷新失败',
          icon: 'error',
          duration: 1500,
        })
      }
    } finally {
      isRefreshing.value = false
      // 停止下拉刷新动画
      uni.stopPullDownRefresh()
    }
  }

  // 上拉加载处理
  const handleLoadMore = async (loadMoreCallback?: () => Promise<void>) => {
    if (isLoading.value || !hasMore.value) return

    isLoading.value = true
    currentPage.value++

    try {
      if (loadMoreCallback) {
        await loadMoreCallback()
      }
    } catch (error) {
      console.error('加载失败:', error)
      currentPage.value-- // 回退页码
      if (showLoadError) {
        uni.showToast({
          title: '加载失败',
          icon: 'error',
          duration: 1500,
        })
      }
    } finally {
      isLoading.value = false
    }
  }

  // 重置状态
  const resetState = () => {
    isRefreshing.value = false
    isLoading.value = false
    hasMore.value = true
    currentPage.value = 1
  }

  // 设置加载状态
  const setLoadingState = (loading: boolean) => {
    isLoading.value = loading
  }

  // 设置是否有更多数据
  const setHasMore = (hasMoreData: boolean) => {
    hasMore.value = hasMoreData
  }

  return {
    // 状态
    isRefreshing,
    isLoading,
    hasMore,
    currentPage,

    // 方法
    handleRefresh,
    handleLoadMore,
    resetState,
    setLoadingState,
    setHasMore,
  }
}
