import axios from "axios";
import route from "@/router";
import store from "@/store";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { nextTick } from "vue";
import config from "./config";
import JSONBIG from "json-bigint";
import { getCookie } from "@/utils/auth"; // getToken from cookie
import { baseURL } from "./apiConfig"
// 配置新建一个 axios 实例
var loading = null;
const service = axios.create({
    // baseURL: "/sharding/",
    baseURL,
    timeout: 20000,
    headers: { "Content-Type": "application/json" },
    showLoading: {
        statu: true,
        text: "加载中...",
    },
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        if (config.showLoading.statu) {
            loading = ElLoading.service({
                lock: true,
                text: config.showLoading.text,
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.3)",
            });
        }
        const u = (config.headers || {}).isUser;
        // 在发送请求之前做些什么 token
        let token = getCookie("accessToken");
        let userId = getCookie("userId");
        if (token) {
            if (u) {
                config.headers["Authorization"] = "Bearer " + token;
            } else {
                config.headers.common["token"] = token;
                config.headers.common["userId"] = userId;
            }
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        // 对响应数据做点什么
        nextTick(async () => {
            loading && (await loading.close());
        });
        const res = response.data;
        if (res.code === 401) {
            ElMessageBox.alert(
                "登录状态已过期，您可以继续留在该页面，或者重新登录",
                "系统提示", {
                confirmButtonText: "重新登录",
                cancelButtonText: "取消",
                type: "warning",
                callback: () => {
                    store.dispatch("user/LogOut").then(() => {
                        route.push("/");
                    });
                },
            }
            );
        } else {
            return response.data;
        }
    },
    (error) => {
        nextTick(async () => {
            loading && (await loading.close());
        });
        // 对响应错误做点什么
        if (error.message.indexOf("timeout") != -1) {
            // ElMessage.error('网络超时');
        } else if (error.message == "Network Error") {
            // ElMessage.error('网络连接错误');
        } else {
            // if (error.response.data) ElMessage.error(error.response.statusText);
            // else ElMessage.error('接口路径找不到');
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;