import axios from 'axios'
import {
  setToken
} from '@/libs/util'
import router from '@/router'

class HttpRequest {
  constructor(publicPath = baseURL) {
    this.publicPath = publicPath
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.publicPath,
      headers: {
        'Content-Security-Policy': 'upgrade-insecure-requests'
      }
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    if (!Object.keys(this.queue).length) {}
  }
  interceptors(instance, url) {
    // 请求头添加token
    instance.interceptors.request.use(
      config => {
        if (localStorage.getItem('token')) {
          config.headers.token = localStorage.getItem('token')
        }
        return config
      },
      error => {
        return Promise.reject(error)
      })
    // 请求头添加timestamp
    instance.interceptors.request.use(
      config => {
        if (localStorage.getItem('timestamp')) {
          config.headers.timestamp = localStorage.getItem('timestamp')
        }
        return config
      },
      error => {
        return Promise.reject(error)
      })
    // 请求头添加nonce
    instance.interceptors.request.use(
      config => {
        if (localStorage.getItem('nonce')) {
          config.headers.nonce = localStorage.getItem('nonce')
        }
        return config
      },
      error => {
        return Promise.reject(error)
      })
    // 请求头添加sign
    instance.interceptors.request.use(
      config => {
        if (localStorage.getItem('sign')) {
          config.headers.sign = localStorage.getItem('sign')
        }
        return config
      },
      error => {
        return Promise.reject(error)
      })
    // 请求拦截
    instance.interceptors.request.use(config => {
      // 添加全局的loading...
      if (!Object.keys(this.queue).length) {}
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const {
        data,
        status
      } = res
      if (data.msg == 1000011 || data.msg == 1000010) {
        setToken('')
        router.replace({
          name: 'terminal'
        })
        spa_refresh()
      } else {
        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
          }
        }
      }
      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
