import axios from 'axios'

// 配置请求域名
axios.defaults.baseURL = 'http://192.168.0.10:8080/api'

axios.interceptors.request.use(function (config) {
  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  return config
}, function (error) {
  return Promise.reject(error)
})

axios.setToken = function (token) {
  if (!token) {
    token = sessionStorage.getItem('token')
  }
  if (token) {
    axios.defaults.headers.common['token'] = token
    sessionStorage.setItem('token', token)
  }
}
axios.setToken()

axios.removeToken = function (token) {
  delete axios.defaults.headers.common['token']
  sessionStorage.removeItem('token')
}

const notLogins = ['/sso/manager/login']

function setHandle (router) {
  axios.interceptors.request.use(function (config) {
    if ((!config.headers.token && !config.headers.common.token) && !~notLogins.indexOf(config.url)) {
      router.replace('login')
      return false
    } else {
      return config
    }
  }, function (error) {
    return Promise.reject(error)
  })

  // 配置response拦截器
  axios.interceptors.response.use(
    response => {
      let data = response.data
      let code = data.code

      switch (code) {
        case 3002:
          axios.removeToken()
          router.replace('login')
          break
        case 3004:
        case 3001:
          router.replace('login')
          break
      }
      return data
    },
    error => {
      if (error.response) {
        switch (error.response.status) {
          case 500:
            // Message({
            //   customClass: 'system-err',
            //   type: 'error',
            //   message: '服务器错误!'
            // })
            break
        }
      }
      return Promise.reject(error.response.data)
    }
  )
}

export { setHandle }
export default axios
