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

// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  timeout: 600000 // request timeout
})

let loading
function startLoading() {
  //使用Element loading-start 方法
  loading = Loading.service({
    target: '.render-container'
  })
}
function endLoading() {
  //使用Element loading-close 方法
  if (loading) {
    loading.close()
  }
}

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      // config.headers['sid'] = getToken()
      config.headers['sysType'] = '3'
      config.headers['sid'] = getToken()
    }
    if (loading) {
      endLoading()
    }

    // config.type 可以从api的接口地址定义 可以不触发loading
    if (config.noLoading !== true) {
      startLoading()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  response => {
    endLoading()
    if (response.config.back) {
      return response.data
    }
    // 二进制数据则直接返回
    if (
      response.request.responseType === 'blob' ||
      response.request.responseType === 'arraybuffer'
    ) {
      return response.data
    }
    const res = response.data
    res.code = Number(res.code)
    if (res.code === 401) {
      MessageBox.confirm('登录状态已过期，请重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        removeToken()
        router.push({ path: '/login' })
      })
    } else if (res.code === 500) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 500
      })
      return Promise.reject(res)
    } else if (res.code !== 0) {
      Message({
        message:
          res.result ||
          res.message ||
          res.content.resultMessage ||
          '接口请求错误',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(res)
    } else {
      if (!res.content.result || res.content.result !== '0') {
        Message({
          message: res.result || res.content.resultMessage || '接口请求错误',
          type: 'error',
          duration: 5 * 1000
        })
      } else {
        return res
      }
    }
  },
  error => {
    endLoading()
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 500
    })
    return
  }
)

export default service
