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'

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

// 异常拦截处理器
const errorHandler = error => {
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 400) {
      notification.error({
        message: '400-错误请求',
        description: data.message
      })
    }
    if (error.response.status === 404) {
      notification.error({
        message: '404-找不到地址',
        description: data.message
      })
    } else if (error.response.status === 500) {
      notification.error({
        message: '500-服务器内部错误',
        description: data.message
      })
    } else if (error.response.status === 501) {
      notification.error({
        message: '501-服务尚未实施',
        description: data.message
      })
    } else if (error.response.status === 502) {
      notification.error({
        message: '502-错误网关',
        description: data.message
      })
    } else if (error.response.status === 503) {
      notification.error({
        message: '503-服务不可用',
        description: data.message
      })
    } else if (error.response.status === 504) {
      notification.error({
        message: '504-网关超时',
        description: data.message
      })
    } else if (error.response.status === 505) {
      notification.error({
        message: '505-HTTP 版本不受支持',
        description: data.message
      })
    } else if (error.response.status === 403) {
      notification.error({
        message: '403-Forbidden',
        description: data.message
      })
    } else if (error.response.status === 401) {
      if (token) {
        notification.error({
          message: '401-Unauthorized',
          description: '授权验证失败'
        })
        storage.removeItem('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 请根据实际情况自行修改
  if (token && !isPrintRequest(config.url) ) {
    config.headers['Authorization'] = `Bearer ${token}`
  }

  return config
}, errorHandler)

function isPrintRequest(url){
  return url.indexOf("http")>-1 && url.indexOf("/print")>-1;
}
// response interceptor
request.interceptors.response.use(response => {
  return response.data
}, errorHandler)

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

export default request

export { installer as VueAxios, request as axios }
