import axios from 'axios'
import Vue from 'vue'
import store from '_platform/store'
import {
    cacheStorage
} from '@/utils'

axios.defaults.timeout = 200000
axios.defaults.withCredentials = true
// axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
if (document.location.protocol === 'http:') {
    axios.defaults.baseURL = process.env.VUE_APP_BASE_URL
} else {
    axios.defaults.baseURL = process.env.VUE_APP_BASE_URL_S
}
axios.interceptors.request.use(function(config) {
    config.headers.clientType = 4
    if (store.state) {
        let token = store.state.token
        if (token) {
            config.headers.token = token
        }
    }
    let userInfo = cacheStorage.getItem('user')

    if (userInfo) {
        userInfo = JSON.parse(userInfo)
        config.headers.userId = userInfo.id
    }
    return config
}, function(error) {
    return Promise.reject(error)
})
// 添加响应拦截器
axios.interceptors.response.use(function(response) {
    let data = response.data || response
    const {
        verifycodesession,
        token
    } = response.headers
    if (token) {
        store.dispatch('setToken', token)
    }
    if (response.data.code === 10001 || response.data.code === 20103) {
        cacheStorage.clear()
        Vue.prototype.$Notice.error({
            title: '登录信息过期，请重新登录',
            desc: response.data.message
        })
        window.location.href = location.href.split('?')[0]
        window.location.reload()
    }
    // 登录验证码 10001
    if (verifycodesession) {
        cacheStorage.setItem(process.env.VUE_APP_VERIFY_CODE_KEY, verifycodesession)
    }
    return Promise.resolve(data)
}, function(error) {
    // 如果存在 error.response 为后台错误，在不同的状态码做不同的操作
    // 否则为网络错误 todo
    if (error.response) {
        /*if (process.env.NODE_ENV === 'development') {
            const {
                response
            } = error
            Vue.prototype.$Notice.error({
                title: response.status,
                desc: response.data.message
            })
        }*/
        // 2021-03-13 优化，提示后台错误，例如参数错误等信息
        const { response } = error
        Vue.prototype.$Notice.warning({
            title: response.data.msg,
            desc: response.data.msg
        })
    } else {
        console.log(error, 'error')
    }
    return Promise.reject(error)
})

Vue.prototype.$http = axios
export default axios
