import axios from 'axios'
import qs from 'qs'
import { getToken } from '@/utils/auth'

const Axios = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 60000,
  responseType: 'json',
  withCredentials: true,
  queryData: {},
  urlData: {},
  headerData: '',
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})

Axios.interceptors.request.use((config) => {
  config.headers['Content-Type'] = config.headerData ? config.headerData : 'multipart/form-data'
  config.headers['X-Auth-Token'] = getToken()
  config.headers['Login-Type'] = 'web'
  // config.urlData = { ...config.urlData,  }
  // 处理请求data,若为get请求，拼到url后面，若为post请求，直接添加到body中
  const urlData = qs.stringify(config.urlData)
  const 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
  }
  if (config.headerData) {
    return config
  } else {
    const fm = new FormData()
    for (const k in config.data) {
      if (Array.isArray(config.data[k])) {
        config.data[k].forEach((v) => {
          fm.append(k, v)
        })
      } else {
        fm.append(k, config.data[k])
      }
    }
    config.data = fm
    return config
  }
}, (error) => {
  console.log(error)
})

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

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)
}
