import axios from 'axios'
import { Message, MessageBox, Alert } from 'element-ui'
import store from '@/store'
import router from '@/router'
import Vue from 'vue'
axios.defaults.withCredentials = false
const service = axios.create({
  baseURL: '/api',
  timeout: 2 * 360000, // request timeout
  withCredentials: false
})
var path
// request interceptor
// var lang = store.state.lang.language

service.interceptors.request.use(
  config => {
    path = router && router.app && router.app._route && router.app._route.path
    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'
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    try {
      if (eval(process.env.VUE_APP_LOGIN_FOR_PERMISSION)) {
        if (!path || path === '/ReviewersResearchForm' || path === '/ReviewersResearch' || path === '/login' || path === '/researchForm' || path === '/researchLogin' || path === '/email-recompose' || path === '/recompose' || path === '/resetpassword' || path === '/error') {
          return config
        }
        if (store.state.user.userId !== zzSessionStorage.getItem('userId')) {
          window.location.href = `/login`
          zzSessionStorage.removeItem('lastWorkbench')
          Alert(store.state.lang.language === 'en'? 'The same browser only allows one user account to be logged in at a time.' : '同一浏览器只允许同时登陆一个账户',  {
            type: 'warning',
          })
        }
      }
    } catch (e) {
      console.log(e)
    }
    return config
  },
  error => {
    // console.log(error)
    return Promise.reject(error)
  }
)

var isConfirm = true

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.IsSuccess) {
      isConfirm = true
      return Promise.resolve(res)
    } else if (res.IsSuccess === false) {
      if (res.Code !== 5) {
        MessageBox.confirm(res.ErrorMessage,  {
          type: 'warning',
          showCancelButton: false,
          callback: action => {}
        })
      }
      return Promise.reject(res)
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    var message = ''
    if (error && error.response) {
      const status = error.response.status
      if (error.response.data && error.response.data.Code === -1) {
        store.dispatch('user/logout').then(() => {
          router.push(`/login`)
          this.$i18n.locale = 'zh'
          this.setLanguage('zh')
          this.$updateDictionary()
        })
      }
      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) {
          if(message !== ''){
            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 {
          Message({
            message: store.state.lang.language === 'en'? 'You are not authorized to access the interface' : '您无权访问接口',
            type: 'warning',
            showClose: true
          })
        }
      } else {
        if(message !== '' && isConfirm){
          MessageBox.confirm(message, store.state.lang.language === 'en'? 'Warning' : '警告', {
            type: 'warning',
            showCancelButton: false,
            callback: action => {}
          })
        }
      }
    }
    if (!window.navigator.onLine && isConfirm) {
      MessageBox.confirm(store.state.lang.language === 'en'? 'Please check your network，and try again later！' : '请检查网络，稍后重试！', store.state.lang.language === 'en'? 'Warning' : '警告', {
        type: 'warning',
        showCancelButton: false,
        callback: action => {}
      })
      isConfirm = false
    }
    return Promise.reject(new Error(message || 'Error'))
  }
)




export default service
