import axios from 'axios'
import Qs from 'qs'
import { MessageBox } from 'element-ui'
import { Cookie } from '../util/util'
import $store from '@/store'

let host = ''
if (window.location.port === '8080') {
  host = '//test-k3.eosget.io'
}

let ax = axios.create({
  baseURL: host,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }],
  transformResponse: [],
  withCredentials: true
})

ax.interceptors.request.use(
  config => {
    // 添加登陆态
    if (config.needLogin) {
      if ($store.state.account === 'NO_LOGINING') {
        $store.dispatch('doScatterLogin').then((account) => {
          return handleConfig(config)
        })
      } else {
        return handleConfig(config)
      }
    } else {
      return config
    }
  },
  error => {
    return Promise.reject(error)
  }
)

// 拦截器处理错误
ax.interceptors.response.use(
  async response => {
    if (response.data.result === 1 || response.data.code === -90001) { // result为1时请求成功
      return Promise.resolve(response)
    } else {
      if (response.data.code === -5) { // code为-5是登录态失效
        try {
          await $store.dispatch('doGameLogin')
          return Promise.resolve(response)
        } catch (error) {
          return Promise.reject(new Error(error))
        }
      } 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)
  }
)

function handleConfig (config) {
  let authData = {
    account: Cookie.getCookie('account') || $store.state.account.name,
    player: Cookie.getCookie('account') || $store.state.account.name,
    token: Cookie.getCookie('token') || ''
  }

  if (config.method === 'post') {
    config.data = Object.assign(config.data, authData)
  } else if (config.method === 'get') {
    config.params = Object.assign(config.params, authData)
  }
  return config
}

export default ax
