/*
 * @Description:
 * @Author: Wang Minjie
 * @Date: 2019-12-31 09:55:24
 * @LastEditTime: 2019-12-31 16:42:16
 * @LastEditors: Wang Minjie
 */
import axios from 'axios'
import store from '@/store'
import { Modal } from 'iview'
import { setToken } from '@/libs/util'
// import { Spin } from 'iview'
const addErrorLog = errorInfo => {
  const { statusText, 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) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  // 获取http请求中的请求配置
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url] // deleted 的用法？ES6class的规范？

    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)

      // 错误提示

      if (res.data.ret === 406 || res.data.ret === 408) {
        setToken('', 1)
        // store.dispatch('handleLogOut')
        Modal.warning({
          title: '请重新登录',
          content: res.data.msg
        })
      } else if (res.data.ret !== 200) {
        // console.log('error', res.data.msg)
        Modal.warning({
          title: '错误提示',
          content: res.data.msg
        })
      }

      // 统一返回接口的数据
      return res.data
    }, 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
