import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { VueAxios } from './axios'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import router from '../router'

const SUCCESS_CODE = 200
const INVALID_TOKEN_CODE = 401

const toast = (msg, description) => {
  notification.error({
    message: msg,
    description: description
  })
}

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 60000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      toast('Forbidden:', data.msg)
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      toast('Unauthorized:', 'Authorization verification failed')
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 由于登录接口待联调，token使用默认值
  // const token = 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjY0MjM0YmY0LTkxOWEtNDFkMS05MzZlLTMwZDU3NDhkYmVjZCJ9.J15_FhVqcm_GsNIS2BCEYf26sWQQ4pMSTedV5eKauZT8-f6480Mx1s5ZdqWdEOlORnkKSc5pUioCngbCopr9cQ'
  // 如果 token 存在,让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers[ACCESS_TOKEN] = token
  }
  if (config.method === 'post') {
    if (!config.data) {
      config.data = {}
    }
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (response.status === 200 && response.data.code === SUCCESS_CODE) {
    return Promise.resolve(response.data)
  } else if (response.data && response.data.code === INVALID_TOKEN_CODE) {
    toast(response.data.msg)
    store.dispatch('Logout').then(() => {
      router.push({ name: 'login' })
    })
    return Promise.reject(response)
  } else {
    if (response.data && response.data.msg) toast(response.data.msg)
    return Promise.reject(response)
  }
}, errorHandler)

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

export default request

export {
  installer as VueAxios,
  request as axios
}
