import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
import qs from "qs";
//endLoading
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";

import { ElMessage } from "element-plus";
import { ResultData } from "@/api/interface";
import { ResultEnum } from "@/enums/httpEnum";
// import { checkStatus } from "./helper/checkStatus";
import { useUserStore } from "@/stores/modules/user";
import router from "@/routers";
//获取导出表格name
const getDispositionName = (response: any) => {
    //导出表格,从content-disposition获取表格的名称 只有导出服务端才会返回该字段
    const contentDisposition = response.headers["content-disposition"];
    if (contentDisposition) {
        let contentDispositionClone = decodeURIComponent(contentDisposition);
        console.log(contentDispositionClone);
        // 解析 Content-Disposition 以提取文件名
        const filenameMatch = contentDispositionClone.match(/filename=(.*)/i);
        if (filenameMatch && filenameMatch[1]) {
            let filename = filenameMatch[1].trim();
            localStorage.setItem("filename", filename);
        }
    }
};

//登出地址
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
    noLoading?: boolean;
}

const config = {
    // 默认地址请求地址，可在 .env.** 文件中修改
    baseURL: import.meta.env.VITE_APP_API_BASEURL as string,
    // 设置超时时间
    timeout: ResultEnum.TIMEOUT as number,
    // 跨域时候允许携带凭证
    withCredentials: true
};

class RequestHttp {
    service: AxiosInstance;
    public constructor(config: AxiosRequestConfig) {
        // instantiation
        this.service = axios.create(config);

        /**
         * @description 请求拦截器
         * 客户端发送请求 -> [请求拦截器] -> 服务器
         * token校验(JWT) : 接受服务器返回的 token,存储到 vuex/pinia/本地储存当中
         */
        this.service.interceptors.request.use(
            (config: CustomAxiosRequestConfig) => {
                const userStore = useUserStore();
                // 当前请求不需要显示 loading，在 api 服务中通过指定的第三个参数: { noLoading: true } 来控制
                config.noLoading || showFullScreenLoading();
                if (config.headers && typeof config.headers.set === "function") {
                    config.headers.set("Authorization", userStore.token);
                }
                return config;
            },
            (error: AxiosError) => {
                return Promise.reject(error);
            }
        );

        /**
         * @description 响应拦截器
         *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
         */
        this.service.interceptors.response.use(
            (response: AxiosResponse) => {
                const { data, request } = response;

                tryHideFullScreenLoading();
                const imgId = request?.responseURL?.split("imgId=")[1];
                //获取导出表格名称
                getDispositionName(response);
                // 获取响应头中的 Authorization 信息
                const authorization = response.headers["authorization"];
                if (imgId) {
                    return {
                        imgId,
                        data
                    };
                }
                if (authorization) {
                    // 可以在这里更新用户的 token 信息
                    const userStore = useUserStore();
                    userStore.setToken(authorization);
                    return data;
                }

                //0正常,1非正常
                if (data.code == 1) {
                    ElMessage.error(data.msg);
                }
                //请求超时
                if (data.code == 504) {
                    ElMessage.error("请求超时！请您稍后重试");
                }
                // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
                return data;
            },
            //请求错误
            async (error: AxiosError) => {
                const { response } = error;
                tryHideFullScreenLoading();
                // 请求超时 && 网络错误单独判断，没有 response
                if (error.message.indexOf("timeout") !== -1) ElMessage.error("请求超时！请您稍后重试");
                if (error.message.indexOf("Network Error") !== -1) ElMessage.error("网络错误！请您稍后重试");
                // 根据服务器响应的错误状态码，做不同的处理
                if (response) {
                    console.log("error-走到了这里", response.status);
                    // checkStatus(response.status, response.data);
                }
                // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
                if (!window.navigator.onLine) router.replace("/500");
                return Promise.reject(error);
            }
        );
    }

    /**
     * @description 常用请求方法封装
     */
    get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
        return this.service.get(url, { params, ..._object });
    }
    post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
        return this.service.post(url, params, _object);
    }
    put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
        // console.log(JSON.stringify(params), "=qs.stringify(params)=");
        return this.service.put(url, qs.stringify(params), {
            ..._object,
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }
        });
    }
    delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
        return this.service.delete(url, { params, ..._object });
    }
    download(url: string, params?: object, _object = {}): Promise<BlobPart> {
        return this.service.post(url, params, { ..._object, responseType: "blob" });
    }
}

export default new RequestHttp(config);
