import { ref } from 'vue'
import { getCurrentInstance } from 'vue'

function useList(url, beforeData = null, httpType) {
    const {
        appContext: {
            config: { globalProperties: global }
        }
    } = getCurrentInstance()

    const empty = ref(false)
    const loading = ref(false)
    const finished = ref(false)
    const page = ref(0)
    const totalElements = ref(0)
    const size = ref(20)
    const list = ref([])

    const getData = (isRefresh = false) => {
        if (isRefresh) {
            page.value = 0
            list.value = []
        }
        loading.value = true
        finished.value = false
        empty.value = false

        let data = { page: page.value, size: size.value, sort: 'createdAt,desc' }
        if (beforeData) {
            data = {
                ...data,
                ...beforeData()
            }
        }

        if (httpType === 'get') {
            return global.$http.get(url, data, { body: 'json' }).then(res => {
                if (res.first) {
                    list.value = []
                }
                list.value = [...list.value, ...res.content]
                empty.value = res.empty
                loading.value = false
                finished.value = res.last
                if (!finished.value) {
                    page.value = page.value + 1
                }
                totalElements.value = Number(res.totalElements)
            })
        } else {
            return global.$http.post(url, data, { body: 'json' }).then(res => {
                if (res.first) {
                    list.value = []
                }
                list.value = [...list.value, ...res.content]
                empty.value = res.empty
                loading.value = false
                finished.value = res.last
                if (!finished.value) {
                    page.value = page.value + 1
                }
                totalElements.value = Number(res.totalElements)
            })
        }
    }

    return {
        empty,
        loading,
        finished,
        page,
        totalElements,
        size,
        list,
        getData
    }
}

export default useList
