import axios from 'axios'

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

// import router from '@/router'
import Vue from 'vue'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_API,
    // baseURL: 'http://mk.sunplus.wang/WebAPI',
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 60000, // request timeout
    // responseType: 'json',
    // headers: {
    //   'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    // }
})

// request interceptor
service.interceptors.request.use(
    config => {
        if (localStorage.getItem('token')) {
            let TOKEN = localStorage.getItem('token')
            config.headers.Authorization = `${TOKEN}`

        }
        // config.headers['content-type'] = 'multipart/form-data'
        return config
    },
    error => {
        // do something with request error
        console.log(error, 'err') // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data

        // if the custom code is not 20000, it is judged as an error.
        if (res.code !== 0) {
            // if (res.code !== 200) {
            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

            Vue.prototype.$message({
                message: res.message,
                type: 'error'
            })


            return Promise.reject(new Error(res.message || 'Error'))
        } else {

            return res
        }
    },
    error => {
        if (error && error.message !== 'canceled')
        Vue.prototype.$message({
            message: error.message,
            type: 'error'
        })

        return Promise.reject(error)
    }
)

export default service