import axios from "axios";
import { ElMessage } from "element-plus";
import windowConfig from "@/window";
import { useUserStore } from "@/stores/user.js";
import { useRouter } from "vue-router";
axios.interceptors.request.use(function (config) {
    const userStore = useUserStore();
    let token = userStore.authToken || sessionStorage.getItem("authToken") || "";
    if (token) {
        config.headers.Authorization = token;
    }
    return config;
}, (err) => {
    return Promise.reject(err);
});
axios.interceptors.response.use(response => {
    return response.data;
}, err => {
    if (err && err.response) {
        switch (err.response.status) {
        case 401:
            err.msg = "请先登录";
            break;
        }
    } else {
        err.msg = "网络连接错误";
    }
    return Promise.reject(err);
});

export function $get ({ url, params = {}, callback, error }) {
    const userStore = useUserStore();
    return axios({
        method: "get",
        url: windowConfig.baseUrl + url,
        params
    }).then(response => {
        callback && callback(response.data);
        return response;
    }).catch((err) => {
        console.log(err);
        error && error(err);
        ElMessage.error(err.msg || "操作失败");
        if (err && err.response && err.response.status === 401) {
            userStore.clearUserInfo();
            router.replace("/login");
        }
    });
};

export function $post ({ url, data = {}, callback, error }) {
    const router = useRouter();
    const userStore = useUserStore();
    return axios.post(windowConfig.baseUrl + url, data).then((response) => {
        if (response.code === 0) {
            callback && callback(response.data);
        } else {
            ElMessage.error(response.message);
        }
        return response;
    }).catch((err) => {
        console.log(err);
        error && error(err);
        ElMessage.error(err.msg || "操作失败");
        if (err && err.response && err.response.status === 401) {
            userStore.clearUserInfo();
            router.replace("/login");
        }
    });
};
