import Cookie from 'js-cookie'
import Vue from 'vue'
import bus from '../plugins/bus'
import * as pathConfig from './config'
import Message from './newMessage'

export default function ({store, $axios, query}) {
  $axios.onRequest(config => {
    if (config.url == '/p/file/uploadImFile'){
      config.headers['Content-Type'] = 'multipart/form-data;'
    } else if (config.url == '/p/user/recentBrowse') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    else {
      config.headers['Content-Type'] = 'application/json; charset=utf-8'
    }
    let lang = null
    if (query.lang) {
      Cookie.set('language', query.lang)
      lang = query.lang
    } else if (Cookie.get('language')) {
      lang = Cookie.get('language')
    } else {
      Cookie.set('language',store.state.locale ? store.state.locale : 'zh')
      lang = store.state.locale ? store.state.locale : 'zh'
    }
    config.headers['Accept-Language'] = lang
    var token = Cookie.get('token')
    if (token && (config.url.indexOf("/p/") === 0 || config.url == '/user/registerOrBindUser')) {
      config.headers['Authorization'] = token
    }
    if (config.url.indexOf('/p/user/conversations') === 0  || config.url == '/p/user/recentBrowse'){
      config.url = pathConfig.imPath + config.url
    }else{
      config.url = pathConfig.path + config.url
    }
  })

  $axios.onError(error => {
    const code = parseInt(error.response.status)
    if (code == 400) {
      store.commit('handleChangeErrMsg', error.response.data)
      Message.warning(error.response.data)
    } else if (code == 500) {
      Message.error('服务器出了点小差~')
    } else if (code == 401) {
      var url = error.response.config.url;
      const showLogin = !error.response.config.dontShowLogin
      Cookie.remove('token')
      if (url === pathConfig.path + '/p/user/collection/isCollection' || url === pathConfig.path + '/p/shop/collection/isCollection') {
        return
      } else {
        bus.$emit("showLogin", showLogin)
      }
      // Message.warning('请先登录')
      //redirect('/login')
    } else if (code == 204) {
      Message.error('活动已结束！')
      this.$router.push({ path: '/index' })
      return
    }
    // 无法识别状态码的错误用日志打印一下
    console.log("error", error)
  })
}
