import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Message, Spin } from 'view-design'
// 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) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        TargetCode: 2
      }
    }
    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 && !config.data.isHiddenSpin) {
        Spin.show({
          render: (h) => {
            return h('div', [
              h('Icon', {
                'class': 'demo-spin-icon-load',
                props: {
                  type: 'ios-loading',
                  size: 18
                }
              }),
              h('div', 'Loading')
            ])
          }
        }) // 不建议开启，因为界面不友好
      }
      this.queue[url] = true
      !config.data && (config.data = {})
      store.state.token && (config.data.token = store.state.token)
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      if (status === 200) {
        if (data.code !== 0) {
          if (data.code === 104) {
            Message.error('账户信息已过期！')
            this.destroy(url)
            router.replace({
              name: 'Home',
              query: {
                plcCode: sessionStorage.getItem('plcCode'),
                door: sessionStorage.getItem('door')
              }
            })
            store.commit('setToken', '')
          } else {
            Message.error(data.msg)
          }
          this.destroy(url)
        }
        return data
      } else {
        Message.error('请求失败！')
        this.destroy(url)
      }
    }, error => {
      console.log('error.response')
      console.log(error)
      if (error.response) {
        if (error.response.status === 404) {
          Message.error('未知的请求404！\n' + url)
        } else if (error.response.status === 415) {
          Message.error(error.response.statusText)
        } else {
          Message.error('请求失败！')
        }
      }
      this.destroy(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
