import axios from 'axios'
import { Message, MessageBox, Alert } from 'element-ui'
import store from '@/store'
import router from '@/router'
import WHITELIST from "./whiteList"
import moment from 'moment-timezone';
import { encryptConfig } from "@/utils/encrypt"
import SystemInfo from "@/utils/systemInfo";
const ROUTER = require('@/router');
axios.defaults.withCredentials = false
const systemInfo = new SystemInfo();
const service = axios.create({
  baseURL: '/api',
  // baseURL: process.env.NODE_ENV === 'prod' ? "https://api.irc.extimaging.com" : '/api',
  timeout: 2 * 360000, // request timeout
  withCredentials: false
})
var path
// request interceptor
// var lang = store.state.lang.language

service.interceptors.request.use(
  async config => {
    if (config.url.includes("/Dictionary/getBasicDataSelect")) {
      let query = router && router.app && router.app._route && router.app._route.query
      if (query.trialId) {
        let str = config.url.split("?")
        config.url = `${str[0]}?TrialId=${query.trialId}`
        if (str[1]) {
          config.url += `&${str[1]}`
        }
      }
    }
    path = router && router.app && router.app._route && router.app._route.path
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    // config.baseURL = process.env.NODE_ENV === 'prod' ? "https://api.irc.extimaging.com" : '/api'
    config.headers['Self-Referer'] = window.location.href
    var language = zzSessionStorage.getItem('lang')
    config.headers['Accept-Language'] = language === 'en' ? 'en-US,en;q=0.5' : 'zh-CN,zh;q=0.9'
    config.headers['TimeZoneId'] = moment.tz.guess()
    const allInfo = systemInfo.getAllInfo();
    let obj = {
      browser: {
        name: allInfo.browser.name,
        version: allInfo.browser.version,
      },
      platform: allInfo.platform,
      os: {
        name: allInfo.os.name,
        version: allInfo.os.version
      },
      hardware: {
        logicalCores: allInfo.hardware.logicalCores,
        deviceMemory: allInfo.hardware.deviceMemory
      },
      webgl: {
        version: allInfo.webgl.version,
        renderer: allInfo.webgl.renderer,
        vendor: allInfo.webgl.vendor,
        shadingLanguage: allInfo.webgl.shadingLanguage,
        gpuType: {
          type: allInfo.webgl.gpuType.type,
          discrete: allInfo.webgl.gpuType.discrete,
        },
        performance: {
          tier: allInfo.webgl.performance.tier,
        },
        extensions: {
          length: allInfo.webgl.extensions.length,
        }
      }
    }
    let guid = await systemInfo.generateGuid(obj)
    config.headers['BrowserFingerprint'] = guid
    if (config.ENCRYPT) {
      try {
        config = await encryptConfig(config)
      } catch (err) {
        console.log(err)
      }
    }
    if (store.getters.token && !config.clearToken) {
      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 === '/researchDetail_m' || path === '/researchLogin_m' || path === '/researchLogin' || path === '/email-recompose' || path === '/recompose' || path === '/resetpassword' || path === '/error') {
        //   return config
        // }
        if (!path || WHITELIST.some(item => item === path)) {
          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)
  }
)

let timer = null;
let time = 1000;

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.IsSuccess) {
      return Promise.resolve(res)
    } else if (res.IsSuccess === false) {
      if (res.Code === -4) {
        return Promise.resolve(res)
      } else if (res.Code === -5) {
        let message = store.state.lang.language === 'en' ? 'Program error. Please contact the administrator.' : '程序异常，请联系管理员';
        MessageBox.confirm(message, {
          type: 'warning',
          showCancelButton: false,
          callback: action => {
          }
        })
      } else if (res.Code !== 5) {
        MessageBox.confirm(res.ErrorMessage, {
          type: 'warning',
          showCancelButton: false,
          callback: action => {
            if (res.Code === 6) {
              window.close()
            }
          }
        })
      }
      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 || error.response.data.Code === -2)) {
        store.dispatch('user/logout').then(() => {
          let _vm = ROUTER.default.app
          try {
            if (_vm.$msgbox && _vm.$msgbox.close) {
              _vm.$msgbox.close();
            }
          } catch (err) {
            console.log(err)
          }
          router.push(`/login`)
          // if (!this.$i18n.locale) {
          //   //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 !== '') {
            setTimer({
              message: message,
              type: 'warning',
              showClose: true
            }, 'message')
          }
          store.dispatch('user/logout').then(() => {
            router.push(`/login`)
            // //this.$i18n.locale = 'zh'
            // //this.setLanguage('zh')
            // this.$updateDictionary()
          })
        } else {
          setTimer({
            message: store.state.lang.language === 'en' ? 'You are not authorized to access the interface' : '您无权访问接口',
            type: 'warning',
            showClose: true
          }, 'message')
        }
      } else {
        if (message !== '') {
          setTimer([message, store.state.lang.language === 'en' ? 'Warning' : '警告', {
            type: 'warning',
            showCancelButton: false,
            confirmButtonText: store.state.lang.language === 'en' ? 'ok' : "确定",
            callback: action => { }
          }], 'confirm')
        }
      }
    }
    if (!window.navigator.onLine) {
      setTimer(
        [store.state.lang.language === 'en' ? 'Please check your network，and try again later！' : '请检查网络，稍后重试！', store.state.lang.language === 'en' ? 'Warning' : '警告', {
          type: 'warning',
          showCancelButton: false,
          confirmButtonText: store.state.lang.language === 'en' ? 'ok' : "确定",
          callback: action => { }
        }], "confirm"
      )
    }
    return Promise.reject(new Error(message || 'Error'))
  }
)

const setTimer = (obj, type) => {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  timer = setTimeout(() => {
    if (type === 'message') {
      Message(obj)
    }
    if (type === 'confirm') {
      obj[2].closeOnClickModal = false
      obj[2].closeOnPressEscape = false
      MessageBox.confirm(...obj)
    }
    clearTimeout(timer);
    timer = null;
  }, time)
}




export default service
