import type { ComputedRef } from 'vue'
import { computed, onMounted, ref, unref, watch, watchEffect } from 'vue'

interface TagOption {
  key: string
  label: string
}

export function useDataSource(propsRef: ComputedRef<any>, { optionData, getPagination }, emit) {
  const dataSourceRef = ref<Recordable[]>([])

  watchEffect(() => {
    optionData.value = unref(dataSourceRef)
  })

  watch(
    () => unref(propsRef).dataSource,
    () => {
      const { dataSource }: any = unref(propsRef)
      dataSource && (dataSourceRef.value = dataSource)
    },
    {
      immediate: true,
    },
  )

  const getDataSourceRef = computed(() => {
    const dataSource = unref(dataSourceRef)
    return dataSource
  })

  async function fetch(opt?) {
    try {
      const { request }: any = unref(propsRef)
      if (!request)
        return

      const pagination = getPagination.value

      const params = {
        ...opt,
        ...pagination,
      }

      const data = await request(params)

      const options: TagOption[] = data.map((item) => {
        return {
          key: item.value,
          label: item.label,
        }
      })

      dataSourceRef.value = options
      emit('fetch-success', {
        items: unref(options),
      })
    }
    catch (error) {
      emit('fetch-error', error)
      dataSourceRef.value = []
    }
  }

  onMounted(() => {
    setTimeout(() => {
      fetch()
    }, 16)
  })

  function setOptionData(values) {
    dataSourceRef.value = values
  }

  async function reload(opt?) {
    await fetch(opt)
  }

  return {
    reload,
  }
}
