import { reactive, onMounted } from 'vue';
/**
 * 查询列表的公用方法
 * @param initList 初始化列表
 * @param reset 重置
 * @param listParm 列表查询的参数
 * @param init 是否加载初始数据
 * 
 * @returns sizeChange 页容量改变事件
 * @returns currentChange 页数改变事件
 * @returns searchBtn 搜索事件
 * @returns resetBtn 重置事件
 */
function useQueryList<T extends Recordable>(initList: Fn, reset: Fn, listParm: Recordable, init = true) {
    //接收列表查询的参数
    const listParams = reactive({} as T)

    //页容量改变时触发
    const sizeChange = (size: number) => {
        listParm.pageSize = size;
        Object.assign(listParams, { pageSize: size })
        initList();
    }
    //页数改变时触发
    const currentChange = (page: number) => {
        if (!listParm.total) return
        listParm.pageNum = page;
        Object.assign(listParams, { pageNum: page })
        initList();
    }
    //搜索
    const searchBtn = () => {
        listParm.pageNum = 1;
        Object.assign(listParams, listParm)
        initList();
    }
    //重置
    const resetBtn = () => {
        reset()
        listParm.pageNum = 1;
        listParm.pageSize = 10;
        Object.assign(listParams, listParm)
        initList();
    }

    // 初始化列表数据
    onMounted(() => {
        Object.assign(listParams, listParm)
        if (init) initList();
    })

    return {
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        listParams
    }
}

export { useQueryList }