import { formatTime, getImageUrl } from '@/utils'
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app'
import { computed, onMounted, ref } from 'vue'

interface PaginationRequest {
  page?: number
  limit?: number
  [key: string]: any
}

function useListPageRequest(
  request: (params: PaginationRequest) => Promise<any>,
  options: {
    autoBind?: boolean
    autoRequest?: boolean
  } = {},
) {
  const { autoBind = true, autoRequest = true } = options
  const list = ref<any[]>([])
  // 加载中
  const loading = ref(false)
  // 加载更多中
  const moreLoading = ref(false)
  // 全部数据加载完成
  const totalPage = ref(0)
  const finished = computed(() => totalPage.value <= pagingParams.value.page)
  const pagingParams = ref<PaginationRequest>({
    page: 1,
    limit: 1000,
  })
  const getPagingParams = computed(() => {
    return {
      ...pagingParams.value,
    }
  })
  let customParams: PaginationRequest = {}

  const statusLoading = computed(() => {
    if (moreLoading.value || loading.value) {
      return 'loading'
    }
    if (finished.value) {
      return 'noMore'
    }
    return 'more'
  })

  const loadData = async () => {
    const { data } = await request({
      ...getPagingParams.value,
      ...customParams,
    })
    data.forEach((item: any) => {
      if (String(item.createtime).length < 11) {
        item.createtime = item.createtime * 1000
      }
      item.createtime = formatTime(item.createtime)
      item.image = getImageUrl(item.image)
    })
    // totalPage.value = data.count ? Math.ceil(data.count / pagingParams.value.limit!) : 0
    // 如果当前是第一页，则清空列表，否则追加数据
    if (getPagingParams.value.page === 1) {
      list.value = []
    }
    list.value.push(...data)
  }

  const onReload = async (params?: AnyObject) => {
    // 如果当前是第一页，则清空列表
    if (getPagingParams.value.page === 1) {
      list.value = []
    }
    loading.value = true
    pagingParams.value.page = 1
    if (params) {
      customParams = params
    }
    try {
      await loadData()
    } finally {
      loading.value = false
    }
  }
  const onMore = async () => {
    if (finished.value) {
      return
    }
    pagingParams.value.page = pagingParams.value.page! + 1
    moreLoading.value = true
    try {
      await loadData()
    } finally {
      moreLoading.value = false
    }
  }

  if (autoRequest) {
    onMounted(onReload)
  }
  if (autoBind) {
    onPullDownRefresh(async () => {
      await onReload()
      uni.stopPullDownRefresh()
    })
    onReachBottom(onMore)
  }

  return {
    list,
    loading,
    moreLoading,
    finished,
    statusLoading,
    totalPage,

    onReload,
    onMore,
  }
}

export { useListPageRequest }
