/*
 * @Author: micky
 * @Date: 2024-08-10 15:24:06
 * @LastEditors: micky
 * @LastEditTime: 2024-08-29 11:34:21
 * @FilePath: \chargingpile-uniapp\src\hooks\useZPaging.ts
 */
import { reactive, ref } from 'vue'

export function useZPaging(
    payload: any,
    requestApi: (params: any) => Promise<any>,
    callback?: Function
) {
    const paging = ref()
    const state = reactive({
        totalParam: {}
    })
    let api: (params: any) => Promise<any> = requestApi
    /**获取列表数据 => 特殊 */
    const cqueryList = async (args, config = {}, fetchApi?: (params: any) => Promise<any>) => {
        const [page_no, page_size] = args
        fetchData(page_no, page_size, config, fetchApi!)
    }
    /**获取列表数据 => 通用 */
    const queryList = async (page_no: number, page_size: number, config = {}) => {
        fetchData(page_no, page_size, config, api)
    }

    /** 改变api */
    const changeApi = (fetchApi: (params: any) => Promise<any>) => {
        api = fetchApi
    }
    /** 直接设置参数 */
    const setParams = (params: any) => {
        state.totalParam = params
    }

    /**更新参数 */
    const updateTotalParam = (params: any) => {
        let nowParam: Record<string, any> = {}
        for (const key in params) {
            nowParam[key] = params[key]
        }
        Object.assign(state.totalParam, nowParam)
    }
    /**刷新列表 */
    const refresh = (params?: any) => {
        updateTotalParam(params)
        paging.value.reload()
    }
    /**获取列表数据 */
    async function fetchData(
        page_no: number,
        page_size: number,
        config = {},
        api: (params: any) => Promise<any>
    ) {
        if (typeof api !== 'function') return
        try {
            uni.showLoading({
                title: '加载中...'
            })
            const params = {
                ...payload,
                ...state.totalParam,
                ...config,
                pageNo: page_no,
                pageSize: page_size
            }
            const res = await api(params)
            paging.value.complete(res.lists ?? res)
            callback && callback()
        } catch (e) {
            paging.value.complete(false)
        }
        uni.hideLoading()
    }
    return {
        paging,
        queryList,
        cqueryList,
        refresh,
        changeApi,
        setParams
    }
}
