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

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api 的 base_url
  timeout: 60000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // console.log('config', config)
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['X-JZ-Admin-Token']为自定义key 请根据实际情况自行修改
      config.headers['X-JZ-Admin-Token'] = getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    const array = [601, 602, 603, 604, 605, 640, 641, 642, 610]
    if (res.errno === 501) {
      MessageBox.alert('系统未登录，请先登录', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
      return Promise.reject('error')
    } else if (res.errno === 502) {
      MessageBox.alert('无权限操作', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject('error')
    } else if (array.includes(res.errno)) {
      MessageBox.alert(res.errmsg, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return response
    } else if (res.errno === 402) {
      MessageBox.alert('数据异常', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      return Promise.reject('error')
    } else if (res.errno === -1 || res.errno === 1) {
      MessageBox.alert(res.errmsg, '错误', {
        confirmButtonText: '确定',
        type: 'error'
      })
      throw new Error(res.errmsg)
    } else if (res.errno !== 0) {
      // 非5xx的错误属于业务错误，留给具体页面处理
      if (response.status == 200) {
        return response
      }
    } else {
      return response
    }
  }, error => {
    // console.log('err' + error)// for debug
    Message({
      message: '登录连接超时',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
