import axios from 'axios'
import qs from 'qs'

const Axios = axios.create({
  timeout: 60000,
  responseType: 'json',
  withCredentials: true,
  queryData: {},
  urlData: {},
  headers: {
    'Content-Type': 'application/json',
    'X-Auth-Token': '',
    'hk-from': 'DP'
  }
})

Axios.interceptors.request.use((config) => {
  let aName = 'X-Auth-Token'
  config.headers[aName] = config.token || ''
  let urlData = qs.stringify(config.urlData)
  let queryData = qs.stringify(config.queryData)
  if (config.url.indexOf(':') > -1) {
    if (typeof config.urlData === 'object') {
      config.url = replaceURLParams(config.url, config.urlData)
    } else {
      config.url = config.url.slice(0, config.url.indexOf(':')) + urlData
    }
  }
  if (queryData) {
    config.url += '?' + queryData
  }
  return config
}, (error) => {
  console.log(error)
})

const ajax = (...args) => {
  return new Promise((resolve, reject) => {
    Axios(...args).then(({ data, headers }) => {
      resolve(data)
    }).catch(reject)
  })
}

export default ajax

export function replaceURLParams (url, params) {
  const args = { ...(params || {}), org: 'MQ' }

  return Object.keys(args).reduce((acc, k) => { // 此方法对每个元素进行处理
    const re = new RegExp(`:${k}(?!w)`, 'i')
    return acc.replace(re, args[k])
  }, url)
}
