import axios from 'axios'
import qs from 'qs'
import toolClass from './util'
import router from '../pages/user/router'
import { Toast } from '../../node_modules/vant';

const token = function (headers) {
  let JWT
  if (headers){
    localStorage.setItem('JWT', headers.authorization)
    JWT = headers.authorization
  }
  const token = JWT ? JWT : localStorage.getItem('JWT')

  return !token ? '' : token
}

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()
  // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
  config.urlData = { ...config.urlData, org: 'MQ' }
  let queryData = qs.stringify(config.queryData)
  // 判断是通过斜杠传参还是通过query传参
  if (config.url.indexOf(':') > -1) {
    if (typeof config.urlData === 'object') {
      config.url = Object.keys(config.urlData).reduce((url, k) => { // 此方法对每个元素进行处理
        const re = new RegExp(`:${k}(?!w)`, 'i')
        return url.replace(re, config.urlData[k])
      }, config.url)
    }
  }
  if (queryData) {
    config.url += '?' + queryData
  }
  let fm = new FormData()
  for (let k in config.data) {
    if (Array.isArray(config.data[k])) {
      fm.append(k, ...config.data[k].map(v => `${k}=${encodeURIComponent(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) {
        // console.log(result)
        // reject(code)
        toolClass.getCode(result.appid)
      } else if (code === 406) {
        // console.log(router.history.current.name)
        if (router.history.current.name !== 'bindMobile') {
          router.push({ name: 'bindMobile' })
        }
      } else {
        // console.log(message)
        Toast.fail({
          duration: 2000, // 持续展示 toast
          forbidClick: true, // 禁用背景点击
          message: message
        })
        reject(message)
      }
    }).catch(reject)
  })
}

export default ajax