import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../../tslib.es6-848120af.js';
import { compareTwoList, getMaxAndMinIdx } from '../../list/parse-list.mjs';
import { createCanvasTable } from '../../canvas/table.mjs';
import { saveJsonToLog } from '../../fs/fs-util.mjs';
import { timeStampFormat } from '../../time/time.mjs';
import { batchSendWxRobotBase64Img } from '../../wecom-robot/batch-send.mjs';
import { getRUMScores } from '../api/rum-score.mjs';
import { getTAMSummaryScoreByGroupIdList } from '../api/summary-score.mjs';
import { parseSummaryScore } from '../parse/summary.mjs';
import { getTableHeaders } from '../parse/header.mjs';
import '../../number/number.mjs';
import '../../list/list.mjs';
import '../../canvas/get-canvas.mjs';
import '../../third-party/canvas.mjs';
import '../../fs/fs.mjs';
import '../../nodejs/crypto.mjs';
import '../../nodejs/fs.mjs';
import '../../nodejs/os.mjs';
import '../../nodejs/path.mjs';
import '../../wecom-robot/base.mjs';
import '../../wecom-robot/helper.mjs';
import 'axios';
import '../../wecom-robot/send-img.mjs';
import '../../node-img/img.mjs';
import '../../nodejs/request.mjs';
import '../../tencent-cloud/base/base.mjs';
import '../api/credential.mjs';

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; }
function getRUMScoreList(_ref) {
  var secretInfo = _ref.secretInfo,
    parsedDate = _ref.parsedDate,
    parsedPreDate = _ref.parsedPreDate,
    date = _ref.date;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var parsedPostDate, rumScores, preRumScores;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (!(!secretInfo.rumSecretId || !secretInfo.rumSecretKey)) {
            _context.next = 1;
            break;
          }
          return _context.abrupt("return", {});
        case 1:
          parsedPostDate = timeStampFormat(new Date(date).getTime() + 1 * 24 * 60 * 60 * 1000, 'yyyyMMdd');
          _context.next = 2;
          return getRUMScores({
            secretId: secretInfo.rumSecretId,
            secretKey: secretInfo.rumSecretKey,
            startTime: "".concat(parsedDate, "00"),
            endTime: "".concat(parsedPostDate, "00")
          });
        case 2:
          rumScores = _context.sent;
          _context.next = 3;
          return getRUMScores({
            secretId: secretInfo.rumSecretId,
            secretKey: secretInfo.rumSecretKey,
            startTime: "".concat(parsedPreDate, "00"),
            endTime: "".concat(parsedDate, "00")
          });
        case 3:
          preRumScores = _context.sent;
          console.log('[getRUMScoreList] parsedPostDate: ', parsedPostDate);
          saveJsonToLog(rumScores, 'rum-score.json');
          saveJsonToLog(preRumScores, 'rum-score-pre.json');
          return _context.abrupt("return", {
            rumScores: rumScores,
            preRumScores: preRumScores
          });
        case 4:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
/**
 * 生成TAM汇总数据图
 * @ignore
 * @param {object} options 配置
 * @param {string} options.date 日期，yyyyMMdd格式
 * @param {Array<number>} options.groupIdList groupId列表
 *
 * @param {object} options.secretInfo 密钥信息
 * @param {string} options.secretInfo.apiKey apiKey
 * @param {string} options.secretInfo.loginName loginName
 * @param {Function} options.secretInfo.getPwdCode getPwdCode
 * @param {Function} options.secretInfo.encrypt encrypt
 *
 * @param {object} options.extraDataMap 额外数据Map
 * @param {object} options.ignoreProjectIdList 忽略的projectIdList
 *
 * @param {object} options.tableHeaderMap 表格头部Map
 * @returns {string} 图片base64
 * @example
 * const requestSummaryScoreDate = Date.now() - 1 * 24 * 60 * 60 * 1000;
 *
 * const tamGroupIdList = [1, 2, 3];
 *
 * const summaryScoreTableHeaderMap = {
 *   ProjectName: {
 *     name: '项目名称',
 *     tableWidth: 95,
 *   },
 *   PagePv: {
 *     name: 'PV',
 *     tableWidth: 65,
 *   },
 * };
 *
 * await genSummaryData({
 *   date: requestSummaryScoreDate,
 *   groupIdList: tamGroupIdList,
 *   secretInfo: {
 *     getPwdCode,
 *     encrypt,
 *     apiKey: process.env.AEGIS_APP_KEY,
 *     loginName: 'lee',
 *   },
 *   tableHeaderMap: summaryScoreTableHeaderMap,
 * });
 */
function genSummaryData(_ref2) {
  var date = _ref2.date,
    groupIdList = _ref2.groupIdList,
    secretInfo = _ref2.secretInfo,
    _ref2$extraDataMap = _ref2.extraDataMap,
    extraDataMap = _ref2$extraDataMap === void 0 ? {} : _ref2$extraDataMap,
    _ref2$ignoreProjectId = _ref2.ignoreProjectIdList,
    ignoreProjectIdList = _ref2$ignoreProjectId === void 0 ? [] : _ref2$ignoreProjectId,
    _ref2$tableHeaderMap = _ref2.tableHeaderMap,
    tableHeaderMap = _ref2$tableHeaderMap === void 0 ? {} : _ref2$tableHeaderMap,
    _ref2$rumSecretList = _ref2.rumSecretList,
    rumSecretList = _ref2$rumSecretList === void 0 ? [] : _ref2$rumSecretList;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var parsedDate, headerDate, parsedPreDate, sortKeyList, data, preData, _iterator, _step, item, _yield$getRUMScoreLis, rumScores, preRumScores, _data$data, _preData$data, parsedData, parsedPreData, tableData, img, _t;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          parsedDate = timeStampFormat(new Date(date).getTime(), 'yyyyMMdd');
          headerDate = timeStampFormat(new Date(date).getTime(), 'yyyy-MM-dd');
          parsedPreDate = timeStampFormat(new Date(date).getTime() - 1 * 24 * 60 * 60 * 1000, 'yyyyMMdd');
          console.log('[genSummaryData] parsedDate: ', parsedDate);
          console.log('[genSummaryData] parsedPreDate: ', parsedPreDate);
          sortKeyList = Object.keys(tableHeaderMap);
          if (sortKeyList.length) {
            _context2.next = 1;
            break;
          }
          return _context2.abrupt("return");
        case 1:
          _context2.next = 2;
          return getTAMSummaryScoreByGroupIdList({
            date: parsedDate,
            groupIdList: groupIdList,
            secretInfo: secretInfo
          });
        case 2:
          data = _context2.sent;
          _context2.next = 3;
          return getTAMSummaryScoreByGroupIdList({
            date: parsedPreDate,
            groupIdList: groupIdList,
            secretInfo: secretInfo
          });
        case 3:
          preData = _context2.sent;
          console.log('[genSummaryData.rumSecretList]', rumSecretList);
          if (!(rumSecretList === null || rumSecretList === void 0 ? void 0 : rumSecretList.length)) {
            _context2.next = 11;
            break;
          }
          _iterator = _createForOfIteratorHelper(rumSecretList);
          _context2.prev = 4;
          _iterator.s();
        case 5:
          if ((_step = _iterator.n()).done) {
            _context2.next = 8;
            break;
          }
          item = _step.value;
          _context2.next = 6;
          return getRUMScoreList({
            secretInfo: item,
            parsedDate: parsedDate,
            parsedPreDate: parsedPreDate,
            date: date
          });
        case 6:
          _yield$getRUMScoreLis = _context2.sent;
          rumScores = _yield$getRUMScoreLis.rumScores;
          preRumScores = _yield$getRUMScoreLis.preRumScores;
          console.log('[genSummaryData.rumScores?.length]', rumScores === null || rumScores === void 0 ? void 0 : rumScores.length);
          if (rumScores) {
            (_data$data = data.data).push.apply(_data$data, _toConsumableArray(rumScores));
          }
          if (preRumScores) {
            (_preData$data = preData.data).push.apply(_preData$data, _toConsumableArray(preRumScores));
          }
        case 7:
          _context2.next = 5;
          break;
        case 8:
          _context2.next = 10;
          break;
        case 9:
          _context2.prev = 9;
          _t = _context2["catch"](4);
          _iterator.e(_t);
        case 10:
          _context2.prev = 10;
          _iterator.f();
          return _context2.finish(10);
        case 11:
          parsedData = parseSummaryScore({
            data: data.data,
            extraDataMap: extraDataMap,
            ignoreProjectIdList: ignoreProjectIdList,
            sortKeyList: sortKeyList
          });
          parsedPreData = parseSummaryScore({
            data: preData.data,
            extraDataMap: extraDataMap,
            ignoreProjectIdList: ignoreProjectIdList,
            sortKeyList: sortKeyList
          });
          saveJsonToLog(parsedData, 'summary.parsed-data.json');
          saveJsonToLog(parsedPreData, 'summary.parsed-data-pre.json');
          compareTwoList(parsedData, parsedPreData, 'ProjectName');
          tableData = getMaxAndMinIdx(parsedData);
          saveJsonToLog(tableData, 'summary.table-data.json');
          img = '';
          try {
            img = createCanvasTable({
              data: tableData,
              headers: getTableHeaders(tableData, tableHeaderMap),
              title: "TAM\u65E5\u62A5 ".concat(headerDate),
              cellWidthList: Object.values(tableHeaderMap).map(function (item) {
                return item.tableWidth || 65;
              })
            });
          } catch (err) {
            console.log('[genSummaryData.createCanvasTable.error]', err);
          }
          return _context2.abrupt("return", {
            img: img,
            data: data
          });
        case 12:
        case "end":
          return _context2.stop();
      }
    }, _callee2, null, [[4, 9, 10, 11]]);
  }));
}
/**
 * 生成TAM汇总数据并发送到机器人
 * @param {object} options 配置
 * @param {string} options.date 日期，yyyyMMdd格式
 * @param {Array<number>} options.groupIdList groupId列表
 *
 * @param {object} options.secretInfo 密钥信息
 * @param {string} options.secretInfo.apiKey apiKey
 * @param {string} options.secretInfo.loginName loginName
 * @param {Function} options.secretInfo.getPwdCode getPwdCode
 * @param {Function} options.secretInfo.encrypt encrypt
 *
 * @param {object} options.extraDataMap 额外数据Map
 * @param {object} options.ignoreProjectIdList 忽略的projectIdList
 * @param {object} options.tableHeaderMap 表格头部Map
 *
 * @param {object} options.webhookUrl 机器人回调地址
 * @param {object} options.chatId 会话Id
 *
 * @example
 * const requestSummaryScoreDate = Date.now() - 1 * 24 * 60 * 60 * 1000;
 *
 * const tamGroupIdList = [1, 2, 3];
 *
 * const summaryScoreTableHeaderMap = {
 *   ProjectName: {
 *     name: '项目名称',
 *     tableWidth: 95,
 *   },
 *   PagePv: {
 *     name: 'PV',
 *     tableWidth: 65,
 *   },
 * };
 *
 * await genSummaryDataAndSendRobot({
 *   date: requestSummaryScoreDate,
 *   groupIdList: tamGroupIdList,
 *   secretInfo: {
 *     getPwdCode,
 *     encrypt,
 *     apiKey: process.env.AEGIS_APP_KEY,
 *     loginName: 'lee',
 *   },
 *   webhookUrl: tamRobotWebhook,
 *   chatId: tamRobotChatId,
 *   tableHeaderMap: summaryScoreTableHeaderMap,
 * });
 */
