import { App } from 'antd'
import { useState } from 'react'
export interface AjaxPromise {
    /**请求*/
    run: (params?: any) => Promise<any>,
    /**执行上次的请求*/
    refresh: () => Promise<any>,
    /** 修改data */
    mutate: (data: any) => void
    /**清空data*/
    initData: () => void,
    /**loding状态*/
    loading: boolean,
    /**data数据*/
    data: any,
}
/**
 * ajax封装方法 hook 方法不要使用在非页面中
 * @returns run 请求操作
 * @returns refresh 执行上次请求
 * @returns loading 请求状态
 * @returns data 请求结果数据
 * @returns initData 初始data
 * */
export function useAjax(fnc: (params?: any) => Promise<any>): AjaxPromise {
    const {message}= App.useApp()
    const [loading, setLoding] = useState(false)//状态
    const [data, setData] = useState<any>()//数据
    const [oldParams, setOldParasm] = useState()
    async function run(params?: any) {//请求
        setLoding(() => true)//开启加载
        setOldParasm(() => params)//存放本次请求参数
        return fnc(params).then(res => {//开启请求
            setLoding(() => false)//关闭请求加载
            setData(() => res)//设置data
            if (res?.code === 500) {
                message.error(res?.msg)
                return undefined
            }
            return res//返回data
        }).catch(err=>{
            console.log(err)
            setLoding(() => false)//关闭请求加载
        })
    }
    async function refresh() {//上次的请求
        setLoding(() => true)//开启加载
        return fnc(oldParams).then(res => {//开启请求
            setLoding(() => false)//关闭请求加载
            setData(() => res)//设置data
            return res//返回data
        })
    }
    async function initData() {
        setData(null)
    }
    // 修改保存数据
    async function mutate(data: any) {
        setData(data)
    }
    return { loading, data, run, refresh, initData, mutate }
}
