import axios from 'axios'
import qs from 'qs'

const root = 'http://www.4dage.com/newOfficialapi/'
// const root = '/newOfficialapi/'

// const root = 'http://localhost:7000'
// const root = 'http://www.4dage.com:7000'
// 配置请求域名
axios.defaults.baseURL = root
// axios.defaults.baseURL = 'http://www.4dage.com/newOfficialapi/'

const configure = (Vue, router, { Message }) => {
  axios.interceptors.request.use(function (config) {
    if (!config.params) {
      config.params = {}
    }
    config.params.language = global.lg
    config.data = qs.stringify(config.data)
    return config
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  })

  // 配置response拦截器
  axios.interceptors.response.use(
    response => {
      let data = response.data
      let code = Number(data)

      switch (code) {
        case -100:
          break
        case -10:
          Message({
            type: 'error',
            message: '登陆状态失效，请重新登陆'
          })
          router.replace({
            name: 'login'
          })
          break

        case -101:
          Message({
            type: 'error',
            message: '服务器异常，请稍后再试！'
          })
          break

        case -102:
          Message({
            type: 'error',
            message: '缺少必要参数！'
          })
          break
      }
      return data
    },
    error => {
      if (error.response) {
        switch (error.response.status) {
          case 500:
            Message({
              customClass: 'system-err',
              type: 'error',
              message: '服务器错误!'
            })
            break
        }
      }
      return Promise.reject(error.response.data)
    }
  )
  // axios.upload = async function (file) {
  //   let { data: {content: token}} = await this.get('/qiniuToken')
  //   let param = new FormData()
  //   param.append('file', file)
  //   param.append('token', token)

  //   let {data: {key}} = await this.post('http://upload-z2.qiniup.com', param, {
  //     headers: { 'Content-Type': 'multipart/form-data' }
  //   })

  //   return 'http://video.cgaii.com/' + key
  // }
  Vue.prototype.$http = axios
}

export default axios
export { configure, root }
