import _extends from "@babel/runtime/helpers/esm/extends";

/**
 * 前端错误日志上报
 */
var ErrorPlugin = /*#__PURE__*/function () {
  /**
   * @param {*} option 参数包含user、menu、type字段
   */
  function ErrorPlugin(option) {
    if (option === void 0) {
      option = {};
    }

    this.user = option.user;
    this.menu = option.menu;
    this.type = option.type || 'H5';
    this.addEvent();
  }

  var _proto = ErrorPlugin.prototype;

  _proto.addEvent = function addEvent() {
    window.addEventListener('error', this.windowErrorHandler.bind(this), false);
  }
  /**
   * 处理window error报错
   */
  ;

  _proto.windowErrorHandler = function windowErrorHandler(e) {
    this.handleError(e.error, {
      info: e.filename,
      colno: e.colno,
      lineno: e.lineno
    });
  }
  /**
   * 处理vue报错
   */
  ;

  _proto.vueErrorHandler = function vueErrorHandler(Vue) {
    var _this = this;

    Vue.config.errorHandler = function (error, vm, info) {
      _this.handleError(error, {
        info: info,
        component: vm._original ? vm._original.$vnode.tag : vm.$vnode.tag
      });
    };
  }
  /**
   * 处理react报错
   */
  ;

  _proto.reactErrorHandler = function reactErrorHandler(error, info) {
    this.handleError(error, {
      info: info.componentStack
    });
  };

  _proto.handleError = function handleError(error, option) {
    var user = this.user || window.ksui && window.ksui.user || {};
    var menu = this.menu || window.ksui && window.ksui.menu || {};
    var data = {
      userId: user.id || '',
      userName: user.name || '',
      menuId: menu.id || '',
      menuName: this.type + "-" + (menu.title || ''),
      error: error.stack || '',
      option: _extends({
        veriosn: document.lastModified,
        url: decodeURIComponent(location.href),
        ua: window.navigator.userAgent
      }, option)
    };
    this.report(data);
  };

  _proto.report = function report(data) {
    data.option = JSON.stringify(data.option);
    var headers = {
      timestamp: Date.now(),
      appkey: '10135'
    };
    console.log('[error-log]', data);
    window.ks.request('syslog.frontendOperationLog.save', data, headers);
  };

  return ErrorPlugin;
}();

export default ErrorPlugin;