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 => {
        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 => {
        const res = response.data
        const config = response.config
        if (config != null) {
            const blob = response.config.responseType
            if (blob == 'blob') {
                return res
            }
        }
        console.log(res)
        if (res.code === '0001') {
            Dialog({
                message: res.message || 'Error'
            });
            return res
        }
        if (res.code !== '0000' || res.code !== '200') {
            Dialog({
                message: res.message || 'Error'
            });
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res
        }
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default service