import axios from "axios";
import { getConfig } from "@/config/config";
import { getToken } from "@/utils/auth";
import CryptoJS from "crypto-js";
import { useUserStore } from "@/store/user";
// 创建axios实例
const request = axios.create({
    baseURL: getConfig("baseUrl"),
    timeout: 60000
})

request.interceptors.request.use(
    config => {
        if (getToken()) config.headers["qdport-Auth"] = "bearer " + getToken();
        config.headers["Authorization"] = `Basic ${CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(`${getConfig("clientId")}:${getConfig("clientSecret")}`))}`;
        return config;
    }, error => {
        return Promise.reject(error);
    }
)
// 响应拦截器
request.interceptors.response.use(
    response => {
        const code = response.data.code || response.data.error_code || 200
        if (code == 200) return response.data;
        else {
            if (response.data.error_code == 401) useUserStore().logOut().then(() => location.href = "/");
            else ElMessage({ message: response.data.msg || response.data.error_description || "异常，请联系管理员", type: "error", duration: 5 * 1000 })

            return Promise.reject(response.data);
        }

    }, error => {
        if (error.response) {
            if (error.response.data.code == 401 || error.response.status == 401) {
                ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", {
                    type: "warning",
                    showClose: false,
                    closeOnPressEscape: false,
                    closeOnClickModal: false,
                    confirmButtonText: "重新登录",
                    cancelButtonText: "取消"
                }).then(() => useUserStore().logOut().then(() => location.href = "/"));
            } else {
                const message = error.response.data.msg || error.response.data || "异常，请联系管理员";
                ElMessage.error({ message: `Status:${error.response.status}，${message}`, duration: 5 * 1000 });
            }
        } else ElMessage.error({ message: "系统接口请求超时", duration: 5 * 1000 });

        return Promise.reject(error.response || error);
    }
)
export default request