/*
 * @Author: WangQiBiao
 * @LastEditors: MoZhuangRu
 * @Description:
 * @Date: 2019-03-12 09:40:46
 * @LastEditTime: 2019-11-21 15:59:50
 */
import axios from 'axios'
import { Loading, Message } from 'element-ui'
import router from '../../route/white-list'
// import store from './../store'
class HttpRequest {
  constructor (baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
    this.needLoadingRequestCount = 0
    this.fullscreenLoading = null
  }

  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      // timeout: 1000 * 60 * 5, // 5分钟
      withCredentials: true, // 跨域
      headers: {
        Accept: 'application/json;charset=utf-8'
      }
    }
    return config
  }

  destroy (url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {
      // Spin.hide()
    }
  }
  /**
   * 错误处理
   */
  handleError (err) {
    if (err.response && err.response.status) {
      switch (err.response.status) {
        // 没有权限
        case 401:
          router.replace({
            path: '/login'
          })
          break
      }
    }
  }

  interceptors (instance, url) {
    instance.defaults.transformResponse = [
      function (res) {
        res = JSON.parse(res)
        // 出错处理
        if (!res.data && res.responseJSON) {
          Message.error(res.responseJSON ? res.responseJSON.message : '服务器出小差了！')
        }
        return res
      }
    ]
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {
        // Spin.show() // 不建议开启，因为界面不友好
      }
      // let needLoading = false
      if (config.params && config.params.needLoading) {
        // 需要loading的时候才增加一次
        this.needLoadingRequestCount += 1
        this.fullscreenLoading = Loading.service({
          fullscreen: true,
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        // if (config.method.toLowerCase === 'get') {
        //   needLoading = config.params.needLoading
        //   delete config.params.needLoading
        // } else {
        //   needLoading = config.params.needLoading
        //   delete config.params.needLoading
        // }
        // needLoading && store.dispatch('actionIsLoading', true)
      }
      this.queue[url] = true
      return config
    }, error => {
      this.handleError(error)
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      // 响应成功后设置loading状态
      if (this.needLoadingRequestCount > 0) {
        this.needLoadingRequestCount--
      } else if (this.needLoadingRequestCount === 0 && this.fullscreenLoading) {
        this.fullscreenLoading.close()
        // store.dispatch('actionIsLoading', false)
      }
      this.destroy(url)
      const { data, status } = res
      return { data, status }
    }, (error) => {
      this.handleError(error)
      // this.destroy(url)
      return Promise.reject(error.response.data)
    })
  }

  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    options.params = Object.assign({}, options.params)
    let url = window.location.href
    if (url.indexOf('?') !== -1) {
      options.params.version = 'demonstration'
    } else {
      options.params.version = 'real'
    }

    this.interceptors(instance, options.url)
    return instance(options)
  }

  // request stream data method
  createdFormDataAxios (URL, formData) {
    return axios.post(this.baseUrl + URL, formData, {
      transformResponse: [
        function (response) {
          return new Blob([response], { type: 'application/json' })
        }
      ],
      headers: {
        'responseType': 'blob',
        'content-type': 'application/x-www-form-urlencoded'
      }
    })
  }
}
export default HttpRequest
