import _regeneratorRuntime from "@babel/runtime/regenerator";
import _extends from "@babel/runtime/helpers/esm/extends";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
var rules = [];
var stopUpload = false;
var vmSet = new Set();
var maxLength = 10;
var wait = 2000; // ms

var poll = 3000; // ms

var pollInterval = null;
var http = null;
var lastCheckTime = +new Date();
var headers = {
  'X-menu-id': '2820215716730110',
  $config: {
    _tips: true,
    _log: false
  }
};
export function installDRCheck(Vue) {
  if (isProd()) return;

  if (!Vue) {
    createEvent();
    mixVue(window.Vue);
  }

  createPoll();
}

function createEvent() {
  window.addEventListener('__ks_ready__', function (e) {
    delayInit(e.detail);
  });
}

function delayInit(_x) {
  return _delayInit.apply(this, arguments);
}

function _delayInit() {
  _delayInit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(option) {
    var data;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            http = option.http;
            _context.prev = 1;
            _context.next = 4;
            return getRulesByHttp();

          case 4:
            data = _context.sent;
            rules = data[0] && data[0].childrenLookupValues || [];
            if (!rules.length) failedToGetRules();
            _context.next = 13;
            break;

          case 9:
            _context.prev = 9;
            _context.t0 = _context["catch"](1);
            failedToGetRules();
            console.log('[drCheck-plugin] ', _context.t0);

          case 13:
          case "end":
            return _context.stop();
        }
      }
    }, _callee, null, [[1, 9]]);
  }));
  return _delayInit.apply(this, arguments);
}

function failedToGetRules() {
  rules = [];
  stopUpload = true;
  clearInterval(pollInterval);
}

function getRulesByHttp() {
  return http('system.lookupValue.BatchByCode', 10124, ['sys_frontend_drcheck_h5'], {
    headers: headers
  });
}

function isProd() {
  return window.location.origin.indexOf('www.kye-erp.com') >= 0 || window.navigator.userAgent.indexOf('prod') > 0;
}

function getModuleId() {
  var erp = window.__ERPMODULE__ && window.__ERPMODULE__.id || '';
  var h5 = window.ksui && window.ksui.menu && window.ksui.menu.id || '';
  return erp || h5;
}

function mixVue(Vue) {
  Vue.mixin({
    mounted: function mounted() {
      var env = {
        url: window.location.href,
        menuId: getModuleId()
      };
      this.__drcheck_env__ = env;
      addVm(this); // console.log('collect: ', vmSet)
    } // destroyed () {
    //   remove(this)
    //   console.log('collect: ', vmSet)
    // }

  });
}

function addVm(vm) {
  if (stopUpload) return;

  try {
    vmSet.add(vm);
    setTimeout(checkForUpload, 0);
    resetPoll();
  } catch (e) {
    console.log('[drCheck-plugin] ', e);
  }
}

function createPoll() {
  pollInterval = window.setInterval(checkForUpload, poll);
}

function resetPoll() {
  clearInterval(pollInterval);
  createPoll();
} // function remove (vm) {
//   vmSet.delete(vm)
// }


function checkForUpload() {
  if (vmSet.size === 0) return;
  if (!rules.length) return;
  var isTimeout = +new Date() - lastCheckTime > wait;

  if (vmSet.size > maxLength || isTimeout) {
    lastCheckTime = +new Date();
    var willUpload = [];
    vmSet.forEach(function (vm) {
      var props = extractDataAndProps(vm);
      var el = vm.$el;
      var currentRule = null;
      var canUpload = rules.some(function (rule) {
        try {
          var option = {
            props: props,
            el: el,
            vm: vm
          };

          if (createFunction(rule.func || rule.lookupValue)(option)) {
            currentRule = rule;
            return true;
          }
        } catch (_) {
          return false;
        }
      });

      if (canUpload) {
        willUpload.push(extractForUpload(vm, currentRule));
      }

      vmSet.delete(vm);
    });
    upload(willUpload);
  }
}

function upload(list) {
  if (list.length === 0) return;
  console.warn('[drCheck-plugin] will-upload: ', list);

  try {
    http('cts.framework.uploadWebActionLog', 50159, list, {
      headers: headers
    });
  } catch (e) {
    console.log('[drCheck-plugin] dcCheck http: ', e);
  }
}

function createFunction(body) {
  // eslint-disable-next-line
  return new Function('option', body);
}

function extractForUpload(vm, rule) {
  var detail = '';

  try {
    detail = JSON.stringify(extractPrimitive(extractDataAndProps(vm)));
  } catch (e) {
    console.log(e);
    detail = '[drCheck-plugin] extract error';
  }

  return {
    menuId: vm.__drcheck_env__.menuId,
    url: vm.__drcheck_env__.url,
    ruleId: rule.lookupCode,
    tag: vm.$vnode.tag,
    detail: detail,
    navigator: window.navigator.userAgent,
    ext1: "xpath: " + getPathTo(vm.$el) + ", version: " + document.lastModified
  };
}

function extractDataAndProps(vm) {
  return _extends({}, vm._props, vm._data);
}

function extractPrimitive(obj) {
  var result = Object.create(null);
  Object.keys(obj).forEach(function (k) {
    if (isObject(obj[k])) {
      result[k] = "_ignore_";
    } else {
      result[k] = obj[k];
    }
  });
  return result;
}

function isObject(obj) {
  return obj !== null && typeof obj === 'object';
}

function getPathTo(element) {
  if (!element) {
    return 'Error Dom';
  }

  try {
    if (element.id !== '') {
      return 'id("' + element.id + '")';
    }

    if (element === document.body) {
      return element.tagName;
    }

    var ix = 0;
    var siblings = element.parentNode.childNodes;

    for (var i = 0; i < siblings.length; i++) {
      var sibling = siblings[i];

      if (sibling === element) {
        return getPathTo(element.parentNode) + '/' + element.tagName + '[' + (ix + 1) + ']';
      }

      if (sibling.nodeType === 1 && sibling.tagName === element.tagName) {
        ix++;
      }
    }
  } catch (_) {
    return element.tagName || 'Error Dom';
  }
}