import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { formatBite } from '../bite/format-bite.mjs';
import { compressBase64Img } from '../canvas/compress-img.mjs';
import { readFileSync } from '../fs/fs.mjs';
import { getGitCommitInfo } from '../git/git.mjs';
import { getComponentInfo, getPageTotal } from '../mp/page-total.mjs';
import { getPath } from '../nodejs/path.mjs';
import { timeStampFormat } from '../time/time.mjs';
import { batchSendWxRobotBase64Img, batchSendWxRobotMarkdown } from '../wecom-robot/batch-send.mjs';
import '../canvas/get-canvas.mjs';
import '../third-party/canvas.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/fs.mjs';
import '../nodejs/os.mjs';
import '../node/node-command.mjs';
import '@babel/runtime/helpers/typeof';
import '../nodejs/child_process.mjs';
import '../validate/validate.mjs';
import '../fs/fs-util.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';

function parsePreviewResult(subPackageInfo) {
  var maxSubPackageNum = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
  var subPackagesList = [];
  try {
    subPackagesList = JSON.parse(subPackageInfo);
  } catch (err) {}
  var previewMap = subPackagesList.reduce(function (acc, item) {
    return Object.assign(Object.assign({}, acc), _defineProperty({}, item.name, item.size));
  }, {});
  var keyList = Object.keys(previewMap).filter(function (item) {
    return !['__APP__', '__FULL__'].includes(item);
  });
  keyList.sort(function (a, b) {
    return previewMap[b] - previewMap[a];
  });
  keyList = keyList.slice(0, maxSubPackageNum);
  var list = ["\u4E3B\u5305: `".concat(formatBite(previewMap.__APP__), "`"), "\u603B\u5305: `".concat(formatBite(previewMap.__FULL__), "`")].concat(_toConsumableArray(keyList.map(function (key) {
    return "".concat(key.replace(/^\/|\/$/g, ''), ": `").concat(formatBite(previewMap[key]), "`");
  })));
  return list.join('，');
}
var getRobotMessageItem = function getRobotMessageItem(key, value) {
  var isLight = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  if (isLight) {
    return "".concat(key, "\uFF1A`").concat(value, "`");
  }
  return "".concat(key, "\uFF1A").concat(value);
};
function getDescMap(_ref) {
  var robot = _ref.robot,
    root = _ref.root,
    env = _ref.env,
    branch = _ref.branch;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var commitInfo, version, time, descMap;
    return _regeneratorRuntime.wrap(function (_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          commitInfo = getGitCommitInfo(root, false, false, false);
          version = '';
          try {
            version = readFileSync(getPath().resolve(root, './package.json'), true).version;
          } catch (err) {}
          time = timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss');
          descMap = {
            branch: {
              title: '分支',
              content: "".concat(branch || commitInfo.branch)
            },
            env: {
              title: '环境',
              content: "".concat(env)
            },
            robot: {
              title: '机器人',
              content: "".concat(robot)
            },
            version: {
              title: '版本',
              content: "".concat(version) || ''
            },
            lastCommit: {
              title: '最后提交',
              content: "".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash || '')
            },
            time: {
              title: '时间',
              content: "".concat(time)
            }
          };
          console.log('[CI] descMap: ', descMap);
          return _context.abrupt("return", descMap);
        case 1:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
}
function getDescList(_ref2) {
  var bundleResult = _ref2.bundleResult,
    subPackageInfo = _ref2.subPackageInfo,
    robot = _ref2.robot,
    root = _ref2.root,
    env = _ref2.env,
    branch = _ref2.branch;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
    var descMap, branchInfo, envInfo, robotInfo, versionInfo, lastCommitInfo, componentInfo, pageInfo, _componentInfo$compon, componentTotal, _componentInfo$wxmlSi, wxmlSizeTotal, _componentInfo$wxssSi, wxssSizeTotal, _componentInfo$jsSize, jsSizeTotal, _componentInfo$vendor, vendorJsSize, _pageInfo$pageTotal, pageTotal, _pageInfo$subPackageT, subPackageTotal;
    return _regeneratorRuntime.wrap(function (_context2) {
      while (1) switch (_context2.prev = _context2.next) {
        case 0:
          _context2.next = 1;
          return getDescMap({
            robot: robot,
            root: root,
            env: env,
            branch: branch
          });
        case 1:
          descMap = _context2.sent;
          branchInfo = descMap.branch, envInfo = descMap.env, robotInfo = descMap.robot, versionInfo = descMap.version, lastCommitInfo = descMap.lastCommit;
          componentInfo = getComponentInfo(bundleResult);
          pageInfo = getPageTotal(bundleResult);
          _componentInfo$compon = componentInfo.componentTotal, componentTotal = _componentInfo$compon === void 0 ? 0 : _componentInfo$compon, _componentInfo$wxmlSi = componentInfo.wxmlSizeTotal, wxmlSizeTotal = _componentInfo$wxmlSi === void 0 ? 0 : _componentInfo$wxmlSi, _componentInfo$wxssSi = componentInfo.wxssSizeTotal, wxssSizeTotal = _componentInfo$wxssSi === void 0 ? 0 : _componentInfo$wxssSi, _componentInfo$jsSize = componentInfo.jsSizeTotal, jsSizeTotal = _componentInfo$jsSize === void 0 ? 0 : _componentInfo$jsSize, _componentInfo$vendor = componentInfo.vendorJsSize, vendorJsSize = _componentInfo$vendor === void 0 ? 0 : _componentInfo$vendor;
          _pageInfo$pageTotal = pageInfo.pageTotal, pageTotal = _pageInfo$pageTotal === void 0 ? 0 : _pageInfo$pageTotal, _pageInfo$subPackageT = pageInfo.subPackageTotal, subPackageTotal = _pageInfo$subPackageT === void 0 ? 0 : _pageInfo$subPackageT;
          return _context2.abrupt("return", [[getRobotMessageItem(branchInfo.title, branchInfo.content, true), getRobotMessageItem(envInfo.title, envInfo.content, true), getRobotMessageItem(robotInfo.title, robotInfo.content, true), getRobotMessageItem(versionInfo.title, versionInfo.content, true), "[\u6784\u5EFA\u5730\u5740](".concat(process.env.BK_CI_BUILD_URL || '', ")"), getRobotMessageItem(lastCommitInfo.title, lastCommitInfo.content, false)].join('，'), "- ".concat([getRobotMessageItem('页面数', pageTotal, true), getRobotMessageItem('组件数', componentTotal, true), getRobotMessageItem('分包数', subPackageTotal, true)].join('，')), "- ".concat([getRobotMessageItem('JS总大小', formatBite(jsSizeTotal), true), getRobotMessageItem('Vendor大小', formatBite(vendorJsSize), true), getRobotMessageItem('样式总大小', formatBite(wxssSizeTotal), true), getRobotMessageItem('WXML总大小', formatBite(wxmlSizeTotal), true)].join('，')), "- ".concat(parsePreviewResult(subPackageInfo, 5))]);
        case 2:
        case "end":
          return _context2.stop();
      }
    }, _callee2);
  }));
}
function sendWxMpCIMessageAfterPlugin(_ref3) {
  var appName = _ref3.appName,
    webhookUrl = _ref3.webhookUrl,
    previewCodeBase64Path = _ref3.previewCodeBase64Path,
    bundleResult = _ref3.bundleResult,
    subPackageInfo = _ref3.subPackageInfo,
    robot = _ref3.robot,
    root = _ref3.root,
    env = _ref3.env,
    branch = _ref3.branch,
    _ref3$compressOptions = _ref3.compressOptions,
    compressOptions = _ref3$compressOptions === void 0 ? {
      maxWidth: 280,
      quality: 0.8
    } : _ref3$compressOptions;
  return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
    var descList, content, previewCodeBase64P, compressedImg;
    return _regeneratorRuntime.wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          if (webhookUrl) {
            _context3.next = 1;
            break;
          }
          return _context3.abrupt("return");
        case 1:
          _context3.next = 2;
          return getDescList({
            bundleResult: bundleResult,
            subPackageInfo: subPackageInfo,
            robot: robot,
            root: root,
            env: env,
            branch: branch
          });
        case 2:
          descList = _context3.sent;
          content = "> \u2705\u3010".concat(appName, " WX MP\u3011").concat(descList.join('\n'));
          _context3.next = 3;
          return batchSendWxRobotMarkdown({
            webhookUrl: webhookUrl,
            chatId: 'ALL',
            content: content
          });
        case 3:
          previewCodeBase64P = readFileSync(previewCodeBase64Path);
          if (previewCodeBase64P) {
            _context3.next = 4;
            break;
          }
          return _context3.abrupt("return");
        case 4:
          _context3.next = 5;
          return compressBase64Img(previewCodeBase64P, compressOptions);
        case 5:
          compressedImg = _context3.sent;
          _context3.next = 6;
          return batchSendWxRobotBase64Img({
            img: compressedImg,
            chatId: 'ALL',
            webhookUrl: webhookUrl
          });
        case 6:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
}

export { sendWxMpCIMessageAfterPlugin };
