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

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

class HttpRequest {
  path = ''
  curPath = ''

  constructor(baseURL) {
    this.baseURL = baseURL
  }

  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(parames) {
    let url = parames.url || ''
    let method = parames.method || 'GET'
    let data = parames.data || parames.params
    let requestUrl = url.indexOf('http://') === -1 && url.indexOf('https://') === -1 ? this.baseURL + url : url
    if (this.curPath !== '') {
      requestUrl = this.curPath
      this.curPath = ''
      this.path = ''
    }

    let options = {
      method: method.toUpperCase(),
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      body: JSON.stringify(data)
    }

    // 设置token
    if (getToken()) {
      options.headers.token = getToken()
    }

    // get请求转换参数
    if (method == 'GET') {
      delete options.body
      let qs = '?'
      for (const key in parames.data) {
        qs += key + '=' + parames.data[key] + '&'
      }
      qs = qs.substring(0, qs.length - 1)
      qs.length > 1 ? (requestUrl += qs) : ''
    }

    return new Promise((resolve, reject) => {
      fetch(requestUrl, options)
        .then(function (response) {
          if (response.ok) {
            return response.json()
          } else {
            const errorInfo = {
              statusText: response.statusText,
              status: response.status,
              url: response.url,
              headers: JSON.stringify(response.headers),
              data: response.data
            }
            addErrorLog(errorInfo)
            if (response.status === 404) {
              error('服务器开小差了,请联系客服~')
            }
            reject(response)
          }
        })
        .then(res => {
          successCallBack(res, resolve, reject)
        })
        .catch(err => {
          error()
        })
    })
  }
}

function error(msg = '请检查您的网络') {
  // Toast({
  //   message: msg,
  //   icon: 'none',
  //   duration: 3500
  // })
}
function successCallBack(res, resolve, reject) {
  switch (res.code) {
    case 200:
      resolve(res.data)
      break
    case 401:
      error('请重新登录!')
      setToken('')
      router.replace({
        name: 'login'
      })
      break
    default:
      businessError(res, reject)
      break
  }
}
function businessError(err, reject) {
  // Toast({
  //   message: err.message,
  //   duration: 2000
  // })
  reject(err)
}

export default HttpRequest