import Vue from 'vue'
import axios from 'axios'
import {
  MessageBox,
  Message
} from 'element-ui'
import store from '@/store'
import router from '@/router'
import {
  getToken, removeToken
} from '@/utils/auth'

const baseURL = process.env.VUE_APP_DOMAIN_TF
// create an axios instance
Vue.prototype.axios = axios
axios.defaults.timeout = 30000
const service = axios.create({
  baseURL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
})

export const token = getToken()

// request interceptor
service.interceptors.request.use(
  (config) => {
    // console.log(config)
    if (store.getters.token) {
      config.headers['Content-Type'] = 'application/json'
      config.headers.Authorization = getToken()
      config.headers['satoken-user'] = getToken()
    }
    return config
  },
  (error) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
// eslint-disable-next-line complexity
service.interceptors.response.use((response) => {
  if (response.status == 200) {
    if ((response.data.code === '200') || (response.data.code === '')) {
      return response.data
    } else if ((response.data.code === '20004') || (response.data.code === '20005') || (response.data.code == 40005)) { // 有res.data
      MessageBox.confirm(
        'You have been logged out, you can cancel to stay on this page, or log in again',
        'Confirm logout',
        {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }
      ).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
      return Promise.reject(new Error(response.data.message || 'Error'))
    }  // 有res.data
    Message({
      message: response.data.message || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(response)
  }  // 没有res.data
  Message({
    message: `请求错误：${response.statusText}`,
    type: 'error',
    duration: 5 * 1000
  })
  console.log('请求错误', response)
  return Promise.reject(response)
}, (error) => {
  Message({
    message: `请求失败：${error.statusText}`,
    type: 'error',
    duration: 5 * 1000
  })
  console.log('请求失败', error)
  return Promise.reject(error)
})

export default service
