import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig} from "axios";
import {useQuasar} from "quasar";
export function getAxiosInstance(axiosRequestConfig: AxiosRequestConfig): AxiosInstance {
    let instance = axios.create(axiosRequestConfig);
    // 全局 请求拦截器
    instance.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
        let headers = config.headers || {}
        return config;
    })
    // 全局 响应拦截器
    instance.interceptors.response.use(successCB, rejectCB);
    return instance;
}


// 请求成功回调
export function successCB(response: AxiosResponse | Promise<AxiosResponse>): AxiosResponse | Promise<AxiosResponse> {
    function processResponse(response: AxiosResponse) {
        if (response.status === 200) { // 响应成功
            if (response.data.code === 401) {
                const $q = useQuasar()
                $q.notify({
                    position: "top",
                    color: 'negative',
                    message: "登录状态失效, 请重新登录",
                    icon: 'report_problem'
                })
                console.log(response,response.data.msg)
            } else if (response.data.code === 403) {
                setTimeout(() => {
                    console.log(response,response.data.msg)
                }, 0)
            }
            return response;
        } else {
            return Promise.reject(response);
        }
    }

    if (response instanceof Promise) {
        let resp: AxiosResponse
        return new Promise((resolve)=>{
            response.then((r: AxiosResponse) => {
                resp = r;
                resolve(processResponse(resp))
            });
        })
    } else {
        return processResponse(response);
    }
}

// 请求失败回调
export function rejectCB(error: any): any {
    let response = error.response
    if(response.status === 401){
        return response;
    } else if(response.status === 403){
        setTimeout(() => {
            console.log(response.data.msg)
        }, 0)
        return response;
    }
    return Promise.reject(error);
}
