import axios from 'axios'
import { MessageBox } from 'element-ui'
import $store from '@/store'

let host = ''
if (window.location.port === '8080') {
  host = '//test.mee.chat/'
}

let ax = axios.create({
  baseURL: host,
  headers: { 'Content-Type': 'multipart/form-data' },
  withCredentials: true
})

ax.host = host

// 拦截器处理错误
ax.interceptors.response.use(
  response => {
    if (response.data.result === 1 || response.data.code === -1001) {
      // result为1时请求成功 code == -1001针对红包已抢完的情况
      return Promise.resolve(response)
    } else {
      if (response.data.code === -5) {
        // code为-5是登录态失效
        $store.dispatch('resetGameLogin')
      } else {
        // 请求出错提示错误
        MessageBox.confirm(response.data.msg, 'Error', {
          center: true,
          showCancelButton: false,
          showConfirmButton: false,
          callback () {}
        })
        return Promise.reject(new Error(response.data.msg))
      }
    }
  },
  error => {
    return Promise.reject(error)
  }
)

export default ax
