'use strict';

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

var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var tslib_es6 = require('../tslib.es6-0d92ef81.js');
var time_time = require('../time/time.js');
var wecomRobot_batchSend = require('../wecom-robot/batch-send.js');
var cyclomaticComplexity_config = require('./config.js');
require('../wecom-robot/base.js');
require('../wecom-robot/helper.js');
require('axios');
require('../wecom-robot/send-img.js');
require('../nodejs/path.js');
require('../node-img/img.js');
require('../nodejs/crypto.js');
require('../nodejs/fs.js');
require('../nodejs/request.js');

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

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

// 或者使用 Record 简写
// type StrictComplexityMetrics = Record<ComplexityKey, string>;
var toFixed = function toFixed(num) {
  var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
  return parseFloat((+num).toFixed(count));
};
// [{1: 'a', 2: 'b', 3: 'c'}]
function parseCyclomaticComplexity() {
  var report = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var info = report.reduce(function (acc, item) {
    var obj = cyclomaticComplexity_config.COMPLEXITY_DEFAULT_CSV_HEADER.reduce(function (acc, header, idx) {
      var value = item[idx + 1];
      return Object.assign(Object.assign({}, acc), _defineProperty__default["default"]({}, header, value));
    }, {});
    acc.push(obj);
    return acc;
  }, []);
  return info;
}
function getStatistics(rawList) {
  var list = rawList.map(function (item) {
    return Object.assign(Object.assign({}, item), {
      CNN: item.CNN ? item.CNN : '0'
    });
  });
  var totalFileInfo = list.reduce(function (acc, item) {
    return Object.assign(Object.assign({}, acc), _defineProperty__default["default"]({}, item.FILE_NAME, item));
  }, {});
  var fileTotal = Object.keys(totalFileInfo).length;
  var funcTotal = list.length;
  var cnnTotal = list.reduce(function (acc, item) {
    return acc + +item.CNN;
  }, 0);
  var tokenTotal = list.reduce(function (acc, item) {
    return acc + (item.TOKEN_COUNT ? +item.TOKEN_COUNT : 0);
  }, 0);
  var parameterTotal = list.reduce(function (acc, item) {
    return acc + (item.PARAMETER_COUNT ? +item.PARAMETER_COUNT : 0);
  }, 0);
  var nLocTotal = list.reduce(function (acc, item) {
    return acc + (item.NLOC ? +item.NLOC : 0);
  }, 0);
  var locTotal = list.reduce(function (acc, item) {
    return acc + (item.LOC ? +item.LOC : 0);
  }, 0);
  var avgCNN = cnnTotal / funcTotal;
  var avgNLOC = nLocTotal / funcTotal;
  var avgToken = tokenTotal / funcTotal;
  var avgParameter = parameterTotal / funcTotal;
  var less5Length = getBetweenLength(list, 5);
  var between5And10Length = getBetweenLength(list, 5, 10);
  var between10And15Length = getBetweenLength(list, 10, 15);
  var between15And20Length = getBetweenLength(list, 15, 20);
  var between20And25Length = getBetweenLength(list, 20, 25);
  var between25And30Length = getBetweenLength(list, 25, 30);
  var between30And35Length = getBetweenLength(list, 30, 35);
  var greater35Length = getBetweenLength(list, undefined, 35);
  var nlocList = list.map(function (item) {
    return {
      CNN: item.NLOC
    };
  });
  var nlocStep = 5;
  var maxNLOCLadder = 120;
  var parameterList = list.map(function (item) {
    return {
      CNN: item.PARAMETER_COUNT
    };
  });
  var parameterStep = 1;
  var maxParameterLadder = 10;
  var nlocLadders = [getBetweenLength(nlocList, 5)];
  for (var i = 5; i < maxNLOCLadder; i += nlocStep) {
    var temp = getBetweenLength(nlocList, i, i + nlocStep);
    nlocLadders.push(temp);
  }
  nlocLadders.push(getBetweenLength(nlocList, undefined, maxNLOCLadder));
  var parameterLadders = [
  // 从 0 开始
  getBetweenLength(parameterList, 0)];
  for (var _i = 0; _i < maxParameterLadder; _i++) {
    var _temp = getBetweenLength(parameterList, _i, _i + parameterStep);
    parameterLadders.push(_temp);
  }
  parameterLadders.push(getBetweenLength(parameterList, undefined, maxParameterLadder));
  return {
    fileTotal: fileTotal,
    funcTotal: funcTotal,
    cnnTotal: cnnTotal,
    avgCNN: avgCNN,
    avgNLOC: avgNLOC,
    avgToken: avgToken,
    avgParameter: avgParameter,
    locTotal: locTotal,
    nLocTotal: nLocTotal,
    tokenTotal: tokenTotal,
    parameterTotal: parameterTotal,
    less5Length: less5Length,
    between5And10Length: between5And10Length,
    between10And15Length: between10And15Length,
    between15And20Length: between15And20Length,
    between20And25Length: between20And25Length,
    between25And30Length: between25And30Length,
    between30And35Length: between30And35Length,
    greater35Length: greater35Length,
    parameterLadders: parameterLadders,
    nlocLadders: nlocLadders
  };
}
function getBetweenLength(list, min, max) {
  var parsedList = list.map(function (item) {
    return {
      CNN: item.CNN ? +item.CNN : 0
    };
  });
  if (min !== undefined && max !== undefined) {
    return parsedList.filter(function (item) {
      return +item.CNN > min && +item.CNN <= max;
    }).length;
  }
  if (min !== undefined) {
    return parsedList.filter(function (item) {
      return +item.CNN <= min;
    }).length;
  }
  if (max !== undefined) {
    return parsedList.filter(function (item) {
      return +item.CNN > max;
    }).length;
  }
  return 0;
}
function getReportTableMd(_ref) {
  var funcTotal = _ref.funcTotal,
    less5Length = _ref.less5Length,
    between5And10Length = _ref.between5And10Length,
    between10And15Length = _ref.between10And15Length,
    between15And20Length = _ref.between15And20Length,
    between20And25Length = _ref.between20And25Length,
    between25And30Length = _ref.between25And30Length,
    between30And35Length = _ref.between30And35Length,
    greater35Length = _ref.greater35Length;
  var list = ['|类别|数目|占比|累计占比|', '|---|---|---|---|'];
  var getRatio = function getRatio(num) {
    return "".concat(getPureRatio(num), "%");
  };
  var getPureRatio = function getPureRatio(num) {
    return toFixed(num / funcTotal * 100);
  };
  var getAccumulateRatio = function getAccumulateRatio(list) {
    var result = list.reduce(function (acc, item) {
      return acc + getPureRatio(item);
    }, 0);
    return "".concat(toFixed(result), "%");
  };
  list.push('|' + "> 35|".concat(greater35Length, "|").concat(getRatio(greater35Length), "|").concat(getAccumulateRatio([greater35Length])));
  list.push('|' + "31 - 35|".concat(between30And35Length, "|").concat(getRatio(between30And35Length), "|").concat(getAccumulateRatio([greater35Length, between30And35Length])));
  list.push('|' + "26 - 30|".concat(between25And30Length, "|").concat(getRatio(between25And30Length), "|").concat(getAccumulateRatio([greater35Length, between30And35Length, between25And30Length])));
  list.push('|' + "21 - 25|".concat(between20And25Length, "|").concat(getRatio(between20And25Length), "|").concat(getAccumulateRatio([greater35Length, between30And35Length, between25And30Length, between20And25Length])));
  list.push('|' + "16 - 20|".concat(between15And20Length, "|").concat(getRatio(between15And20Length), "|").concat(getAccumulateRatio([greater35Length, between30And35Length, between25And30Length, between20And25Length, between15And20Length])));
  list.push('|' + "11 - 15|".concat(between10And15Length, "|").concat(getRatio(between10And15Length), "|").concat(getAccumulateRatio([greater35Length, between30And35Length, between25And30Length, between20And25Length, between15And20Length, between10And15Length])));
  list.push('|' + "6 - 10|".concat(between5And10Length, "|").concat(getRatio(between5And10Length), "|").concat(getAccumulateRatio([greater35Length, between30And35Length, between25And30Length, between20And25Length, between15And20Length, between10And15Length, between5And10Length])));
  list.push('|' + " <= 5 |".concat(less5Length, "|").concat(getRatio(less5Length), "|100%"));
  return list;
}
function getCyclomaticComplexityReportAndSendToRobot(_ref2) {
  var reportJson = _ref2.reportJson,
    detailLinks = _ref2.detailLinks,
    webhookUrl = _ref2.webhookUrl,
    chatId = _ref2.chatId,
    _ref2$repo = _ref2.repo,
    repo = _ref2$repo === void 0 ? '' : _ref2$repo;
  return tslib_es6.__awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
    var list, info, mdTable, date, links, msgList;
    return _regeneratorRuntime__default["default"].wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          list = parseCyclomaticComplexity(reportJson);
          info = getStatistics(list);
          mdTable = getReportTableMd(info);
          date = time_time.timeStampFormat(Date.now(), 'yyyy-MM-dd');
          links = (detailLinks || []).map(function (item) {
            return "[".concat(item.label, "](").concat(item.value, ")");
          }).join(' ');
          msgList = ["## \u3010".concat(repo ? "".concat(repo, " ") : '', "\u4EE3\u7801\u5708\u590D\u6742\u5EA6\u7EDF\u8BA1\u3011 ").concat(date).concat(links ? " ".concat(links) : ''), '### 1. 📃 基本信息', "- \u7EDF\u8BA1\u6587\u4EF6\u4E2A\u6570\uFF1A".concat(info.fileTotal), "- \u7EDF\u8BA1\u51FD\u6570\u4E2A\u6570\uFF1A".concat(info.funcTotal), "- \u5E73\u5747\u5708\u590D\u6742\u5EA6\uFF1A".concat(toFixed(info.avgCNN)), "- \u5E73\u5747\u4EE3\u7801\u884C\u6570\uFF1A".concat(toFixed(info.avgNLOC)), "- \u5E73\u5747\u53C2\u6570\u4E2A\u6570\uFF1A".concat(toFixed(info.avgParameter)), '### 2. 💻 代码圈复杂度'].concat(_toConsumableArray__default["default"](mdTable));
          if (!(!webhookUrl || !chatId)) {
            _context.next = 1;
            break;
          }
          return _context.abrupt("return", {
            list: list,
            info: info,
            msgList: msgList,
            mdTable: mdTable
          });
        case 1:
          _context.next = 2;
          return wecomRobot_batchSend.batchSendWxRobotMarkdown({
            content: msgList.join('\n'),
            webhookUrl: webhookUrl,
            isV2: true,
            chatId: chatId
          });
        case 2:
          return _context.abrupt("return", {
            list: list,
            info: info,
            msgList: msgList,
            mdTable: mdTable
          });
        case 3:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}

exports.getCyclomaticComplexityReportAndSendToRobot = getCyclomaticComplexityReportAndSendToRobot;
exports.getReportTableMd = getReportTableMd;
exports.getStatistics = getStatistics;
exports.parseCyclomaticComplexity = parseCyclomaticComplexity;
