/**
 * 网络请求
 */
const _getHeaderUrl = Symbol('_getHeaderUrl')
const signatureUtil = require('./HSSignatureUtil.js')
import axios from 'axios'
import qs from 'qs'
function checkStatus(response) {
  // loading
  // 如果http状态码正常，则直接返回数据
  if (
    response &&
    (response.status === 200 ||
      response.status === 304 ||
      response.status === 400)
  ) {
    return response
    // 如果不需要除了data之外的数据，可以直接 return response.data
  }
  // 异常状态下，把错误信息返回去
  return {
    status: -404,
    msg: '网络异常'
  }
}

function checkCode(res) {
  // 如果code异常(这里已经包括网络错误，服务器错误，后端抛出的错误)，可以弹出一个错误提示，告诉用户
  if (res.status === -404) {
    console.log(res.msg)
  }
  if (res.data && !res.data.success) {
    // alert(res.data.error_msg)
  }

  return res
}
class HSHttpClient {
  constructor(url, ...params) {
    this.urlParams = new Map()
    this.realUrl = ''
    this[_getHeaderUrl](url, params)
  }

  [_getHeaderUrl](url, params) {
    const regexExpression = /\{\b([a-zA-Z_]\w*?)\b\}/g
    let match
    this.realUrl = url
    let i = 0
    while ((match = regexExpression.exec(url))) {
      if (i > params.length - 1) {
        throw new Error('参数值数量少于参数名数量!')
      }
      this.urlParams.set(match[1], params[i])
      this.realUrl = this.realUrl.replace(
        `{${match[1]}}`,
        encodeURIComponent(params[i])
      )
      i++
    }
  }

  getSignRequestUrl(paramsObj, body = '') {
    let returnUrl = ''
    let tempParamsUrl = ''
    if (paramsObj) {
      for (var key in paramsObj) {
        tempParamsUrl += `&${key}=${encodeURIComponent(paramsObj[key])}`
        this.urlParams.set(key, paramsObj[key])
      }
    }
    const timestamp = signatureUtil.getTimeStamp()
    const nonce = signatureUtil.getRandom(5)
    const signaPlain = signatureUtil.makeSignPlain(
      this.urlParams,
      body,
      timestamp,
      nonce
    )
    returnUrl = `${
      this.realUrl
    }?timestamp=${timestamp}&nonce=${nonce}&signature=${signaPlain}${tempParamsUrl}`
    return returnUrl
  }

  get(params = null) {
    const url = this.getSignRequestUrl(params)
    return axios
      .get(url, params)
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  }

  post(data, params = null) {
    const url = this.getSignRequestUrl(params, data)
    return axios({
      method: 'post',
      baseURL: process.env.BASE_API,
      url,
      data: qs.stringify(params),
      timeout: 600000,
      headers: {
        // 'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  }
}

// module.exports = HSHttpClient
const clint = {
  get(urls, params = null, ...parm) {
    const s = new HSHttpClient(urls, ...parm)
    const url = s.getSignRequestUrl(params)
    return axios
      .get(url, params)
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  },
  post(urls, data, params = null, ...parm) {
    const s = new HSHttpClient(urls, ...parm)
    const url = s.getSignRequestUrl(params, data)
    return axios({
      method: 'post',
      baseURL: process.env.BASE_API,
      url,
      data: qs.stringify(data),
      timeout: 600000,
      headers: {
        // 'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      }
    })
      .then(response => {
        return checkStatus(response)
      })
      .then(res => {
        return checkCode(res)
      })
  }
}
export default clint
