'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var tslib_es6 = require('../../tslib.es6-0d92ef81.js');
var canvas_table = require('../../canvas/table.js');
var tencentCloud_rum_performance = require('../../tencent-cloud/rum/performance.js');
var wecomRobot_batchSend = require('../../wecom-robot/batch-send.js');
var tam_img_countryMap = require('./country-map.js');
var list_parseList = require('../../list/parse-list.js');
require('../../canvas/get-canvas.js');
require('../../third-party/canvas.js');
require('../../list/list.js');
require('../../tencent-cloud/base/base.js');
require('axios');
require('../../nodejs/crypto.js');
require('../../wecom-robot/base.js');
require('../../wecom-robot/helper.js');
require('../../wecom-robot/send-img.js');
require('../../nodejs/path.js');
require('../../node-img/img.js');
require('../../nodejs/fs.js');
require('../../nodejs/request.js');
require('../../number/number.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
// const DEFAULT_REGION = '其他';
var CHINA_REGION = '中国';
var ONE_DAY_SECONDS = 24 * 60 * 60;
var SORT_KEY = 'allCount';
var TABLE_HEADER_MAP = {
  region: '地区',
  allCount: '请求数',
  firstScreen: '首屏耗时',
  dns: 'DNS查询',
  tcp: 'TCP连接',
  ssl: 'SSL建连',
  ttfb: '请求响应',
  contentDownload: '内容传输',
  domParse: '内容解析',
  resourceDownload: '资源加载'
  // appLaunch: '',
  // scriptEvaluate: '',
  // pageRoute: '',
  // firstPaint: '',
  // engineInit: '',
  // bundleLoad: '',
  // firstScreenRequest: '',
  // loadEnd: '',
  // durationCount000Ratio: '',
  // durationCount500Ratio: '',
  // durationCount1000Ratio: '',
  // durationCount3000Ratio: '',
  // durationCount5000Ratio: '',
  // bucketInf: '',
};
var RATIO_KEY_LIST = ['durationCount000Ratio', 'durationCount500Ratio', 'durationCount1000Ratio', 'durationCount3000Ratio', 'durationCount5000Ratio'];
function isChina(region) {
  return !Object.values(tam_img_countryMap["default"]).includes(region);
}
function fixedNumber(num) {
  return Math.floor(num * 100) / 100;
}
function formatValue(value) {
  if (typeof value !== 'number') return value;
  return fixedNumber(value);
}
function genTableData(data) {
  var tableData = data.map(function (regionItem) {
    var temp = Object.keys(regionItem).reduce(function (ac, perfName) {
      var value = regionItem[perfName];
      if (RATIO_KEY_LIST.includes(perfName)) {
        value = value * 100;
      }
      ac[perfName] = {
        name: perfName,
        value: formatValue(value)
      };
      return ac;
    }, {});
    return temp;
  });
  return tableData;
}
function sortObj(obj, sortKeyList) {
  return sortKeyList.reduce(function (acc, key) {
    if (obj[key] !== undefined) {
      acc[key] = obj[key];
    }
    return acc;
  }, {});
}
function clusterChina(obj) {
  obj[CHINA_REGION] = {
    region: CHINA_REGION
  };
  Object.keys(obj).forEach(function (region) {
    if (isChina(region)) {
      Object.keys(obj[region]).forEach(function (key) {
        if (key === 'allCount') {
          obj[CHINA_REGION][key] = obj[region][key] + (obj[CHINA_REGION][key] || 0);
        } else if (key !== 'region') {
          obj[CHINA_REGION][key] = obj[region][key] * obj[region].allCount + (obj[CHINA_REGION][key] || 0);
        }
      });
      delete obj[region];
    }
  });
  Object.keys(obj[CHINA_REGION]).map(function (key) {
    if (!['allCount', 'region'].includes(key)) {
      obj[CHINA_REGION][key] = obj[CHINA_REGION][key] / obj[CHINA_REGION].allCount;
    }
  });
}
/**
 * 解析 RUM 性能数据返回值，按地区聚合并按请求量排序
 * @param results 原始接口返回数据
 * @returns 按地区聚合后的数据列表
 * @example
 * ```ts
 * const data = parseResult(rumApiResults);
 * // [
 * //   {
 * //     region: '巴西',
 * //     allCount: 100,
 * //     firstScreen: 1000,
 * //     // ...
 * //   },
 * //   { region: '中国', allCount: 5000, ... },
 * // ]
 * ```
 */
function parseResult(results) {
  var obj = {};
  var _iterator = _createForOfIteratorHelper(results),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      (item.series || []).forEach(function (it) {
        var _a;
        var key = ((_a = it === null || it === void 0 ? void 0 : it.tags) === null || _a === void 0 ? void 0 : _a.region) || '';
        if (key) {
          if (!obj[key]) obj[key] = {
            region: key
          };
          ((it === null || it === void 0 ? void 0 : it.columns) || []).reduce(function (acc, column, columnIndex) {
            var _a, _b;
            if (TABLE_HEADER_MAP[column] !== undefined) {
              acc[column] = (_b = (_a = it.values) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b[columnIndex];
            }
            return acc;
          }, obj[key]);
        }
      });
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  clusterChina(obj);
  return Object.keys(obj).map(function (key) {
    var value = sortObj(obj[key], Object.keys(TABLE_HEADER_MAP));
    return value;
  }).sort(function (a, b) {
    return b[SORT_KEY] - a[SORT_KEY];
  });
  // .reduce((acc,item) => {})
  // return  Object.keys(obj).reduce((acc, key) => {
  //   acc[key] = sortObj(obj[key], Object.keys(TABLE_HEADER_MAP));
  //   return acc;
  // }, {});
}
function getTableHeaders(keyList) {
  return keyList.map(function (key) {
    return TABLE_HEADER_MAP[key] || key;
  });
}
function genRUMnPerfData(_ref) {
  var secretId = _ref.secretId,
    secretKey = _ref.secretKey,
    id = _ref.id,
    startTime = _ref.startTime,
    endTime = _ref.endTime,
    _ref$type = _ref.type,
    type = _ref$type === void 0 ? 'region' : _ref$type;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
    var res, list, tableData;
    return _regeneratorRuntime__default["default"].wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          _context.next = 1;
          return tencentCloud_rum_performance.getRUMPerformance({
            secretId: secretId,
            secretKey: secretKey,
            id: id,
            startTime: startTime,
            endTime: endTime,
            type: type
          });
        case 1:
          res = _context.sent;
          list = parseResult(res.data || []);
          tableData = genTableData(list);
          return _context.abrupt("return", tableData);
        case 2:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function genRUMPerfImgAndSend(_ref2) {
  var secretId = _ref2.secretId,
    secretKey = _ref2.secretKey,
    id = _ref2.id,
    startTime = _ref2.startTime,
    endTime = _ref2.endTime,
    _ref2$type = _ref2.type,
    type = _ref2$type === void 0 ? 'region' : _ref2$type,
    _ref2$title = _ref2.title,
    title = _ref2$title === void 0 ? '' : _ref2$title,
    chatId = _ref2.chatId,
    webhookUrl = _ref2.webhookUrl;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2() {
    var data, preData, tableData, len, img;
    return _regeneratorRuntime__default["default"].wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 1;
          return genRUMnPerfData({
            secretId: secretId,
            secretKey: secretKey,
            id: id,
            startTime: startTime,
            endTime: endTime,
            type: type
          });
        case 1:
          data = _context2.sent;
          _context2.next = 2;
          return genRUMnPerfData({
            secretId: secretId,
            secretKey: secretKey,
            id: id,
            startTime: startTime - ONE_DAY_SECONDS,
            endTime: endTime - ONE_DAY_SECONDS,
            type: type
          });
        case 2:
          preData = _context2.sent;
          list_parseList.compareTwoList(data, preData, 'region');
          tableData = list_parseList.getMaxAndMinIdx(data);
          if (tableData.length) {
            _context2.next = 3;
            break;
          }
          return _context2.abrupt("return");
        case 3:
          len = Object.keys(tableData[0]).length;
          img = '';
          try {
            img = canvas_table.createCanvasTable({
              data: tableData,
              headers: getTableHeaders(Object.keys(tableData[0])),
              title: title,
              cellWidthList: [95].concat(_toConsumableArray__default["default"](Array.from({
                length: len
              }).map(function () {
                return 65;
              })))
            });
          } catch (err) {
            console.error('[genRUMPerfImgAndSend.createCanvasTable.err]', err);
          }
          if (!(!img || !chatId)) {
            _context2.next = 4;
            break;
          }
          return _context2.abrupt("return");
        case 4:
          _context2.next = 5;
          return wecomRobot_batchSend.batchSendWxRobotBase64Img({
            img: img,
            webhookUrl: webhookUrl,
            chatId: chatId
          });
        case 5:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}

exports.clusterChina = clusterChina;
exports.fixedNumber = fixedNumber;
exports.formatValue = formatValue;
exports.genRUMPerfImgAndSend = genRUMPerfImgAndSend;
exports.genRUMnPerfData = genRUMnPerfData;
exports.genTableData = genTableData;
exports.isChina = isChina;
exports.parseResult = parseResult;
exports.sortObj = sortObj;
