"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _moment = _interopRequireDefault(require("moment"));
var _qs = require("qs");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } // @ts-ignore
var hasRegId = function hasRegId(msg) {
  var _pagePointConfig = pagePointConfig,
    regKey = _pagePointConfig.regKey;
  var eventType = msg.eventType;
  if (eventType) {
    // 为自定义事件, 判断有无regkey 或者根据eventType 来判断是否发送
    return msg[regKey] || eventType === 'pageLoad' ? true : false;
  } else {
    // dom 元素
    var ownRegId = msg.getAttribute(regKey);
    return ownRegId ? true : false;
  }
};
var options = {
  /**
   * 监听组件标识.
   * @cfg {String} regKey='data-reg-id'
   */
  regKey: 'data-reg-id',
  /**
   * 采集组件attr. 可根据配置采集组件Attribute，默认采集所有'data-'开头的attr
   * @cfg {Array} regAttrs=[]
   */
  regAttrs: [],
  /**
   * 埋点数据后台url,可为字符串也可为一个返回url的函数
   * @cfg {string||Function} url=''
   */
  url: '',
  /**
   * 控制台输出,仅在未配置url的情况下
   * @cfg {Boolean} consoleLog=true
   */
  consoleLog: true,
  /**
   * 发送首屏加载数据
   * @cfg {Boolean} sendPerformanceMsg=false
   */
  sendPerformanceMsg: false,
  /**
   * 发送异常错误收集
   * @cfg {Boolean} sendErrorMsg=false
   */
  sendErrorMsg: false,
  /**
   * 用户扩展数据
   * @cfg {Object}
   */
  extData: {},
  /**
   * 埋点发送信息之前调用的方法，可用来判断是否发送此次埋点信息，返回true或者object发送，false反之。
   * 另外支持扩展发送数据和更换事件对象target，返回数据格式{data:xxx,element:xxx}
   * 默认情况下会根据是否包含regKey决定发送与否
   * @cfg {function} 组件数据 参数事件target和事件类型($element,type)
   */
  beforeSend: hasRegId,
  enable: false
};
var perTimeFlag = false;
var pagePointConfig = _objectSpread({}, options);
var clickTimeId,
  browserType = '',
  OSType = '';
var defaultValue = '',
  clickType = 'click',
  dblclickType = 'dblclick',
  keydownType = 'keydown',
  focusType = 'focusin',
  EventType = {
    clickType: clickType,
    dblclickType: dblclickType,
    keydownType: keydownType,
    focusType: focusType
  };
