import { inject, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { getProduct } from '../api'
import emitter from '/@/utils/emitter'

export default function useInfiniteScroll() {
  const profile = <any>inject('profile')
  const parentloading = ref(false)

  const productSelect = ref('')
  emitter.on('ExchangeProduct-productSelect', (value: any) => {
    productSelect.value = value
  })

  const searchInp = ref('')
  emitter.on('ExchangeProduct-searchInp', (value: any) => {
    searchInp.value = value
  })

  const allData = ref([])
  let currentPage = ref(1)
  let total = 0
  let limit = 10


  function load() {
    if (currentPage.value * limit < total) {
      currentPage.value++
      fetchProduct()
    }
  }

  async function fetchProduct() {
    parentloading.value = true
    const query = {
      profileId: profile.value.profile_id,
      productlineId: productSelect.value,
      page: currentPage.value,
      limit: limit,
      searchItem: searchInp.value,
    }
    try {
      const res = await getProduct(query)
      if (res && res.data) {
        const newData = res.data
        if (currentPage.value > 1) {
          allData.value.push(...newData)
        } else {
          allData.value = newData
        }
        total = res.total
      }
    } catch (error) {
      console.log('error:', error)
    } finally {
      parentloading.value = false
      emitter.emit('ExchangeProduct-allData', allData)
    }
  }

  onMounted(() => {
    fetchProduct()
  })

  onBeforeUnmount(() => {
    emitter.all.clear()
  })

  return { allData, parentloading, currentPage, load, fetchProduct }
}
