import axios from 'axios';
import {message as msg} from "ant-design-vue";

// 创建 Axios 实例
const service = axios.create({
    baseURL: '/api/', // 这里可以设置你的 API 基础地址
    timeout: 5000 // 请求超时时间
});

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 从本地存储中获取 token
        const token = localStorage.getItem('token');
        if (token) {
            // 设置请求头中的 Authorization
            config.headers['Authorization'] = `Bearer ${token}`;
        }
        return config;
    },
    error => {
        console.log(error); // 打印错误信息
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    response => {
        const {code, result, message} = response.data;
        if (code === 0) {
            return result;
        } else {
            if (code === 401) {
                msg.error(message).then(r => {
                    localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    window.location.href = '/'
                    msg.destroy()
                })
                return;
            }
            msg.error(message).then(r => {
                msg.destroy()
            })
        }
    },
    error => {
        console.log('err' + error); // 打印错误信息
        return Promise.reject(error);
    }
);

// 封装 get 请求
const get = (url, params = {}) => {
    return service.get(url, { params });
};

// 封装 post 请求
const post = (url, data = {}) => {
    return service.post(url, data);
};

// 封装上传文件请求
const upload = (url, file) => {
    const formData = new FormData();
    formData.append('file', file);
    return service.post(url, formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    });
};

export { get, post, upload };