import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import modal from 'ant-design-vue/es/modal'
import { VueAxios } from './axios'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 10000 // 请求超时时间
})

const err = (error) => {
  const config = error.config
  // 网络连接出错
  if (error.message.indexOf('Network Error') >= 0) {
    notification.destroy()
    notification.error({
      message: '提示',
      description: '无网络连接，请检查网络是否连接正常'
    })
    store.commit('SET_loadingStatus', false)
    return Promise.reject(err)
  }

  // 业务错误提示
  if (error.response) {
    const status = error.response.status
    if ((status == 503 || status == 500)) {
      notification.destroy()
      notification.error({
        message: '提示',
        description: error.response.data.message
      })
    }
    store.commit('SET_loadingStatus', false)
    return Promise.reject(err)
  }

  // 超时无法访问服务
  if (error.message.indexOf('timeout') >= 0) {
    notification.destroy()
    notification.error({
      message: '提示',
      description: '网络连接超时,正在重连...'
    })
    // If config does not exist or the retry option is not set, reject
    if (!config || !config.retry) return Promise.reject(err)
    // Set the variable for keeping track of the retry count
    config.__retryCount = Vue.ls.get(config.url + '__retryCount') || 0
    // Check if we've maxed out the total number of retries
    if (config.__retryCount >= config.retry) {
      Vue.ls.remove(config.url + '__retryCount')
      notification.destroy()
      notification.error({
        message: '提示',
        description: '网络重连失败,请检测网络连接是否正常'
      })
      store.commit('SET_loadingStatus', false)
      // Reject with the error
      return Promise.reject(err)
    }
    // Increase the retry count
    config.__retryCount += 1
    Vue.ls.set(config.url + '__retryCount', config.__retryCount)
    // Create new promise to handle exponential backoff
    config.url = config.url.replace('/api', '')
    const backoff = new Promise(function (resolve) {
      setTimeout(function () {
        resolve()
      }, config.retryDelay || 1)
    })

    // Return the promise in which recalls axios to retry the request
    return backoff.then(function () {
      return service(config)
    })
  }
}

// request interceptor
service.interceptors.request.use(config => {
  const token = store.getters.token
  const changeOrg = store.getters.changeOrg
  if (token) {
    config.headers['access-token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
    config.headers['access-org'] = changeOrg // 当前要切换的账号 sn
  }
  config.retry = 3
  config.retryDelay = 1000
  store.commit('SET_loadingStatus', true)
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  const et = sessionStorage.getItem('errorTips')
  // 无权限或登录超时
  if ((response.data.status == '1001' || response.data.status == '1099') && !et) {
    sessionStorage.setItem('errorTips', 1)
    modal.destroyAll()
    modal.error({
      title: '提示',
      content: response.data.message,
      onOk () {
        sessionStorage.setItem('errorTips', 0)
        store.dispatch('Logout').then(() => {
          window.location.reload()
        })
      }
    })
  } else if (response.data.status != 200 && response.data.status) {
    // 其它业务错误提示
    notification.destroy()
    notification.error({
      message: '提示',
      description: response.data.message
    })
  }
  store.commit('SET_loadingStatus', false)
  return response.data
}, err)

const installer = {
  vm: {},
  install (Vue) {
    Vue.use(VueAxios, service)
  }
}

export {
  installer as VueAxios,
  service as axios
}
