import axios from 'axios'
import store from '@/store'
import { getToken } from './util'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
}

class HttpRequest {
  constructor (baseUrl = baseURL,confapp) {
    this.baseUrl = baseUrl
    this.queue = {}
    this.confapp=confapp
  }
  getInsideConfig () {
    let appkey=null
    let companykey=null
    let regrole=null
    try{
        let params = new URLSearchParams(location.search)
        appkey=params.get("appkey")
        companykey=params.get("companykey")
        regrole=params.get("regrole")
        this.confapp.regrole=regrole
        this.confapp.companykey=companykey
    }catch(e){
       console.log(e)
    }
    const config = {
      baseURL: this.baseUrl,
      headers: {
        Authorization:"Bearer "+getToken(),
        XAPPKEY:appkey?appkey: this.confapp.appkey,
        XCOMPANYKEY:companykey,
        XREGROLE:regrole,//专用于注册时，区分是否是非租户注册
        XBIZPATH:this.confapp.bizpath
      }
    }
    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 => {
      console.log(error)
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, 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 }
        }
      }
      addErrorLog(errorInfo)
      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
