import axios from 'axios'

const service = axios.create(
    //     {
    //     baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    // }
)
import {
    Dialog
} from 'vant';
// request interceptor
service.interceptors.request.use(
    config => {
        // 根据requestBase判断切换不同域名 默认为VUE_APP_BASE_API
        if (config.requestBase == 'VUE_APP_ZL_WSS') {
            config.baseURL = process.env.VUE_APP_ZL_WSS;
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        }
        if (config.requestBase == 'VUE_APP_ZL_WSS_ZP') {
            config.baseURL = process.env.VUE_APP_ZL_WSS_ZP;
        }
        if (config.requestBase == 'VUE_APP_ZL_JF') {
            config.baseURL = process.env.VUE_APP_ZL_JF;
        }


        if (sessionStorage.getItem('x-token')) {
            config.headers['x-token'] = sessionStorage.getItem('x-token')
        }
        if (config.type === 'change') {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
        } else if (config.type === 'formData') {
            config.headers['Content-Type'] = 'multipart/form-data;charset=utf-8;'
        } else {
            config.headers['Content-Type'] = 'application/json'
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        console.log(response, 'response')
        const res = response.data
        const config = response.config
        if (config != null) {
            const blob = response.config.responseType
            if (blob == 'blob') {
                return res
            }
        }

        if (res.code === '0001') {
            Dialog({
                message: res.msg || 'Error'
            });
            return res
        }
        if (res.code == '200' || response.status == '200') {
            return res
        } else if (response.statusCode == '500' || response.statusCode == '403' || response.statusCode == '404') {
            Dialog({
                message: res.msg || 'Error'
            });
            return Promise.reject(new Error(res.message || 'Error'))
        }
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default service