/**
 * Created by ebi on 2017/5/11.
 */
import axios from './axios.js'
import router from '../router'
import { getToken, removeToken } from '../utils/auth'

axios.defaults.baseURL = ''

axios.interceptors.request.use(
  config => {
    config.headers.token = getToken()
    // 小程序里用m的页面
    config.headers.Platform = 'pc'
    config.headers.type = 'web'
    if (getToken() === null || getToken() === undefined) {
      delete config.headers.token
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// insurance 保险 502 503 504时兜底的
function fetch(
  url = '',
  params = {},
  method = 'get',
  contentType = 'form',
  header = {},
  insurance,
  timeout = 15000
) {
  contentType === 'form' && (contentType = 'application/x-www-form-urlencoded')
  contentType === 'json' && (contentType = 'application/json')
  contentType === 'file' && (contentType = 'multipart/form-data')
  const query = []
  for (const k in params) {
    query.push(k + '=' + params[k])
  }
  let qs = query.join('&')
  if (
    contentType === 'application/x-www-form-urlencoded' &&
    query.length > 0 &&
    method === 'get'
  ) {
    url += (url.indexOf('?') < 0 ? '?' : '&') + qs
  }
  if (contentType !== 'application/x-www-form-urlencoded' && method !== 'get') {
    qs = params
  }
  return new Promise((resolve, reject) => {
    const requestParams = {
      timeout,
      method,
      url: '/api' + url,
      data: qs,
      headers: {
        'Content-Type': contentType,
        ...header
      }
    }
    const success = response => {
      const { status, data = {}, statusText } = response
      if (status >= 200 && status <= 401) {
        if (data.code === 401 || data.code === 400) {
          // 未登录
          removeToken()
          router.push(`/?redirect=${encodeURIComponent(window.location.href)}`)
          reject(new Error('需要登录'))
          return
        }
        resolve(data)
      } else if (status === 500) {
        resolve(data)
        router.push('/500')
      } else {
        resolve(data)
      }
    }
    axios(requestParams)
      .then(success)
      .catch(err => {
        if (
          /502|503|504/.test(err.message) ||
          (err + '').indexOf('timeout') > -1
        ) {
          if (insurance) {
            resolve(insurance)
            return
          }
          let msg = '系统繁忙，正在为您排队中，请稍后再试'
          if (window.location.href.indexOf('/zu') > -1) {
            msg += ` ${err.message}`
          }
        } else {
          resolve(err.data)
        }
      })
  })
}

export default fetch
