/**
 * Axios配置
 */

import axios from 'axios'
import { Message } from 'iview'
import { getStore } from '@/utils/utils'
import router from '@/router'
import store from '@/store/index'
/**
 * Axios基础设置
 */
axios.defaults.timeout = 150000
const service = ''
axios.defaults.withCredentials = true
axios.defaults.baseURL = service
/**
 * request请求拦截
 */
axios.interceptors.request.use(
    config => {
        let pinfo = config.params || config.data || false
        if (pinfo.no_needtoken) {
            delete pinfo.no_needtoken
            config.data = pinfo
        } else {
            let manager_access_token = getStore('userInfo').manager_access_token
            let obj = { manager_access_token }
            if (config.method === 'post') {
                let setParams = config.data
                Object.assign(obj, setParams)
                config.data = obj
            }
            if (config.method === 'get') {
                let setParams = config.params
                Object.assign(obj, setParams) 
                config.params = obj
            }
        }
        return config
    },
    // 当出现请求错误时做一些事
    err => {
        console.log('err' + err)
        Promise.reject(err)
    }
)
/**
 * respone拦截器
 */
axios.interceptors.response.use(
    res => {
        if (res.data.code ==403) {
            router.push({path:'/login',query:{isMessageInfo:true}})
            store.dispatch('logout')
            return false
        } else {
            return res.data
        }
    },
    err => {
        console.log('err => ', err)
        store.commit('changeloading',false)
        if (err.toString().indexOf('timeout') !== -1) {
            Message.info('请求超时')
        } else {
            Message.info('请求服务器失败')
        }
    }
)

export default axios