type OptionsType<T> = {
    apiFn: (payload: any) => Promise<T[] | any> // 请求api
    onSuccess?: (response: T[] | any) => void // 接口调用成功的回调函数
    onError?: (err: any) => void // 接口调用失败的回调函数
}
type StateType<T> = {
    loading: boolean // loading
    data: T[] // 返回结果
}

/**
 * 获取异步请求数据
 */
export function useFetchData<T>(options: OptionsType<T>) {
    const { apiFn, onSuccess, onError } = options

    const state: StateType<T> = reactive({
        loading: false,
        data: []
    })

    const loadData = async () => {
        state.loading = true
        try {
            const result = await apiFn()
            state.data = result
            onSuccess && onSuccess(result)
        } catch (error) {
            onError && onError(error)
        } finally {
            state.loading = false
        }
    }

    onMounted(loadData)

    return {
        ...toRefs(state),
        loadData
    }
}

/**
 * loading
 */
export function useRequest<T>(options: OptionsType<T>) {
    const { apiFn, onSuccess, onError } = options

    const loading = ref(false)

    const runFn = async (...args: any[]) => {
        loading.value = true
        try {
            const result = await apiFn(...args)
            onSuccess && onSuccess(result)
        } catch (error) {
            onError && onError(error)
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        runFn
    }
}
