import axios from 'axios'
import {Message} from 'element-ui'
import store from '../store'
import router from '../router'
import i18n from '../lang' // internationalization
import {getAcceptLanguage} from '../lang'

class BreakSignal {
  constructor(message) {
    this.message = message
  }
}

// 创建axios实例
const service = axios.create({
  withCredentials:true,//
  baseURL: `${process.env.VUE_APP_BASE_API}`, // api的base_url
  timeout: 60 * 1000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json'
  }
})

// request拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['X-Sino-Mark-Token'] = `${store.getters.token}`
  }
  config.headers['Accept-Language'] = getAcceptLanguage()
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.headers && response.headers['content-type'] === 'application/xml;charset=utf-8' && response.headers['content-disposition']) {
      return response
    }
    return response.data
  },
  error => {
    if (error.message.indexOf('Network Error') !== -1) {
      Message.error(i18n.t('http.networkError'))
      throw new BreakSignal(i18n.t('http.networkError'))
    } else if (error.message.indexOf('timeout') !== -1) {
      Message.error(i18n.t('http.networkTimeout'))
      throw new BreakSignal(i18n.t('http.networkTimeout'))
    } else if (error.response.data.status === 503) {
      Message.error(i18n.t('http.serviceUnavailable'))
      throw new BreakSignal(i18n.t('http.serviceUnavailable'))
    } else if (error.response.data.status === 404) {
      Message.error(i18n.t('http.urlNotFound'))
      throw new BreakSignal(i18n.t('http.urlNotFound'))
    } else if (error.response.data.status === 500) {
      Message.error(i18n.t('http.serverError'))
      throw new BreakSignal(i18n.t('http.serverError'))
    }
    console.log('err---', JSON.stringify(error, null, 4))
    return Promise.reject(error)
  }
)
const http = {};
['get', 'post', 'put', 'delete'].forEach(item => {
  http[item] = function (url, data, hasErrorHandle = false, progressEvent = null) {
    return service[item](url, data, {onUploadProgress: progressEvent}).then(res => {
      if (res.headers && res.headers['content-type'] === 'application/xml;charset=utf-8' && res.headers['content-disposition']) {
        return res
      }
      // if (url.search('sys-perm')!=-1) {
      //   console.log(url)
      // }
      if (res.code === 10000) {
        Message.error(i18n.t('http.needLogin'))
        store.dispatch('user/resetToken')
        router.replace('/login')
        return Promise.reject(res)
      } else if (res.code !== 0 && !hasErrorHandle) {
        Message({
          message: res.message,
          type: 'error'
        })
        return Promise.reject(res)
      }
      return res
    })
  }
})

http.export = function(url, data, contentType, hasErrorHandle = false) {
  const tmpService = axios.create({
    baseURL: `${process.env.VUE_APP_BASE_API}`, // api的base_url
    timeout: 120 * 1000, // 请求超时时间
    headers: {
      'X-Sino-Mark-Token': `${store.getters.token}`,
      'Accept-Language': getAcceptLanguage()
    }
  })
  return tmpService['post'](url, data, { responseType: 'blob' }).then(res => {
    if (res.headers &&
      (res.headers['content-type'] === 'application/json;charset=utf-8' ||
        res.headers['content-type'] === 'application/json;charset=UTF-8')) {
      const reader = new FileReader()
      reader.onload = function(event) {
        // 内容就在这里
        const result = reader.result
        const json = JSON.parse(result)
        // 没有权限
        if (json.errCode === '10000') {
          Message.error(i18n.t('http.needLogin'))
          store.dispatch('user/resetToken')
          router.replace('/login')
        } else if (json.code !== 0) {
          Message({
            message: json.errMsg,
            type: 'error'
          })
          return Promise.reject(res)
        }
      }
      reader.readAsText(res.data)
    } else {
      const link = document.createElement('a')
      const blob = new Blob([res.data], { type: contentType })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', decodeURI(res.headers['filename']))
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  })
}

http.image = function(url) {
  const tmpService = axios.create({
    baseURL: `${process.env.VUE_APP_BASE_API}`, // api的base_url
    timeout: 120 * 1000, // 请求超时时间
    headers: {
      'Authorization': `Bearer ${store.getters.token}`
    }
  })
  return tmpService['get'](url, { responseType: 'arraybuffer' }).then(res => {
    if (res.headers &&
      (res.headers['content-type'] === 'application/json;charset=utf-8' ||
        res.headers['content-type'] === 'application/json;charset=UTF-8')) {
      const reader = new FileReader()
      reader.onload = function(event) {
        // 内容就在这里
        const result = reader.result
        const json = JSON.parse(result)
        // 没有权限
        if (json.errCode === '1001') {
          Message.error(i18n.t('http.needLogin'))
          store.dispatch('user/resetToken')
          router.replace('/login')
        } else if (json.errCode !== '00') {
          Message({
            message: json.errMsg,
            type: 'error'
          })
          return Promise.reject(res)
        }
      }
      reader.readAsText(res.data)
    } else {
      return `data:${res.headers['content-type']};base64,` + btoa(
        new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
      )
    }
  })
}

export default http
