import {reactive, ref, watch} from 'vue';

/**
 *
 * @param parameter
 * @param api
 * @param callback
 * @param immediate
 * @param watchParameter
 */
function useTableQuery({
                           parameter,
                           api,
                           callback,
                           immediate = true,
                           watchParameter = false,
                       }) {
    const loading = ref(false);

    const pagination = reactive({
        current: 1,
        pageSize: 20,
        total: 0
    });

    const fetchData = async () => {
        try {
            loading.value = true;

            const params = {
                ...parameter,
                current: pagination.current,
                pageSize: pagination.pageSize
            }

            const {data} = await api(params);

            pagination.pageSize = data.page;
            pagination.total = data.total;

            callback && callback({
                ...data,
                rows: data.rows.map(v => ({...v, key: v.id})),
                current: pagination.current
            });
        } finally {
            loading.value = false;
        }
    }

    const initFetchData = async () => {
        if (pagination.current === 1) {
            fetchData().then();
        } else {
            pagination.current = 1;
            pagination.total = 0;
        }
    }

    watch(
        () => [pagination.current, pagination.pageSize],
        () => fetchData(),
        {deep: true, immediate: immediate}
    )

    if (watchParameter) watch(
        () => parameter,
        () => initFetchData(),
        {deep: true}
    );

    return {
        loading,
        pagination,
        fetchData,
        initFetchData,
    }
}

export default useTableQuery;
