import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'

let loadingInstance = null
let requestCount = 0

const showLoading = () => {
  requestCount++
  if (requestCount === 1) {
    loadingInstance = Loading.service({
      target: '.pc-player-container',
      text: '加载中...',
      background: 'rgba(255,255,255,0.6)'
    })
  }
}

const closeLoading = () => {
  requestCount--
  if (requestCount <= 0) {
    requestCount = 0
    if (loadingInstance) {
      loadingInstance.close()
      loadingInstance = null
    }
  }
}

const service = axios.create({
  baseURL: '/',
})

service.interceptors.request.use(
  config => {
    if (!config.hideLoading) {
      showLoading()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (!response.config.hideLoading) {
      closeLoading()
    }
    const res = response.data || {}
    if (res.code == 200 || res.code == 20000) {
      return Promise.resolve(res)
    } else if (res.code == 401) {
      Message({
        message: '用户被踢下线，请重新登入',
        type: 'error',
        duration: 5000
      })
      window.location.href = '/'
      return Promise.resolve(res)
    } else {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 2000
      })
      return Promise.resolve(res)
    }
  },
  error => {
    closeLoading()
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
