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

// 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: '.main-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['auth'] = getToken()
    }
    if (loading) {
      endLoading()
    }

    // console.log(config.noLoading)
    //linkage 接口
    // config.type 可以从api的接口地址定义 可以不触发loading
    if (config.noLoading != true) {
      startLoading()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    endLoading()

    if (response.config.back) {
      return response.data
    }
    // 检查res.content是否存在，处理blob等特殊响应类型
    if (res.content) {
      if (res.content.code) {
        res.content.result = res.content.code
      }
      if (res.content.result) {
        res.content.code = res.content.result
      }
    }

    // 只有当res.content不存在且res不是blob时才显示错误
    if (!res.content && !(response.config.responseType === 'blob')) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 500
      })
      return Promise.reject(res)
    }
    if (response.request.responseType === 'blob' || response.request.responseType === 'Blob') {
      return response.data
    }
    if (res.content.code !== '0' && res.content.result !== 0) {
      //500毫秒延迟  显得过度平滑
      // token过期或失效 根据项目设置其code
      if (response.headers['content-type'] !== 'application/x-zip-compressed') {
        if (res.content.code === '4001' || res.content.code === '4002') {
          MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确认退出', {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        } else {
          Message({
            message: res.content.message || res.content.resultMessage || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
        }
      }
    } else {
      if (res.content.code === '1' || res.content.code === '') {
        Message({
          message: res.content.resultMessage ? res.content.resultMessage : res.content.message ? res.content.message : '接口错误',
          type: 'error',
          duration: 5 * 1000
        })
        return false
      } else {
        res.content.result = '0'
        res.result = String(res.result ? res.result : 0)
        res.code = String(res.code ? res.code : 0)
        return res
      }
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 500
    })
    return Promise.reject(error)
  }
)

export default service
