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.url,
    timeout: 10000
})


// 请求拦截器
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.status === 401 || response.data.status === 40000) {   
            ElMessage({
                message: response.data.message,
                type: 'error',
            })
            setTimeout(()=>{
                const userStore = useUserStore();
                userStore.setUserInfo({});
                userStore.setToken('');
                router.push('/login');
            },700)
        }
        if (response.data.status === 400) {   
            ElMessage({
                message: response.data.message,
                type: 'error',
            })
            throw new Error(response.data.message);
        }
        return response.data;
    },
    error => {
        // 处理响应错误
        console.error(error);
        ElMessage({
            message: error.response?.data?.message || error, 
            type: 'error',
        })
        return Promise.reject(error);
    }
);

export default request;