function genSummaryDataAndSendRobot(_ref3) {
  var date = _ref3.date,
    groupIdList = _ref3.groupIdList,
    secretInfo = _ref3.secretInfo,
    _ref3$extraDataMap = _ref3.extraDataMap,
    extraDataMap = _ref3$extraDataMap === void 0 ? {} : _ref3$extraDataMap,
    _ref3$ignoreProjectId = _ref3.ignoreProjectIdList,
    ignoreProjectIdList = _ref3$ignoreProjectId === void 0 ? [] : _ref3$ignoreProjectId,
    _ref3$tableHeaderMap = _ref3.tableHeaderMap,
    tableHeaderMap = _ref3$tableHeaderMap === void 0 ? {} : _ref3$tableHeaderMap,
    webhookUrl = _ref3.webhookUrl,
    chatId = _ref3.chatId,
    _ref3$rumSecretList = _ref3.rumSecretList,
    rumSecretList = _ref3$rumSecretList === void 0 ? [] : _ref3$rumSecretList;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
    var result, img, data;
    return _regeneratorRuntime.wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          if (!rumSecretList.length && secretInfo.rumSecretId && secretInfo.rumSecretKey) {
            rumSecretList = [{
              rumSecretId: secretInfo.rumSecretId,
              rumSecretKey: secretInfo.rumSecretKey
            }];
          }
          _context3.next = 1;
          return genSummaryData({
            date: date,
            groupIdList: groupIdList,
            secretInfo: secretInfo,
            extraDataMap: extraDataMap,
            ignoreProjectIdList: ignoreProjectIdList,
            tableHeaderMap: tableHeaderMap,
            rumSecretList: rumSecretList
          });
        case 1:
          result = _context3.sent;
          if (result) {
            _context3.next = 2;
            break;
          }
          return _context3.abrupt("return");
        case 2:
          img = result.img, data = result.data;
          if (!(!img || !chatId)) {
            _context3.next = 3;
            break;
          }
          return _context3.abrupt("return", data);
        case 3:
          _context3.next = 4;
          return batchSendWxRobotBase64Img({
            img: img,
            webhookUrl: webhookUrl,
            chatId: chatId
          });
        case 4:
          return _context3.abrupt("return", data);
        case 5:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
}

export { genSummaryData, genSummaryDataAndSendRobot };
