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'
    var language = zzSessionStorage.getItem('lang')
    config.headers['Accept-Language'] = language === 'en' ? 'en-US,en;q=0.5' : 'zh-CN,zh;q=0.9'
    // console.log(config.headers)
    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 contentDisposition = response.headers['content-disposition']
    if (contentDisposition) {
      if (contentDisposition.includes('zip')) {
        let fileName = contentDisposition.split('; ')[1].split('=')[1]
        fileName = decodeURI(fileName)
        const a = document.createElement('a')
        const href = URL.createObjectURL(new Blob([res], { type: response.headers['content-type'] }))
        a.download = fileName
        a.href = href
        a.click()
        URL.revokeObjectURL(href)
        return true
      }
    }

    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) {
          if (contentDisposition.includes('zip')) {
            fileName = contentDisposition.split('; ')[1].split('=')[1]
          } else {
            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: response.headers['content-type'] }))
        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 = store.state.lang.language === 'en' ? 'Request error' : '请求错误'; break
        case 401: message = store.state.lang.language === 'en' ? 'Not authorized or login timed out. Please log in again.' : '未授权或登陆超时,请重新登录'; break
        case 403: message = error.response.data.ErrorMessage; break
        case 404: message = store.state.lang.language === 'en' ? 'Request address error' : `请求地址出错`; break
        case 405: message = store.state.lang.language === 'en' ? 'Interface parameter error or request method inconsistency' : `接口参数传递错误，或者请求方法不一致`; break
        case 408: message = store.state.lang.language === 'en' ? 'Request timed out' : '请求超时'; break
        case 429: message = store.state.lang.language === 'en' ? 'The application service limits the traffic. Your requests are too frequent. Please try again later.' : '应用服务限流，您的请求过于频繁，请稍后再试'; break
        case 500: message = store.state.lang.language === 'en' ? 'Internal server error, and unable to complete the request. Software release might be in process. Please contact the administrator.' : '服务器内部错误，无法完成请求；可能正在发布中，请联系管理员处理'; break
        case 501: message = store.state.lang.language === 'en' ? 'Service has not been implemented.' : '服务未实现'; break
        case 502: message = store.state.lang.language === 'en' ? 'System is being upgraded. Please wait patiently.' : '系统正在升级，请耐心等待。'; break
        case 503: message = store.state.lang.language === 'en' ? 'Service is not available' : '服务不可用'; break
        case 504: message = store.state.lang.language === 'en' ? 'Gateway timed out' : '网关超时'; break
        case 505: message = store.state.lang.language === 'en' ? 'HTTP version is not supported' : '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`)
            this.$i18n.locale = 'zh'
            this.setLanguage('zh')
            this.$updateDictionary()
          })
        }
      } else {
        MessageBox.confirm(message, '警告', {
          type: 'warning',
          showCancelButton: false,
          confirmButtonText: '确定',
          callback: action => { }
        })
      }
    }

    return Promise.reject(new Error(message || 'Error'))
  }
)

export default service
