import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import router from '@/router'
axios.defaults.withCredentials = false
const service = axios.create({
  baseURL: '/api',
  timeout: 2 * 360000, // request timeout
  withCredentials: false
})

// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    let fileReader = new FileReader();
    fileReader.onload = function() {
      try {
        let jsonData = JSON.parse(fileReader.result);  // 如果是普通对象数据，后台转换失败
        if (!jsonData.IsSuccess && jsonData.ErrorMessage) {
          MessageBox.confirm(jsonData.ErrorMessage,  {
            type: 'warning',
            showCancelButton: false,
            callback: action => {}
          })
          return Promise.reject(jsonData)
        }
      } catch (err) {   // 解析成对象失败，说明是正常的文件流
        let contentDisposition = response.headers['content-disposition']
        let fileName = ''
        if (contentDisposition) {
          fileName = contentDisposition.split('; ')[2].split('=')[1].split("\'")[2]
          fileName = decodeURI(fileName)
        }
        const a = document.createElement('a')
        // xls类型: application/vnd.ms-excel
        // xlsx类型：application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
        const href = URL.createObjectURL(new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' }))
        a.download = fileName
        a.href = href
        a.click()
        URL.revokeObjectURL(href)
        return Promise.resolve(res)
      }
    };
    fileReader.readAsText(res)
  },
  error => {
    var message = ''
    if (error && error.response) {
      const status = error.response.status
      switch (status) {
        case 400: message = '请求错误'; break
        case 401: message = '未授权或登陆超时,请重新登录'; break
        case 403: message = '服务器拒绝访问，请联系管理员授权'; break
        case 404: message = `请求地址出错`; break
        case 405: message = `接口参数传递错误，或者请求方法不一致`; break
        case 408: message = '请求超时'; break
        case 429: message = '应用服务限流，您的请求过于频繁，请稍后再试'; break
        case 500: message = '服务器内部错误，无法完成请求；可能正在发布中，请联系管理员处理'; break
        case 501: message = '服务未实现'; break
        case 502: message = '系统正在升级，请耐心等待。'; break
        case 503: message = '服务不可用'; break
        case 504: message = '网关超时'; break
        case 505: message = 'HTTP版本不受支持'; break
        default: break
      }
      if (error.response.status === 401) {
        if (store.getters.token) {
          Message({
            message: message,
            type: 'warning',
            showClose: true
          })
          store.dispatch('user/logout').then(() => {
            router.push(`/login`)
          })
        }
      } else {
        MessageBox.confirm(message, '警告', {
          type: 'warning',
          showCancelButton: false,
          confirmButtonText: '确定',
          callback: action => {}
        })
      }
    }
    if (!window.navigator.onLine) {
      MessageBox.confirm(store.state.lang.language === 'en'? 'Please check your network' : '请检查您的网络', store.state.lang.language === 'en'? 'Warning' : '警告', {
        type: 'warning',
        showCancelButton: false,
        callback: action => {}
      })
    }
    return Promise.reject(new Error(message || 'Error'))
  }
)

export default service
