import axios from "axios"
import { getConfig } from "@/config/config"
import { getToken } from "@/utils/auth"
import CryptoJS from "crypto-js"
import { useUserStore } from "@/store/user.js"
// 创建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 => {
        console.log(error)
        return Promise.reject(error)
    }
)
// 响应拦截器
request.interceptors.response.use(
    response => {
        const code = response.data.code || 200
        if (code == 200) {
            return response.data
        } else {
            ElMessage({ message: response.data.msg || response.data.error_description || "异常，请联系管理员", type: "error", duration: 5 * 1000 })
            return Promise.reject("error")
        }

    }, error => {
        let { message, response } = error

        if (error.response.data.code == 401 || error.response.status == 401) {
            ElMessageBox.confirm("登录状态已过期，请重新登录", "系统提示", { confirmButtonText: "重新登录", cancelButtonText: "取消", type: "warning" }).then(() => {
                useUserStore().logOut().then(() => {
                    location.href = "/index"
                })
            })
        } else {
            if (message == "Network Error") {
                message = "后端接口连接异常"
            } else if (message.includes("timeout")) {
                message = "系统接口请求超时"
            } else if (message.includes("Request failed with status code")) {
                message = "系统接口" + message.substr(message.length - 3) + "异常" + response.data.msg
            }
            if (process.env.NODE_ENV != "production") {
                message = message + "==>" + response.config.url
            }
            ElMessage({ message: message || "异常，请联系管理员", type: "error", duration: 5 * 1000 })
        }
        return Promise.reject(error)
    }
)
export default request