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


export const service = axios.create({
    baseURL: window.g.BASE_API,
    // withCredentials: true, // 跨域请求时发送 cookies
    timeout: 10000

})




// 请求拦截器
service.interceptors.request.use(
    config => {
        // const token = session.get('Token');
        // token && (config.headers.Authorization = token);
        if (config.method.toUpperCase() === "POST") {
            config.headers['Content-Type'] = 'application/json;charset=utf-8';
        }
        return config
    },
    error => {
        return Promise.error(error)
    }
)
// 响应请求拦截器

service.interceptors.response.use(
    response => {
        // console.log("response", response)
        if (response.status === 200) {
            return Promise.resolve(response.data)
        } else {
            return Promise.reject(response)
        }
    },
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                case 500:
                    console.error("网络错误，请稍后再试");
                    break;
                case 404:
                    console.error("请求路径出错");
                    break;

                default:
                    console.error(error.response.data.console)
            }
            return Promise.reject(error.response)
        }
    }
)



export function get(url, params) {
    return new Promise((resolve, reject) => {
        service.get(url, {
            params
        }).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}

export function post(url, params) {
    return new Promise((resolve, reject) => {
        service.post(url,
            params
        ).then(res => {
            resolve(res)
        }).catch(err => {
            reject(err)
        })
    })
}