import axios from "axios";
import { ElMessage } from "element-plus";

const request = axios.create({
    baseURL: 'https://shop.lihaink.cn/api',
    timeout: 5000
})

function convertParamsToQueryString (params) {
    const queryString = Object.keys(params)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&');
    return queryString;
}

// 请求拦截器
request.interceptors.request.use(
    config => {
        config.Token = localStorage.getItem('token')||null;
        return config;
    },
    error => {
        // 处理请求错误
        console.error(error);
        return Promise.reject(error);
    }
);

// 响应拦截器
request.interceptors.response.use(
    response => {
        if(response.data.status!==200){
            ElMessage.error(response.data.message);
            return Promise.reject(response.data);
        }
        // 对响应数据做些什么，例如解析数据、统一处理错误等
        return Promise.resolve(response.data);
    },
    error => {
        // 处理响应错误
        console.error(error);
        return Promise.reject(error);
    }
);

export default request;