import axios, {AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig} from "axios";
import {message} from "ant-design-vue";
import {useUserStore} from "@/stores/modules/userStore.ts";
import router from "@/router";

export interface CustomAxiosRequestConfig extends AxiosRequestConfig {
    //是否需要全屏禁用
    loading?: boolean,
    loadingMessage?: string
}

export interface CustomInternalAxiosRequestConfig extends InternalAxiosRequestConfig {
    //是否需要全屏禁用
    loading?: boolean,
    loadingMessage?: string
}

const axiosConfig: AxiosRequestConfig = {
    baseURL: __APP_ENV.VITE_APP_BASE_API,
    timeout: __APP_ENV.VITE_APP_ENV === 'production' ? 10 * 1000 : 60 * 1000,
    timeoutErrorMessage: "请求超时......"
};

class RequestHttp {

    service: AxiosInstance;

    constructor(config: AxiosRequestConfig) {
        this.service = axios.create(config);

        this.service.interceptors.request.use((cfg: CustomInternalAxiosRequestConfig) => {
            const userStore = useUserStore()
            cfg.headers.set(userStore.getTokenInfo?.name as string, userStore.getTokenInfo?.value as string)
            return cfg;
        }, async (error) => {
            message.error(error.message)
            return Promise.reject(error);
        })

        this.service.interceptors.response.use(async (resp): Promise<any> => {
            const jsonResult: JsonResult<unknown> = resp.data;
            if (jsonResult && jsonResult.code != 200) {
                //一些特定的错误需要重新登录
                if ([-1].includes(jsonResult.code)) {
                    //清除登录信息
                    await useUserStore().resetUserInfo();
                    //跳转登录页
                    await router.push({
                        path: '/login'
                    })
                }
                message.error(jsonResult.message)
                return Promise.reject(jsonResult);
            }
            return Promise.resolve(jsonResult);
        }, (error) => {
            message.error(error.message)
            return Promise.reject(error);
        })
    }

    /**
     *  常用请求方法封装
     */
    get<T>(url: string, params?: object, _object: CustomAxiosRequestConfig = {}): Promise<JsonResult<T>> {
        return this.service.get(url, {params, ..._object});
    }

    post<T>(url: string, params?: object | object[], _object: CustomAxiosRequestConfig = {}): Promise<JsonResult<T>> {
        return this.service.post(url, params, _object);
    }

    put<T>(url: string, params?: object | object[], _object: CustomAxiosRequestConfig = {}): Promise<JsonResult<T>> {
        return this.service.put(url, params, _object);
    }

    delete<T>(url: string, params?: object, _object: CustomAxiosRequestConfig = {}): Promise<JsonResult<T>> {
        return this.service.delete(url, {params, ..._object});
    }

}

const api = new RequestHttp(axiosConfig);

export default api
