import { Message } from 'element-ui'

import { auth } from '@/utils/auth'

const axios = require('axios')
const CancelToken = axios.CancelToken
const source = CancelToken.source()
const request = axios.create({
    baseURL: process.env.VUE_APP_API,
    timeout: 600000
})

function checkResponse(res) {
    if (res) {
        if (res.message && res.message.length > 0) {
            Message.error(res.message)
            if (res.code == 403) {
                source.cancel('Operation canceled.')
                auth.logout()
                location.reload()
            }
        }
        else if (res.error) {
            Message.error(res.error)
        }
    }
}

request.interceptors.request.use(config => {
    config.headers['Accept'] = '*'
    let tgTicket = auth.getToken()
    if (tgTicket){
        config.headers['token'] = tgTicket;
    }
    return config
}, error => {
    return Promise.reject(error)
})

request.interceptors.response.use((response) => {
    const res = response.data;
    checkResponse(res)
    return res
},  (error) => {
    if (error.response) {
        checkResponse(error.response.data)
    }
    return Promise.reject(error)
});

export default request
