import axios from 'axios'
import router from '@/router'
import store from '@/store'
import { Notify } from 'vant'
import { setToken, getToken } from '@/libs/util'

const addErrorLog = errorInfo => {
  const { statusText, status, config } = errorInfo
  let info = {
    type: 'ajax',
    code: status,
    // osInfo: getOs(),
    // browserInfo: getBrowser().browser + '/' + getBrowser().version,
    msg: errorInfo.data.message ? errorInfo.data.message : statusText,
    url: config.url,
    dataInfo: config.data ? JSON.parse(config.data) : {},
    headers: config.headers
  }
  if (!config.url.includes('save_error_logger')) {
    store.dispatch('addErrorLog', info)
  }
}

class HttpRequest {
  path = ''
  curPath = ''

  constructor(baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {}
    }
    if (getToken()) {
      config.headers.Authorization = 'Bearer ' + getToken()
    }
    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(
      response => {
        this.destroy(url)
        // console.log(response)
        if (response.data.code == 200) {
          return response.data
        } else {
          Notify({ type: 'warning', message: response.data.message })
          return Promise.reject(response.data.message)
        }
      },
      error => {
        this.destroy(url)
        let errorInfo = error.response
        console.log('errorInfo:', errorInfo)
        if (!errorInfo) {
          const {
            request: { statusText, status },
            config
          } = JSON.parse(JSON.stringify(error))
          console.log('config:', config)
          errorInfo = {
            statusText,
            status,
            config
          }
        }
        addErrorLog(errorInfo)
        if (errorInfo.status === 401) {
          setToken('')
          router.replace({
            name: 'login'
          })
        }
        return Promise.reject(error)
      }
    )
  }

  setPath(...paths) {
    this.curPath = `${this.path}/${paths.join('/')}`
    return this
  }

  replace(...params) {
    let count = 0
    this.curPath = this.curPath.replace(/\{.*?\}/g, _match => params[count++])
    return this
  }

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

export default HttpRequest