// 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'
// import { ACCESS_TOKEN } from '@/store/mutation-types'
// console.log(process.env.VUE_APP_PRO_NAME)
// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 60000 // 请求超时时间
})

const err = (error) => {
  console.log(error.response.data.message, 'error')
  if (error.response) {
    const status = error.response.status
    if ((status == 503 || status == 500) && window.location.pathname != '/user/login') {
      notification.destroy()
      notification.error({
        message: '提示',
        description: error.response.data.message
      })
    }
  }
  // 超时无法访问服务
  if (error.message.indexOf('timeout') >= 0 && window.location.pathname != '/user/login') {
    notification.destroy()
    notification.error({
      message: '提示',
      description: '请求超时'
    })
  }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = store.getters.token
  config.headers['App-Type'] = 9 // 平台类型
  if (token) {
    config.headers['access-token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  console.log(response, 'response.data.status')
  if (window.location.pathname != '/user/login') {
    if (response.data.status == '500' || response.data.status == '900') {
      notification.destroy()
      notification.error({
        message: '提示',
        description: response.data.message
      })
    }
    const et = sessionStorage.getItem('errorTips')
    if (response.data.status && response.data.status.length == 4 && !et) {
      sessionStorage.setItem('errorTips', 1)
      modal.destroyAll()
      modal.error({
        title: '提示',
        content: response.data.message,
        onOk () {
          sessionStorage.setItem('errorTips', 0)
          if (['1001', '1002', '1006', '1099', '1100', '9000'].indexOf(response.data.status) >= 0) {
            store.dispatch('Logout').then(() => {
              window.location.reload()
            })
          }
        }
      })
    }
  }
  return response.data
}, err)

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

export {
  installer as VueAxios,
  service as axios
}
