import Vue from 'vue'
import qs from 'qs'
import axios from 'axios'
import Layer from '@/plugins/Layer/index'
const Cookie = process.client ? require('js-cookie') : undefined;

const service = axios.create({
    timeout: 1000 * 10,
    withCredentials: false,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-Ca-Stage': process.env.X_CA_STAGE,
    }
})
// request拦截器
service.interceptors.request.use(config => {
    if(process.client){
        config.headers['token'] = Cookie.get('token') || '';
    }
    return config
}, error => {
    return Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(res => {
    if(res.data.code !== 200 || res.data.errorCode !== 0){
        if(res.data.errorMessage){
            if(process.client){
                Layer.msg(res.data.errorMessage)
            }
        }
    }
    return res.data;
}, err => {
    console.log(err)
    return {
        code: 500,
        errorCode: 500,
        errorMessage: '网络错误'
    }
})

const selectPath = (type) => {
    if(type == 'API_RED'){
        return 'https://red.guangdianyun.tv';
    }else{
        return 'https://apiliveroom.dev.guangdianyun.tv/v1';
    }
}
const get = (url, params, type) => {
    let nUrl = `${selectPath(type)}${url}`
    let config = {
        method: 'get',
        url: nUrl,
        params: params
    };
    return service(config)
};
const post = (url, data, type) => {
    let nUrl = `${selectPath(type)}${url}`
    let config = {
        method: 'post',
        url: nUrl,
        data: qs.stringify(data)
    };
    return service(config)
};

export default {
    get,
    post,
    service,
}