import { ref } from 'vue'

import emitter from '@/utils/mitt'

export function listLoadAndRefresh(getData: any, type: string, scrollPage: any = {}) {
  const refreshing = ref(false)
  const finished = ref(false)
  const curPage = ref(1)
  const loading = ref(false)
  const list: any = ref([])
  const totalCount = ref(0)
  const firstFlag = ref(true)

  async function onLoad() {
    if (firstFlag.value) {
      emitter.emit('showLoading', '')
    }
    loading.value = true
    try {
      const data = await getData(curPage.value)
      totalCount.value = data.totalCount
      if (refreshing.value) {
        list.value = data.list
        refreshing.value = false
      } else {
        list.value = list.value.concat(data.list)
      }
      if (list.value.length >= data.totalCount) {
        finished.value = true
      } else {
        curPage.value++
      }
    } catch (error) {
      console.log(error)
    }
    if (type === 'internal' || type === 'report') {
      loading.value = false
      scrollPage()
    } else {
      loading.value = false
      if (firstFlag.value) {
        emitter.emit('hiddenLoading', '')
        firstFlag.value = false
      }
    }
  }

  function onRefresh() {
    // list.value = []
    refreshing.value = true
    finished.value = false
    curPage.value = 1
    onLoad()
  }
  return {
    refreshing,
    finished,
    loading,
    list,
    onLoad,
    onRefresh,
    curPage,
    totalCount
  }
}