var defaultAttrs = {
  id: defaultValue,
  tagname: defaultValue,
  className: defaultValue,
  value: defaultValue,
  type: defaultValue,
  name: defaultValue,
  innerText: defaultValue
};
var defaultKeys = {
  shiftKey: false,
  ctrlKey: false,
  altKey: false,
  metaKey: false
};
// 获取浏览器相关的基本数据
var browserData = function browserData() {
  return {
    browser: window.navigator.userAgent,
    url: window.location.href,
    screenWidth: document.body.clientWidth,
    screenHeight: document.body.clientHeight,
    pageTitle: document.title,
    referer: document.referrer,
    evtTime: (0, _moment.default)().format('YYYYMMDDHHmmssSSS'),
    browserType: browserType,
    OSType: OSType
  };
};
var sendPagePoint = function sendPagePoint(event, ext) {
  // 先判断是否埋点已开启
  if (!(pagePointConfig.enable && event)) {
    return;
  }
  var eventData = event,
    composeKeys = {};
  var _pagePointConfig2 = pagePointConfig,
    regKey = _pagePointConfig2.regKey,
    extData = _pagePointConfig2.extData,
    beforeSend = _pagePointConfig2.beforeSend;
  // 假如 event 为 事件对象, 处理event 信息， 否则直接发送
  if (event.target || event.nativeEvent) {
    var target = event.target || event.currentTarget || event;
    if (target && beforeSend) {
      var result = beforeSend(target, event.type);
      if (!result) {
        return;
      }
      ext = _objectSpread(_objectSpread({}, ext), result);
    }
    // click 和 keydown 事件 都发送功能按键情况
    if (event.eventType === clickType || event.eventType === dblclickType || event.eventType === keydownType) {
      composeKeys = {
        shiftKey: event.shiftKey,
        ctrlKey: event.ctrlKey,
        altKey: event.altKey,
        metaKey: event.metaKey
      };
      // click 情况发送 clientX clientY, kewdown 发送 keyCode
      if (event.eventType !== keydownType) {
        composeKeys.clientX = target.clientX + window.document.body.scrollLeft + window.document.documentElement.scrollLeft || 0;
        composeKeys.clientY = target.clientY + window.document.body.scrollTop + window.document.documentElement.scrollTop || 0;
      } else {
        composeKeys.keyCode = event.keyCode;
      }
    }
    eventData = _objectSpread(_defineProperty({
      id: target.id || defaultValue,
      eventType: event.eventType || event.type,
      tagname: target.tagName || defaultValue,
      className: target.className || defaultValue,
      value: target.value || defaultValue,
      type: target.type || defaultValue,
      name: target.name || defaultValue,
      // @ts-ignore
      innerText: removeR(target.innerText).substring(0, 50) || defaultValue
    }, regKey, target.getAttribute(regKey)), composeKeys);
  } else {
    // 用户自定义事件,beforeSend送出全部event信息
    var attrs = {};
    if (event.eventType === clickType || event.eventType === dblclickType || event.eventType === keydownType) {
      attrs = _objectSpread(_objectSpread({}, defaultAttrs), defaultKeys);
      if (event.eventType !== keydownType) {
        attrs.clientX = 0;
        attrs.clientY = 0;
      } else attrs.keyCode = 0;
    } else if (event.eventType === focusType) {
      attrs = defaultAttrs;
    }
    if (beforeSend) {
      var _result = beforeSend(event);
      if (!_result) {
        return;
      }
      ext = _objectSpread(_objectSpread({}, ext), _result);
    }
    eventData = _objectSpread(_objectSpread({}, attrs), eventData);
  }
  // 发送信息组成：event信息 + 浏览器相关信息 + 开启埋点功能时用户配置信息 + 调用sendPagePoint时用户传入信息
  var data = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, eventData), browserData()), extData), ext);
  send(data);
};
var logPerformance = function logPerformance() {
  // 性能相关数据
  var t = window.performance.timing;
  // 如果当前的页面尚未加载完成，那么设个延时等待再次调用
  if (t.loadEventEnd === 0) {
    setTimeout(function () {
      logPerformance();
    }, 2000);
    return;
  }
  var times = {
    eventType: 'performanceMsg',
    redirectTime: t.redirectEnd - t.redirectStart,
    dnsTime: t.domainLookupEnd - t.domainLookupStart,
    ttfbTime: t.responseStart - t.navigationStart,
    appcacheTime: t.domainLookupStart - t.fetchStart,
    unloadTime: t.unloadEventEnd - t.unloadEventStart,
    tcpTime: t.connectEnd - t.connectStart,
    reqTime: t.responseEnd - t.responseStart,
    analysisTime: t.domComplete - t.domInteractive,
    blankTime: t.domLoading - t.fetchStart,
    domReadyTime: t.domContentLoadedEventEnd - t.fetchStart,
    loadTime: t.loadEventEnd - t.navigationStart
  };
  send(_objectSpread(_objectSpread({}, times), browserData()));
};
var setPagePoint = function setPagePoint(params) {
  pagePointConfig = _objectSpread(_objectSpread({}, pagePointConfig), params);
  var sendPerformanceMsg = params.sendPerformanceMsg,
    sendErrorMsg = params.sendErrorMsg,
    enable = params.enable;
  if (enable !== false) {
    browserType = getBrowserInfo();
    OSType = getOS();
    // 开启web事件监听
    addPagePointEventListener();
    if (sendPerformanceMsg) {
      document.onreadystatechange = function () {
        if (document.readyState === 'complete') {
          if (perTimeFlag) return;
          logPerformance();
          perTimeFlag = true;
        }
      };
      setTimeout(function () {
        if (perTimeFlag) return;
        logPerformance();
        perTimeFlag = true;
      }, 2000);
    }
    if (sendErrorMsg) {
      window.onerror = function (msg, errurl, line) {
        var col = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0;
        var error = arguments.length > 4 ? arguments[4] : undefined;
        var errordata = _objectSpread({
          eventType: 'errorMsg',
          msg: msg,
          // @ts-ignore
          url: errurl,
          line: line,
          col: col,
          ua: window.navigator.userAgent,
          errorStack: error ? error.stack : ''
        }, browserData());
        send(errordata);
      };
    }
  } else {
    // 关闭事件监听
    removePagePointEventListener();
    window.onerror = function () {};
    perTimeFlag = false;
  }
};
// @ts-ignore
var removeR = function removeR(str) {
  if (!str) return '';
  try {
    return str.replace(/[\r\n]/g, ' ');
  } catch (e) {
    //console.log(e)
  }
};
var send = function send(params) {
  var url = pagePointConfig.url;
  var server_url;
  if (url) {
    if (typeof url === 'function') server_url = url();
    var image = new Image(),
      imageID = 'pagepoint_' + Date.now();
    image.onload = function () {
      delete window[imageID];
    };
    window[imageID] = image;
    image.src = "".concat(server_url, "?").concat((0, _qs.stringify)(params));
  } else {
    console.log(params);
  }
};
var clickHandler = function clickHandler(e) {
  var target = e.srcElement ? e.srcElement : e.target;
  var dataUIRole = target.getAttribute('data-ui-role');
  //   console.log('!!!!!!!click',e, target)
  if (dataUIRole) {
    return;
  }
  clearTimeout(clickTimeId);
  clickTimeId = setTimeout(function () {
    e.eventType = clickType;
    sendPagePoint(e);
  }, 300);
};
var dblclickHandler = function dblclickHandler(e) {
  clearTimeout(clickTimeId);
  var target = e.srcElement ? e.srcElement : e.target;
  var dataUIRole = target.getAttribute('data-ui-role');
  if (dataUIRole) {
    return;
  }
  e.eventType = dblclickType;
  sendPagePoint(e);
};
var keydownHandler = function keydownHandler(e) {
  var target = e.srcElement ? e.srcElement : e.target;
  var dataUIRole = target.getAttribute('data-ui-role');
  if (dataUIRole) {
    return;
  }
  e.eventType = keydownType;
  sendPagePoint(e);
};
var focusHandler = function focusHandler(e) {
  try {
    var target = e.srcElement ? e.srcElement : e.target;
    // window 会触发一次
    if (target === window) {
      return;
    }
    var dataUIRole = target.getAttribute('data-ui-role');
    if (dataUIRole) {
      return;
    }
    e.eventType = focusType;
    sendPagePoint(e);
  } catch (e) {}
};
var removePagePointEventListener = function removePagePointEventListener() {
  try {
    // @ts-ignore
    if (window.addEventListener) {
      //监听click的事件
      window.removeEventListener('click', clickHandler, true);
      //监听双击dbclick事件
      window.removeEventListener('dblclick', dblclickHandler, true);
      //监听按键事件
      window.removeEventListener('keydown', keydownHandler, true);
      window.removeEventListener('focus', focusHandler, true);
    }
  } catch (e) {}
};
var addPagePointEventListener = function addPagePointEventListener() {
  try {
    if (window.addEventListener) {
      //监听click的事件
      window.addEventListener('click', clickHandler, true);
      //监听双击dbclick事件
      window.addEventListener('dblclick', dblclickHandler, true);
      //监听按键事件
      window.addEventListener('keydown', keydownHandler, true);
      window.addEventListener('focus', focusHandler, true);
    }
  } catch (e) {}
};
//判断所处操作系统
function getOS() {
  var sUserAgent = navigator.userAgent.toLowerCase();
  var isWin = navigator.platform === 'Win32' || navigator.platform === 'Win64' || navigator.platform === 'wow64';
  if (isWin) {
    var isWin2K = sUserAgent.indexOf('Windows nt 5.0') > -1 || sUserAgent.indexOf('Windows 2000') > -1;
    if (isWin2K) return 'Win2000';
    var isWinXP = sUserAgent.indexOf('Windows nt 5.1') > -1 || sUserAgent.indexOf('Windows XP') > -1;
    if (isWinXP) return 'WinXP';
    var isWin2003 = sUserAgent.indexOf('Windows nt 5.2') > -1 || sUserAgent.indexOf('Windows 2003') > -1;
    if (isWin2003) return 'Win2003';
    var isWinVista = sUserAgent.indexOf('Windows nt 6.0') > -1 || sUserAgent.indexOf('Windows Vista') > -1;
    if (isWinVista) return 'WinVista';
    var isWin7 = sUserAgent.indexOf('Windows nt 6.1') > -1 || sUserAgent.indexOf('Windows 7') > -1;
    if (isWin7) return 'Win7';
    var isWin8 = sUserAgent.indexOf('windows nt 6.2') > -1 || sUserAgent.indexOf('Windows 8') > -1;
    if (isWin8) return 'Win8';
    var isWin10 = sUserAgent.indexOf('windows nt 10.0') > -1 || sUserAgent.indexOf('Windows 10') > -1;
    if (isWin10) return 'Win10';
  }
  var isMac = navigator.platform === 'Mac68K' || navigator.platform === 'MacPPC' || navigator.platform === 'Macintosh' || navigator.platform === 'MacIntel';
  if (isMac) return 'Mac';
  var isUnix = navigator.platform === 'X11' && !isWin && !isMac;
  if (isUnix) return 'Unix';
  var isLinux = String(navigator.platform).indexOf('Linux') > -1;
  var bIsAndroid = sUserAgent.toLowerCase().indexOf('android') > -1;
  if (isLinux) {
    if (bIsAndroid) return 'Android';else return 'Linux';
  }
  return 'other';
}
//判断所用浏览器
function getBrowserInfo() {
  var agent = navigator.userAgent.toLowerCase();
  var browserInfo = '';
  // IE
  if (agent.indexOf('trident') > 0) {
    browserInfo = 'IE';
  }
  // OLD_IE
  else if (agent.indexOf('msie') > 0) {
    browserInfo = 'IE';
  }
  // Edge
  else if (agent.indexOf('edge') > 0) {
    browserInfo = 'Edge';
  }
  // firefox
  else if (agent.indexOf('firefox') > 0) {
    browserInfo = 'Firefox';
  }
  // Opera
  else if (agent.indexOf('opr') > 0) {
    browserInfo = 'Opera';
  }
  // Safari
  else if (agent.indexOf('safari') > 0 && agent.indexOf('chrome') < 0) {
    browserInfo = 'Safari';
  }
  // Chrome
  else if (agent.indexOf('chrome') > 0) {
    browserInfo = 'Chrome';
  } else {
    browserInfo = 'other';
  }
  return browserInfo;
}
var extendInfo = function extendInfo(data) {
  var extData = pagePointConfig.extData;
  Object.assign(extData, data);
};
var _default = {
  setPagePoint: setPagePoint,
  sendPagePoint: sendPagePoint,
  pagePointConfig: pagePointConfig,
  extendInfo: extendInfo,
  EventType: EventType
};
exports.default = _default;