import axios from 'axios'
import store from '@/store'

class HttpRequest {
  constructor(baseUrl = baseURL) {

    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig() {
    let baseUrl = this.baseUrl;
    if(process.env.NODE_ENV === 'production'){
      baseUrl = this.baseUrl;
    }else if(store.state.user.baseUrl){
      if(store.state.user.baseUrl.indexOf('http') >= 0){
        baseUrl = store.state.user.baseUrl
      }else{
        baseUrl = 'http://' + store.state.user.baseUrl
      }
    }
    const config = {
      // 读取登录后返回url(企业所在的服务器Url)
      baseURL: baseUrl,
      // baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json'
      }
    }
    return config
  }

  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }

  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {data, status, headers} = res
      return {data, status, headers}
    }, error => {
      this.destroy(url)
      let errorInfo = error.response
      if (!errorInfo) {
        const {request: {statusText, status}, config} = JSON.parse(JSON.stringify(error))
        errorInfo = {
          statusText,
          status,
          request: {responseURL: config.url}
        }
      }
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}

export default HttpRequest
