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(1)
    const totalElements = ref(0)
    const size = ref(20)
    const list = ref([])

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

        let data = { page: page.value }
        if (beforeData) {
            data = {
                ...data,
                ...beforeData()
            }
        }

        if (httpType === 'get') {
            return global.$http
                .get(url, data, { body: 'json' })
                .then(res => {
                    if (res.current_page === 1) {
                        list.value = []
                    }
                    list.value = [...list.value, ...res.data]
                    empty.value = res.meta.total == 0
                    finished.value = res.meta.current_page === res.meta.last_page
                    if (!finished.value) {
                        page.value = page.value + 1
                    }
                    totalElements.value = Number(res.meta.total)
                    loading.value = false
                })
                .catch(e => {
                    console.log(e)
                })
        } else {
            return global.$http
                .post(url, data, { body: 'json' })
                .then(res => {
                    if (res.current_page === 1) {
                        list.value = []
                    }
                    list.value = [...list.value, ...res.data]
                    empty.value = res.meta.total == 0
                    finished.value = res.meta.current_page === res.meta.last_page
                    if (!finished.value) {
                        page.value = page.value + 1
                    }
                    totalElements.value = Number(res.meta.total)
                    loading.value = false
                })
                .catch(e => {
                    console.log(e)
                })
        }
    }

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

export default useList
