import axios from "axios";
import { ElMessage } from "element-plus";
import router from "@/router/index.js";
import { useUserStore } from "../store/user";
import config from "@/config";

const request = axios.create({
    baseURL: config.api,
    timeout: 60000
})


// 请求拦截器
request.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么，例如添加token、修改请求头等
        const token = localStorage.getItem('Token');
        if (token) {
            config.headers['token'] = token;
        }

        return config;
    },
    error => {
        // 处理请求错误
        console.error(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    response => {
        // 对响应数据做些什么，例如解析数据、统一处理错误等
        if (response.data.code === -1 && (response.data.msg == '登录过期' || response.data.msg == '登录超时，请重新登录')) {
            ElMessage({
                message: response.data.msg,
                type: 'error',
            })
            setTimeout(() => {
                const userStore = useUserStore();
                userStore.setUserInfo({});
                userStore.setToken('');
                router.push('/login');
            }, 500)
            throw new Error(response.data.msg);
        }
        if (response.data.code === 400) {
            ElMessage({
                message: response.data.msg,
                type: 'error',
            })
            throw new Error(response.data.msg);
        }
        if (response.data.show) {
            ElMessage({
                message: response.data.msg,
                type: 'error',
            })
        }
        if (response.data.code === 500) {
            response.data.msg = JSON.parse(response.data.msg);
            ElMessage({
                message: response.data.msg?.msg || response.data.msg,
                type: 'error',
            })
            throw new Error(response.data.msg);
        }
        // console.log(response.data);
        if (response.data.code === 0) {
            return Promise.reject(response.data)
        }
        return response.data;
    },
    error => {
        // 处理响应错误
        console.error(error);
        ElMessage({
            message: error.response?.data?.msg || error,
            type: 'error',
        })
        return Promise.reject(error);
    }
);

export default request;