import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import bus from './bus';
import { http } from './http'; // import {date} from './filter'

var API_CODE = 'cts.trace.uploadWebActionLog';

var LogPlugin = /*#__PURE__*/function () {
  function LogPlugin(option) {
    if (option === void 0) {
      option = {};
    }

    this.userId = option.userId;
    this.menuId = option.menuId;
    this.countThreshold = option.countThreshold || 10;
    this.timeThreshold = option.timeThreshold || 10; //秒

    this.sizeThreshold = option.sizeThreshold || 10; //kb

    this.deounceThreshold = option.deounceThreshold || 300; //毫秒

    this.uploadDebouncTime = null;
    this.initTime = Date.now();
    this.reportList = [];
    this.lastActionName = '';
    this.lastActionId = '';
    this.immediateReport = false;
    this.ignoreUrl = [API_CODE].concat(option.ignoreUrl || []);
    this.ignoreClass = ['log-disabled', 'el-dialog__wrapper', 'main-panel'].concat(option.ignoreClass || []);
    this.ignoreTag = ['canvas'].concat(option.ignoreTag || []);
    this.init(); // this.firstReport()
  }

  var _proto = LogPlugin.prototype;

  _proto.init = function init() {
    this.ignoreUrl.push('mcs.user.menu.access.report');
    window.setInterval(this.checkReport.bind(this), this.timeThreshold * 1000);
    this.addEventListener();
  };

  _proto.setOption = function setOption(option) {
    var _this = this;

    Object.keys(option).forEach(function (item) {
      if (_this.hasOwnProperty(item)) {
        _this[item] = option[item];
      }
    });
    console.log(this);
  };

  _proto.reportOnInit = /*#__PURE__*/function () {
    var _reportOnInit = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
      var menu, info, user, userId, report;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) {
          switch (_context.prev = _context.next) {
            case 0:
              menu = window.ksui && window.ksui.menu;
              _context.next = 3;
              return window.ks.getUserInfo();

            case 3:
              info = _context.sent;
              user = info.userInfo || {};
              userId = this.userId || user.id;

              if (!(!userId || !menu.id)) {
                _context.next = 9;
                break;
              }

              console.warn("[log-plugin \u9996\u6B21\u4E0A\u62A5] userId\u6216menuId\u672A\u83B7\u53D6\u5230");
              return _context.abrupt("return");

            case 9:
              report = this.getNormalizerReport();
              report.menuId = menu.id;
              report.userId = userId;
              report.location = 'h5';
              report.navigator = navigator.appVersion || navigator.userAgent;
              report.navigator = report.navigator + ' KSUI:' + window.ksui.version;
              report.xpath = this.makeActionId();
              report.action = '首次进入';
              report.startTime = String(this.initTime);
              report.endTime = '0';
              report.url = 'h5';
              report.httpStatus = '200'; // `${user.id}-${now}-${random(4)}-${menu.id || 'xxxx'}`

              report.webTraceId = userId + "-" + (menu && menu.id || 'xxxx') + "-" + String(this.initTime) + "-" + (this.lastActionId || this.randomCode()) + "-" + Math.floor(1000 + 1000 * Math.random()); // report.webTraceId = userId + '-' + Date.now() + '-' + Math.floor(1000 + 1000 * Math.random()) + '-' + menu.id

              report.requestHeaders = userId + "-" + String(menu.id) + "-" + String(this.initTime);
              report.resCode = 0;
              console.log('首次上报', report);
              report.immediate = true;
              this.reportList.push(report);
              this.checkReport();

            case 28:
            case "end":
              return _context.stop();
          }
        }
      }, _callee, this);
    }));

    function reportOnInit() {
      return _reportOnInit.apply(this, arguments);
    }

    return reportOnInit;
  }();

  _proto.firstReport = function firstReport() {
    var _this2 = this;

    if (window.ks && window.ks.request) {
      this.reportOnInit();
    } else {
      setTimeout(function () {
        if (window.ks && window.ks.request) {
          _this2.reportOnInit();
        } else {
          _this2.firstReport();
        }
      }, 10);
    }
  };

  _proto.getNormalizerReport = function getNormalizerReport() {
    return {
      xpath: '',
      // 事件id
      action: '',
      // 事件名称
      userId: this.userId || window.ksui && window.ksui.user && window.ksui.user.id,
      menuId: '',
      startTime: '',
      endTime: '',
      url: '',
      requestHeaders: '',
      // 模块首次进入时间
      requestBody: '',
      // 弃用
      responseHeaders: '',
      // 弃用
      responseData: '',
      // 弃用
      httpStatus: '',
      webTraceId: '',
      resCode: '',
      immediate: this.immediateReport
    };
  };

  _proto.checkReport = function checkReport() {
    var _this3 = this;

    if (!this.reportList.length) return;

    if (this.reportList.some(function (item) {
      return item.immediate;
    })) {
      console.log("[log-plugin] \u89E6\u53D1\u7ACB\u5373\u4E0A\u62A5");
      this.upload();
      this.clear();
      return;
    }

    if (this.uploadDebouncTime) {
      clearTimeout(this.uploadDebouncTime);
    }

    if (this.reportList.length >= this.countThreshold) {
      console.log("[log-plugin] \u8FBE\u5230\u91C7\u96C6\u6761\u6570: " + this.countThreshold + "\u4E0A\u62A5");
      this.upload();
      this.clear();
    } else {
      this.uploadDebouncTime = setTimeout(function () {
        _this3.upload();

        _this3.clear();
      }, this.deounceThreshold);
    }
  };

  _proto.clear = function clear() {
    this.reportList = [];
  };

  _proto.upload = function upload() {
    var data = this.reportList;
    var headers = {
      timestamp: Date.now(),
      $config: {
        _tips: false
      }
    };
    http(API_CODE, 50159, data, {
      headers: headers
    }).then(function () {
      console.log("[log-plugin] \u65E5\u5FD7\u4E0A\u62A5\u6210\u529F");
    }).catch(function (error) {
      console.log(error);
      console.log("[log-plugin] \u65E5\u5FD7\u4E0A\u62A5\u5931\u8D25");
    });
  };

  _proto.makeReport = function makeReport(axiosResponse) {
    var ua = navigator.appVersion || navigator.userAgent;
    var config = axiosResponse.config;
    var menuId = this.menuId || config.headers['X-menu-id'];
    var report = this.getNormalizerReport();

    if (!report.userId) {
      console.warn("[log-plugin] userId\u672A\u83B7\u53D6\u5230,\u8BF7\u8BBE\u7F6EuserId: ksui.log.userId = \"\u7528\u6237id\"");
      return false;
    }

    if (!menuId) {
      console.warn("[log-plugin] menuId\u672A\u83B7\u53D6\u5230,\u8BF7\u8BBE\u7F6EmenuId: ksui.log.menuId = \"\u83DC\u5355id\"");
      return false;
    }

    if (!/^[0-9]+$/.test(menuId)) {
      console.warn("[log-plugin] menuId\u683C\u5F0F\u9519\u8BEF: " + menuId + ", \u5E94\u8BE5\u662F\u5168\u6570\u5B57");
      return false;
    }

    report.menuId = String(menuId);
    report.location = config.location || '';
    report.navigator = ua;
    report.xpath = config.lastActionId || '';
    report.action = config.lastActionName || '';
    report.startTime = String(config.startTime || 0);
    report.endTime = String(Date.now());
    report.url = config.url || '';
    report.httpStatus = String(axiosResponse.status || '');
    report.webTraceId = config.headers['x-webtrace-id'];
    report.requestHeaders = report.userId + "-" + String(menuId) + "-" + String(this.initTime);

    if (axiosResponse.data && axiosResponse.data.code !== undefined) {
      report.resCode = String(axiosResponse.data.code);
    }

    return report;
  };

  _proto.collectRequest = function collectRequest(config) {
    config.startTime = config.headers.timestamp || Date.now();
    config.lastActionName = this.lastActionName;
    config.lastActionId = this.lastActionId;
    config.location = location.host;
  };

  _proto.collectResponse = function collectResponse(axiosResponse) {
    var conf = axiosResponse.config; // 过滤掉不走开放平台的接口,第三方接口不采集

    if (!conf.headers || !conf.headers.method) {
      return;
    } // 过滤掉标注为不上报日志的接口


    if (conf.$config && conf.$config._log === false) {
      return;
    } // 过滤不上报的method


    if (this.ignoreUrl.some(function (url) {
      return conf.headers.method.indexOf(url) >= 0;
    }) || this.ignoreUrl.some(function (url) {
      return conf.url.indexOf(url) >= 0;
    })) {
      return;
    }

    if (conf.lastActionName && conf.lastActionId) {
      var report = this.makeReport(axiosResponse);

      if (report) {
        this.immediateReport = false;
        this.reportList.push(report);
        this.checkReport();
      }
    }
  };

  _proto.randomCode = function randomCode() {
    var id = this.userId || window.ksui && window.ksui.user && window.ksui.user.id || '';
    return '' + id + Date.now() + Math.floor(1000 + 1000 * Math.random());
  };

  _proto.isIgnore = function isIgnore(dom) {
    if (!dom) return true;
    var classList = dom.className;
    var tagName = dom.tagName && dom.tagName.toLocaleLowerCase();
    var ignore = this.ignoreClass.some(function (c) {
      return typeof classList === 'string' && classList.indexOf(c) >= 0;
    }) || this.ignoreTag.some(function (t) {
      return tagName.indexOf(t) >= 0;
    });
    return ignore;
  };

  _proto.handleEvent = function handleEvent(e) {
    if (this.isIgnore(e.target)) {
      this.lastActionName = '';
      this.lastActionId = '';
    } else {
      var text = e.target.textContent || '';
      this.lastActionName = text ? text.trim().replace(/\s/g, '').substr(0, 10) : text;
      this.lastActionId = this.randomCode();
    }
  } // 自定义日志事件名称
  ;

  _proto.click = function click(option) {
    if (option === void 0) {
      option = {};
    }

    if (typeof option === 'string') {
      this.lastActionName = option;
      return;
    }

    if (option.actionName) {
      this.lastActionName = option.actionName;
    }

    if (option.actionId) {
      this.lastActionId = option.actionId;
    }

    if (option.immediate) {
      this.immediateReport = option.immediate;
    }
  };

  _proto.addEventListener = function addEventListener() {
    document.addEventListener('click', this.handleEvent.bind(this), true);
    bus.$on('httpStart', this.collectRequest.bind(this));
    bus.$on('httpEnd', this.collectResponse.bind(this));
  };

  _proto.makeActionId = function makeActionId() {
    return this.randomCode();
  } // httpStart(request) {
  //   this.collectRequest(request)
  // }
  // httpEnd(response) {
  //   this.collectResponse(response)
  // }
  ;

  return LogPlugin;
}();

export default new LogPlugin();