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

/**
 *
 * @param parameter
 * @param api
 * @param callback
 * @param immediate
 * @param watchParameter
 */
function useTableQuery({
    parameter,
    api,
    callback,
    uuid = false,
    immediate = true,
    watchParameter = false,
}) {
    const loading = ref(false);
    const vo = reactive({
        rows: [],
        page: 0,
        total: 0,
    });

    const pagination = reactive({
        page: 1,
        pageSize: 9,
        total: 0
    });

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

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

            const { data } = await api(params);

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

            const _vo = {
                ...data,
                rows: data.list.map(v => ({ ...v, key: v.id })),
            };

            if (data.list.length === 0) {
                if (pagination.page > 1) pagination.page--;
            }

            Object.assign(vo, data);
            vo.page = _vo.page;
            vo.total = _vo.total;
            vo.rows = [...vo.rows, ..._vo.rows];
            if (uuid) {
                vo.rows = Array.from(
                    vo.rows.reduce((map, item) => {
                        map.set(item.id, item);
                        return map;
                    }, new Map()).values()
                )
            }

            callback && callback(vo);
        } finally {
            loading.value = false;
        }
    }

    const initFetchData = async () => {
        pagination.page = 1;
        pagination.total = 0;
        vo.page = 0;
        vo.total = 0;
        vo.rows.length = 0;
        await fetchData();
    }

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

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

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

export default useTableQuery;
