(function () {
  window.removeToken = function (text) {
    antd.Modal.info({
      title: '提示',
      content: text || 'Token过期',
      onOk() {
        localStorage.removeItem('ocr-token')
        localStorage.removeItem('user-info')
        window.location.href = 'login.html';
      }
    })
  }

  // 深拷贝且将所有成员键名首字母转为大写
  const deepCopyAndSetCase = obj => {
    const _obj = Array.isArray(obj) ? [] : {}
    for (let key in obj) {
      const _key = typeof key === 'string' ? key[0].toLocaleUpperCase() + key.replace(/^\w/, '') : key
      if (obj[key] && Array.isArray(obj[key]) || Object.prototype.toString.call(obj[key]) === "[object Object]") {
        _obj[_key] = deepCopyAndSetCase(obj[key])
      } else {
        _obj[_key] = obj[key]
      }
    }
    return _obj
  }

  axios.defaults.timeout = 60 * 1000;
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
  axios.interceptors.request.use(
    config => {
      let _token = localStorage.getItem('ocr-token') || '';
      if (_token) {
        config.headers.common["Token"] = _token;
      }
      let _clientId = localStorage.getItem('ocr-clientId');
      if (_clientId) {
        config.headers.common["ClientId"] = _clientId;
        config.headers.common["ClientType"] = 1;
      }
      config.headers.common["IsLogs"] = true;
      return config;
    }
  )
  // 返回状态判断(添加响应拦截器)
  axios.interceptors.response.use(
    (res) => {
      res.Data = deepCopyAndSetCase(res.data || res.Data)
      delete res.data
      let _res = res.Data;

      if (_res.DetailedStatus == 1 || _res.DetailedStatus == 7) { } else if (_res.DetailedStatus == 11 || _res.DetailedStatus == 14 || _res.DetailedStatus == 15) {
        //登录权限过期，需要重新登录
        window.removeToken(_res.DetailedMessage);
      } else {
        antd.message.error(_res.DetailedMessage);

      }
      return res;
    },
    (error) => {
      const config = error.config;
      // this.loading = false;
      //是否重复请求
      if (error && error.response) {
        switch (error.response.status) {
          case 400:
            error.message = "请求错误";
            break;
          case 401:
            window.removeToken();
            error.message = "权限丢失,重新获取中";
            break;

          default:
            error.message = `连接错误${error.response.status}`;
        }
      } else {
        error.message = "连接到服务器失败或超时";
      }
      error.message && antd.message.error(error.message);

      return Promise.reject(error);
    }
  )
})();