// 鉴于wepy.request并没有axios的调用方式,故使用小程序环境的flyio
import Fly from 'flyio/dist/npm/wx'
const fly = new Fly()

let Authorization = null
function getAuthorization () {
  return Authorization
}

function setAuthorization (header) {
  Authorization = header
}
const log = console.log
fly.config.baseURL = 'https://test-api.wxagame.com/game-mobile/api/v1/'

// add token
fly.interceptors.request.use((config, promise) => {
  log(config, 'request config')
  console.log(getAuthorization())
  if (getAuthorization()) {
    config.headers['Authorization'] = getAuthorization()
  }
  return config
})

fly.interceptors.response.use((config, promise) => {
  if (config.headers['Authorization'.toLowerCase()]) {
    setAuthorization(config.headers['Authorization'.toLowerCase()])
  }
  log(config, 'response')
  return config
}, (error, promise) => {
  log(error, 'response code error')
  // 需要手动处理的错误类型(同后端的协议自处理返回码)
  if (error.status === 422) {
    // fly里面讲responseText存放在engine中.
    let responseJSON = {}
    try {
      // responseJSON = JSON.parse(error.engine.responseText)
      responseJSON = error.engine.response
    } catch (error) {
      log('JSON Parse error')
    }
    const response = {
      error: 1,
      errors: responseJSON.errors,
      message: responseJSON.message
    }
    return promise.resolve({
      data: response
    })
  } else if (error.status === 400) {
    let response = error.engine.response
    wx.showToast({
      title: response.message,
      icon: 'none',
      duration: 2500
    })
    return promise.reject(error)
  } else {
    // 其他类型的错误直接reject掉
    return promise.reject(error)
  }
})
export default fly
export {
  setAuthorization
}
