import axios from 'axios'
import Vue from 'vue'
import router from '../router'

var isProduction = process.env.NODE_ENV === 'production'
const vue = new Vue()
let loading = ''

// 配置请求域名

const serverName = isProduction ? '/zhoushan' : 'http://192.168.0.245:8001/zhoushan'
// http://119.23.129.199:8100/
const exceptUrls = ['/login']

axios.defaults.baseURL = serverName
axios.defaults.headers['X-Requested-with'] = 'XMLHttpRequest'

axios.interceptors.request.use(function (config) {
  for (let i = 0; i < exceptUrls.length; i++) {
    let url = exceptUrls[i]
    if (config.url.indexOf(url) > -1) {
      config.baseURL = serverName.replace('/zhoushan', '')
    }
  }
  config.headers['token'] = window.localStorage.getItem('token')
  loading = vue.$loading({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 配置response拦截器
axios.interceptors.response.use(

  response => {
    loading.close()
    let data = response.data
    let code = Number(response.data.code)

    switch (code) {
      case -1:
        break
      case 102:
        break
      case 5001:
        if (window.localStorage.getItem('token')) {
          window.localStorage.setItem('token', '')
          vue.$alert('登录状态失效，请重新登录', '提示', {
            confirmButtonText: '确定',
            callback: function () {
              router.push('/login')
            }
          })
        }
        break
      case 0:
        break
    }
    // tryHideFullScreenLoading()
    return data
  },
  error => {
    loading.close()
    if (error.response) {
      switch (error.response.code) {
        case 5001:
          if (window.localStorage.getItem('token')) {
            window.localStorage.setItem('token', '')
            vue.$alert('登录状态失效，请重新登录', '提示', {
              confirmButtonText: '确定',
              callback: function () {
                router.push('/login')
              }
            })
          }
          break
      }
    }
    return Promise.reject(error)
  }
)
export { serverName, axios }
