import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout
})

service.apiModule = {
  authority: '/authority',
  rdfm: '/edfe',
  rpfm: '/epfe',
  wb: process.env.VUE_APP_ENV_NAME === 'wb' ? '/wbtest' : '/wb'
}
service.defaults.headers.post['Content-Type'] = 'application/json'
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
      config.headers['Authorization'] = getToken()
    }
    // 除了get请求，所有其他请求都要带上compilerUserId（编制者），counselorUserId（FMEA辅导员）
    var fmeaPermission = store.getters.fmeaId
        ? sessionStorage.getItem(store.getters.fmeaId)
        : null,
      fmeaPermission = fmeaPermission ? JSON.parse(fmeaPermission) : null,
      compilerUserId = fmeaPermission ? fmeaPermission.compilerUserId : null,
      counselorUserId = fmeaPermission ? fmeaPermission.counselorUserId : null

    if ('get' !== config.method) {
      if (config.data && !config.data.compilerUserId && compilerUserId) {
        config.data.compilerUserId = compilerUserId
      }
      if (
        config.data &&
        !config.data.compilerUserId &&
        counselorUserId &&
        counselorUserId.length > 0
      ) {
        config.data.counselorUserId = counselorUserId
      }
    } else {
      if (config.params) {
        config.params.timeStamp = new Date().getTime()
      } else {
        config.params = {
          timeStamp: new Date().getTime()
        }
      }
    }
    // json序列化
    if ('post' === config.method) {
      // || 'put' === config.method
      //['post'].includes(config.method)
      config.data = JSON.stringify(config.data)
    }
    // 上传文件不能序列化data
    if ('upload' === config.method) {
      config.method = 'post'
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.status !== 0) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        res.code === 50008 ||
        res.code === 50012 ||
        res.code === 50014 ||
        res.status == 401
      ) {
        logout(res.message)
      } else {
        Message({
          message: res.message || 'Error',
          type: res.status === 1 || res.status === 301 ? 'warning' : 'error',
          duration: 4 * 1000
        })
        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      return Promise.resolve(res)
    }
  },
  error => {
    var msg =
      error.response && error.response.data && error.response.data.message
        ? error.response.data.message
        : null
    var status =
      error.response && error.response.data && error.response.data.status
        ? error.response.data.status
        : null

    if (status && status === 401) {
      logout(msg)
    } else {
      Message({
        message: msg || error.message,
        type: 'error',
        duration: 4 * 1000
      })
      return Promise.reject(error)
    }
  }
)

function logout(msg = null) {
  //this.$t()指向问题会报错，所以改为window.vm
  var _that = window.vm
  // to re-login
  MessageBox.confirm(
    msg ? msg : _that.$t('overlengthTips.tipsXfour'),
    _that.$t('overlengthTips.tipsXthree'),
    {
      confirmButtonText: _that.$t('overlengthTips.tipsXone'),
      cancelButtonText: _that.$t('overlengthTips.tipsXtwo'),
      type: 'warning'
    }
  ).then(() => {
    store.dispatch('user/resetToken').then(() => {
      location.reload()
    })
  })
}

export default service
