

const Loading = window.ELEMENT.Loading
const Message = window.ELEMENT.Message
const axios = window.axios
var loadingInstance = null
const timeout = 60 * 1000 * 3
const Loadings = (text, time = timeout) => {
  const loading = Loading.service({
    lock: true,
    text: text || '正在处理您的操作，请稍候...',
    spinner: 'el-icon-loading',
    color: '#fff',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  setTimeout(() => {
    if (loading.visible) {
      Message.error('请求超时')
      loading.close()
    }
  }, time)
  return loading
}

const axiosInstance = axios.create({
  url: '/',
  baseURL: '',
  timeout,
  withCredentials: false,
  validateStatus: (status) => {
    return status >= 200 && status <= 500 // 默认的
  }
})

// 改变post请求的fromDate状态
axiosInstance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

axiosInstance.interceptors.request.use(
  config => {
    // 处理post 请求
    if (config.data) {
      if (config.data.Loading) {
        loadingInstance = Loadings()
        delete config.data.Loading
      }
    }
    // 处理get请求参数
    if (config.params) {
      if (config.params.Loading) {
        loadingInstance = Loadings()
        delete config.params.Loading
      }
    }
    if(config.headers.ContentType) {
      config.headers['Content-Type']  = config.headers.ContentType
    }

    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器  添加响应器拦截，在响应数据之前
axiosInstance.interceptors.response.use(
  response => {
    if (response) {
      loadingInstance && loadingInstance.close()
      if (response.status === 200) {
        const isFile = Object.prototype.hasOwnProperty.call(response.headers, 'content-disposition')
        if (isFile) {
          return response
        } else {
          if(response.data.code === '200') {
            return response.data
          }else {
            Message({ message: '后端异常:' + response.data.msg,  type: 'error',})
            return Promise.reject()
          }
        }
      } else {
        const { status, data, request: { responseType }} = response
        const { message } = data
        if (responseType === 'arraybuffer') {
          const resBlob = new Blob([data])
          const reader = new FileReader()
          reader.readAsText(resBlob, 'utf-8')
          reader.onload = () => {
            Message({ message: JSON.parse(reader.result).message, type: 'warning', duration: 1500 })
          }
          return Promise.reject()
        }
        var messages = message
        // if (status === 401) {
        //   window.location.replace('#/login')
        // }
        // 修改提示信息，除错误码500外，其他错误码均为警告级别，见bug8130
        if (status === 500) {
          Message({ message: '后端异常:' +  messages,  type: 'error', duration: '5000' })
        } else {
          Message({ message: '后端接口异常', type: 'warning', duration: '5000'})
        }
        return Promise.reject()
      }
    }
  }
)

export default axiosInstance
