import axios from 'axios'
import { Loading } from 'element-ui'
import vue from 'vue'
export default function () {
  let instance = axios.create()
  let load
  var target

  console.log('this', this)
  function getUrl () {
    return window.sessionStorage.getItem('API_URL') ? window.sessionStorage.getItem('API_URL') + '/v1' : 'https://api.medmeeting.com/v1'
  }
  function getToken () {
    return window.sessionStorage.getItem('user') ? 'Bearer_' + JSON.parse(window.sessionStorage.getItem('user')).token : ''
  }
  instance.defaults.baseURL = getUrl()
  instance.defaults.headers.common['Authorization'] = getToken()

  instance.interceptors.request.use(
    (config) => {
      target = function () {
        if (config.LoadingTarget) {
          return config.LoadingTarget
        } else if (document.getElementsByClassName('main-content')) {
          return '.main-content'
        }
        return null

      }
      load = Loading.service({
        target: target()
      })
      config.timeout = 100000
      config.headers.common.Authorization = getToken()
      config.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    (res) => {
      vue.nextTick(load.close())
      // 自身api错误情况
      if (res.data.status === 'error') {
        res.status = 411
        return Promise.reject(res)
      }
      return res
    },
    (error) => {
      vue.nextTick(load.close())
      if (/Error: timeout/.test(error)) {
        return Promise.reject({
          data: {
            msg: '网络超时',
            errorCode: 'error'
          },
          status: 408
        })
      }
      return Promise.reject({
        data: {
          msg: '网络错误',
          errorCode: 'error'
        },
        status: 500
      })
    }
  )
  return instance()
}
