import axios from 'axios'
import qs from 'qs'
import router from '../router'
import { Message } from 'element-ui'

export function token (headers) {
  let JWT
  if (headers) {
    localStorage.setItem('JWT', headers.authorization)
    JWT = headers.authorization
  }
  return JWT ? JWT : localStorage.getItem('JWT') // eslint-disable-line
}

const Axios = axios.create({
  timeout: 60000,
  responseType: 'json',
  withCredentials: true,
  queryData: {},
  urlData: {},
  headers: {
    'Content-Type': 'multipart/form-data',
    'authorization': token()
  }
})

Axios.interceptors.request.use((config) => {
  config.headers.authorization = token()
  // config.urlData = { ...config.urlData,  }
  // 处理请求data,若为get请求，拼到url后面，若为post请求，直接添加到body中
  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
  }
  let fm = new FormData()
  for (let 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, headers }) => {
      if (headers.authorization) {
        token(headers)
      }
      const { code, message, result } = data
      if (code === 200) {
        resolve(result)
      } else if (code === 401) {
        router.push({ name: 'login' })
      } else {
        Message({
          message: message,
          type: 'error'
        })
        reject(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)
}
