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

let acitveAxios = 0
let timer
const showLoading = () => {
  acitveAxios++
  if (timer) {
      clearTimeout(timer)
  }
  timer = setTimeout(() => {
      if (acitveAxios > 0) {
          context.$bus.emit("showLoading")
      }
  }, 400);
}

const closeLoading = () => {
  acitveAxios--
  if (acitveAxios <= 0) {
      clearTimeout(timer)
      context.$bus.emit("closeLoading")
  }
}

// create an axios instance
const service = axios.create({
  baseURL: '/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    //   config.headers['x-token'] = localStorage.token
    //   config.headers['x-userId'] = localStorage.userId
    // }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data||{}
    // if the custom code is not 200, it is judged as an error.
    if (res.code == 200 || res.code == 20000) {
      return Promise.resolve(res  )
    } else if( res.code == 401){
      // localStorage.removeItem('token')
      // localStorage.removeItem('paperId')
      // return Promise.reject( res )
      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 => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
