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: 9,
        total: 0
    });

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

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

            const {data} = await api(params);

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

            console.log('我看看看', data);

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

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

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

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

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

export default useTableQuery;
