import axios from 'axios'
import Qs from 'qs'
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': 'application/x-www-form-urlencoded' },
  transformRequest: [function (data) {
    data = Qs.stringify(data)
    return data
  }],
  transformResponse: [],
  withCredentials: true
})

ax.host = host

ax.interceptors.request.use(
  async config => {
    // 添加登录态
    if (config.needLogin) {
      if (!localStorage.getItem('user_id') || !localStorage.getItem('token')) {
        try {
          await $store.dispatch('doGameLogin')
          return handleConfig(config)
        } catch (error) {
        }
      } else {
        return handleConfig(config)
      }
    } else {
      return handleConfig(config)
    }
  },
  error => {
    return Promise.reject(error)
  }
)

// 拦截器处理错误
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)
  }
)

async function handleConfig (config) {
  try {
    let authData = {
      user_id: localStorage.getItem('user_id') || '',
      token: localStorage.getItem('token') || ''
    }

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

// let _request = ax.request
ax.request2 = async function (config) {
  var objResult = null
  if (config.cache) {
    return new Promise(async (resolve, reject) => {
      var data = null
      config = await handleConfig(config)
      if (config.method === 'post') {
        data = config.data
      } else if (config.method === 'get') {
        data = config.params
      }

      var cacheKey = config.method + ':' + config.url + '?' + JSON.stringify(data)
      var cacheStr = localStorage.getItem(cacheKey)
      if (cacheStr) {
        objResult = JSON.parse(cacheStr)
        config.callback(objResult)
      }

      objResult = await ax.request(config)
      delete objResult['config'] // 这个config没必要缓存
      delete objResult['request'] // 这个request没必要缓存
      var str2 = JSON.stringify(objResult)
      if (cacheStr != str2) {
        if (objResult.data.result) {
          localStorage.setItem(cacheKey, str2)
        }
        config.callback(objResult)
      }
    })
  } else {
    objResult = await ax.request(config)
    config.callback(objResult)
  }
}

export default ax
