import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from "axios";
//endLoading
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
import { usePathUrl } from "@/hooks/usePathUrl";
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";
import { useMsg } from "@/hooks/useMsg";

const getUcOffline = () => {
    const userStore = useUserStore();
    let httpUrl = import.meta.env.VITE_SINGLE_URL + "uc/offline";
    fetch(httpUrl, {
        method: "POST",
        credentials: "include",
        keepalive: true,
        headers: {
            Authorization: userStore.phpToken,
            "Refresh-Authorization": userStore.refreshToken
        }
    })
        .then((res: any) => {
            if (res.status === 200) {
                useMsg("success", "退出登录成功 ！");
                setTimeout(() => {
                    console.log("在这里来了");
                    location.href = usePathUrl();
                    // 2.重置用户数据
                    userStore.$reset();
                    // 3.清除 本地
                    localStorage.clear();
                }, 800);
            }
        })
        .catch(() => {
            location.href = usePathUrl();
            // 2.重置用户数据
            userStore.$reset();
            // 3.清除 本地
            localStorage.clear();
            useMsg("error", "退出登录失败,请稍后再试 ！");
        });
};
const getUcOnline = (phpToken: any, refreshToken: any) => {
    let httpUrl = import.meta.env.VITE_SINGLE_URL + "uc/online";
    fetch(httpUrl, {
        method: "POST",
        credentials: "include",
        keepalive: true,
        headers: {
            Authorization: phpToken,
            "Refresh-Authorization": refreshToken
        }
    });
};
//登出地址
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
    noLoading?: boolean;
}

//计步器
// let setUp: number = 0;
const config = {
    // 默认地址请求地址，可在 .env.** 文件中修改
    baseURL: (import.meta.env.VITE_APP_API_BASEURL + import.meta.env.VITE_APP_API_VERSION) 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.newUserToken);
                    config.headers.set("Refresh-Authorization", userStore.refreshToken);
                }
                getUcOnline(userStore.phpToken, userStore.refreshToken);
                return config;
            },
            (error: AxiosError) => {
                return Promise.reject(error);
            }
        );

        /**
         * @description 响应拦截器
         *  服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
         */
        this.service.interceptors.response.use(
            (response: AxiosResponse) => {
                const { data } = response;
                // const userStore = useUserStore();
                tryHideFullScreenLoading();
                // 登陆失效
                if (data.status == 401) {
                    ElMessage.error(data.msg || data.message);
                    // getUcOffline();
                    location.href = usePathUrl();
                    return Promise.reject(data);
                }
                let statusStr = data.status + "";
                const STATUS_STRS = [
                    "600006",
                    "600002",
                    "600003",
                    "600001",
                    "600004",
                    "600005",
                    "3433535",
                    "40005"
                    // "70003",
                    // "70001"
                ];
                //单数70005
                const STATUS_STRS1 = ["70005", "70004", "70003"];
                if (statusStr.length > 3 && STATUS_STRS1.includes(statusStr)) {
                    console.log("走到了这里");
                    return data;
                    // return Promise.reject(data);
                }
                if (statusStr.length > 3 && !STATUS_STRS.includes(statusStr)) {
                    console.log("32121");
                    ElMessage.error(data.msg || data.message);
                    return Promise.reject(data);
                }
                if (data.status === 504) {
                    ElMessage.error("请求超时！请您稍后重试");
                }
                // 全局错误信息拦截（防止下载文件的时候返回数据流，没有 code 直接报错）
                if (data.code && data.code !== ResultEnum.SUCCESS) {
                    ElMessage.error(data.msg);
                    return Promise.reject(data);
                }
                //当是200但是msg不是Success弹出错误信息
                if (data.status === 200 && data.message !== "Success") {
                    ElMessage.error(data.message);
                }

                // 成功请求（在页面上除非特殊情况，否则不用处理失败逻辑）
                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) {
                    checkStatus(response.status);
                    if (response.status === 401) {
                        location.href = usePathUrl();
                        getUcOffline();
                    }
                }
                // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
                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>> {
        return this.service.put(url, params, _object);
    }
    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);
