import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _classCallCheck from '@babel/runtime/helpers/classCallCheck';
import _createClass from '@babel/runtime/helpers/createClass';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { _ as __awaiter } from '../tslib.es6-848120af.js';
import { formatBite } from '../bite/format-bite.mjs';
import { addTextForImg } from '../canvas/img-text.mjs';
import { getGitCommitInfo } from '../git/git.mjs';
import { saveBase64ImgToFile } from '../node-img/img.mjs';
import { getFs } from '../nodejs/fs.mjs';
import { getPath } from '../nodejs/path.mjs';
import { uploadCOSFile } from '../tencent-cloud/cos/cos.mjs';
import { getCosUrlLink } from '../tencent-cloud/cos/link.mjs';
import { getMiniprogramCi } from '../third-party/miniprogram-ci.mjs';
import { timeStampFormat } from '../time/time.mjs';
import { sendWxRobotMarkdown } from '../wecom-robot/base.mjs';
import { DEFAULT_BUILD_SETTING, MAX_TRY_TIMES_MAP, PREVIEW_IMG_MAX_WORD_LENGTH } from './config.mjs';
import { getBundleBuildDesc, getBundleVersion, parseUploadResult, flattenSubPackages } from './helper.mjs';
import '../third-party/image-size.mjs';
import '../canvas/get-canvas.mjs';
import '../third-party/canvas.mjs';
import '../node/node-command.mjs';
import '@babel/runtime/helpers/typeof';
import '../nodejs/child_process.mjs';
import '../validate/validate.mjs';
import '../nodejs/crypto.mjs';
import '../nodejs/request.mjs';
import '../tencent-cloud/cos/helper.mjs';
import '../third-party/cos-nodejs-sdk-v5.mjs';
import '../wecom-robot/helper.mjs';
import 'axios';
import '../wecom-robot/message.mjs';

function getFullPackageSize(result) {
  var obj = flattenSubPackages(result);
  return formatBite(obj.__FULL__.size);
}
function getMainPackageSize(result) {
  var obj = flattenSubPackages(result);
  return formatBite(obj.__APP__.size);
}
var MpCI = /*#__PURE__*/function () {
  /**
  * 小程序自动化构建工具
  * @param {object} options 选项
  *
  * @example
  *
  * const { MpCI, fetchRainbowConfig } = require('t-comm');
  *
  * const env = "${env}"
  * const branch = "${branch}"
  *
  * const root = "${WORKSPACE}";
  *
  * async function getCIConfig() {
  *   let res = {};
  *   const str = await fetchRainbowConfig('mp_ci', {
  *     appId: '',
  *     envName: 'x',
  *     groupName: 'x',
  *   });
  *   try {
  *     res = JSON.parse(str);
  *   } catch (err) {}
  *   return res;
  * }
  *
  * function getRobot(config = {}) {
  *   return config?.robotMap?.[branch]?.[env] || 1;
  * }
  *
  * async function main() {
  *   const config = await getCIConfig();
  *   console.log('config: \n', config, typeof config);
  *   const {
  *     appName,
  *     appId,
  *     webhookUrl,
  *     chatId,
  *     cosInfo,
  *   } = config;
  *
  *   const ci = new MpCI({
  *     appName,
  *     appId,
  *     root,
  *     env,
  *     robotNumber: getRobot(config),
  *
  *     webhookUrl,
  *     chatId,
  *
  *     cosInfo,
  *   });
  *
  *   await ci.upload();
  *   await ci.preview();
  *   await ci.sendRobotMsg();
  * }
  *
  * main();
  */
  function MpCI(options) {
    _classCallCheck(this, MpCI);
    this.webhookUrl = '';
    this.chatId = '';
    this.projectPath = '';
    this.privateKeyPath = '';
    this.buildDesc = '';
    this.version = '';
    this.errorLink = '';
    this.pagePath = '';
    this.searchQuery = '';
    this.tryTimesMap = {
      UPLOAD: 1,
      PREVIEW: 1
    };
    var ci = options.ci;
    if (!ci) {
      try {
        ci = getMiniprogramCi();
      } catch (err) {
        console.log('[MpCI] err', err);
      }
    }
    this.ciLib = ci;
    this.options = options;
    this.projectCI = null;
    this.previewResult = {
      subPackageInfo: []
    };
    this.savePreviewPath = getPath().resolve(process.cwd(), 'mp_ci_preview_destination.png');
    var appId = options.appId,
      appName = options.appName,
      projectPath = options.projectPath,
      privateKeyPath = options.privateKeyPath,
      ignores = options.ignores,
      type = options.type,
      root = options.root,
      env = options.env,
      robotNumber = options.robotNumber,
      buildSetting = options.buildSetting,
      webhookUrl = options.webhookUrl,
      chatId = options.chatId,
      cosInfo = options.cosInfo,
      errorLink = options.errorLink,
      pagePath = options.pagePath,
      searchQuery = options.searchQuery;
    this.appId = appId;
    this.appName = appName || '';
    this.type = type || 'miniProgram';
    this.pagePath = pagePath || '';
    this.searchQuery = searchQuery || '';
    this.root = root || process.cwd();
    this.ignores = ignores || ['node_modules/**/*'];
    this.pkgFile = getPath().resolve(this.root, './package.json');
    this.env = env || 'test';
    this.robotNumber = robotNumber || 30;
    this.webhookUrl = webhookUrl;
    this.chatId = chatId;
    this.buildSetting = Object.assign(Object.assign({}, DEFAULT_BUILD_SETTING), buildSetting || {});
    this.projectPath = projectPath || '';
    this.privateKeyPath = privateKeyPath || '';
    this.cosInfo = cosInfo || {};
    this.errorLink = errorLink || '';
    this.validateOptions();
    if (this.ciLib) {
      this.init();
    }
    this.initBaseInfo();
  }
  return _createClass(MpCI, [{
    key: "validateOptions",
    value: function validateOptions() {
      if (!this.projectPath) {
        this.projectPath = getPath().resolve(this.root, 'dist/build/mp-weixin');
      }
      if (!this.privateKeyPath) {
        this.privateKeyPath = getPath().resolve(this.root, 'private.key');
      }
      if (this.ciLib && !getFs().existsSync(this.privateKeyPath)) {
        throw new Error('ERROR: privateKeyPath 位置不存在');
      }
      if (!getFs().existsSync(this.projectPath)) {
        throw new Error('ERROR: projectPath 位置不存在');
      }
      // if (!getFs().existsSync(this.pkgFile)) {
      //   throw new Error('ERROR: package.json 不存在');
      // }
    }
  }, {
    key: "initBaseInfo",
    value: function initBaseInfo() {
      this.getBuildTime();
      if (!this.options.commitInfo) {
        this.commitInfo = getGitCommitInfo(this.root, false, false, false);
      } else {
        this.commitInfo = this.options.commitInfo;
      }
      if (!this.options.buildDesc) {
        this.buildDesc = getBundleBuildDesc({
          root: this.root,
          env: this.env
        }) || '';
      } else {
        this.buildDesc = this.options.buildDesc;
      }
      if (!this.options.version) {
        this.version = getBundleVersion(this.root);
      } else {
        this.version = this.options.version;
      }
    }
  }, {
    key: "init",
    value: function init() {
      var appId = this.appId,
        projectPath = this.projectPath,
        privateKeyPath = this.privateKeyPath,
        ignores = this.ignores,
        type = this.type;
      this.projectCI = new this.ciLib.Project({
        appid: appId,
        type: type,
        projectPath: projectPath,
        privateKeyPath: privateKeyPath,
        ignores: ignores
      });
    }
  }, {
    key: "getBuildTime",
    value: function getBuildTime() {
      this.buildTime = timeStampFormat(Date.now(), 'yyyy-MM-dd hh:mm:ss');
    }
    /**
     * 上传
     */
  }, {
    key: "upload",
    value: function upload() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _t;
        return _regeneratorRuntime.wrap(function (_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              _context.prev = 0;
              _context.next = 1;
              return this.tryUpload();
            case 1:
              _context.next = 5;
              break;
            case 2:
              _context.prev = 2;
              _t = _context["catch"](0);
              if (!(this.tryTimesMap.UPLOAD < MAX_TRY_TIMES_MAP.UPLOAD)) {
                _context.next = 4;
                break;
              }
              this.tryTimesMap.UPLOAD += 1;
              _context.next = 3;
              return this.tryUpload();
            case 3:
              _context.next = 5;
              break;
            case 4:
              throw new Error(_t);
            case 5:
            case "end":
              return _context.stop();
          }
        }, _callee, this, [[0, 2]]);
      }));
    }
  }, {
    key: "tryUpload",
    value: function tryUpload() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var robotNumber, version, buildDesc, uploadResult;
        return _regeneratorRuntime.wrap(function (_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              robotNumber = this.robotNumber, version = this.version, buildDesc = this.buildDesc;
              _context2.next = 1;
              return this.ciLib.upload({
                project: this.projectCI,
                version: version,
                desc: buildDesc,
                robot: robotNumber,
                setting: this.buildSetting
              });
            case 1:
              uploadResult = _context2.sent;
              this.getBuildTime();
              _context2.next = 2;
              return this.ciLib.getDevSourceMap({
                project: this.projectCI,
                robot: robotNumber,
                sourceMapSavePath: './sm.zip'
              });
            case 2:
              console.log('[MpCI] UploadResult:\n', uploadResult);
            case 3:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
    }
  }, {
    key: "preview",
    value: function preview() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        return _regeneratorRuntime.wrap(function (_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              _context3.prev = 0;
              _context3.next = 1;
              return this.tryPreview();
            case 1:
              _context3.next = 3;
              break;
            case 2:
              _context3.prev = 2;
              _context3["catch"](0);
              if (!(this.tryTimesMap.UPLOAD < MAX_TRY_TIMES_MAP.UPLOAD)) {
                _context3.next = 3;
                break;
              }
              this.tryTimesMap.UPLOAD += 1;
              _context3.next = 3;
              return this.tryPreview();
            case 3:
            case "end":
              return _context3.stop();
          }
        }, _callee3, this, [[0, 2]]);
      }));
    }
    /**
     * 预览
     */
  }, {
    key: "tryPreview",
    value: function tryPreview() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee4() {
        var previewParam, previewResult;
        return _regeneratorRuntime.wrap(function (_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              previewParam = {
                project: this.projectCI,
                desc: this.buildDesc,
                setting: this.buildSetting,
                qrcodeFormat: 'image',
                qrcodeOutputDest: this.savePreviewPath,
                robot: this.robotNumber,
                pagePath: this.pagePath || undefined,
                searchQuery: this.searchQuery || undefined
                // pagePath: 'pages/index/index', // 预览页面
                // searchQuery: 'a=1&b=2',  // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`&`
              };
              _context4.next = 1;
              return this.ciLib.preview(previewParam);
            case 1:
              previewResult = _context4.sent;
              console.log('[MpCI] PreviewResult:\n', previewResult);
              this.previewResult = previewResult;
              _context4.next = 2;
              return this.uploadPreviewImg(previewResult);
            case 2:
            case "end":
              return _context4.stop();
          }
        }, _callee4, this);
      }));
    }
    /**
     * 上传预览图片到COS
     */
  }, {
    key: "uploadPreviewImg",
    value: function uploadPreviewImg(previewResult) {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
        var robotNumber, env, buildTime, commitInfo, version, textList, newPreviewImg;
        return _regeneratorRuntime.wrap(function (_context5) {
          while (1) switch (_context5.prev = _context5.next) {
            case 0:
              robotNumber = this.robotNumber, env = this.env, buildTime = this.buildTime, commitInfo = this.commitInfo, version = this.version;
              textList = ['[CI RESULT]', "VERSION: ".concat(version), "UPLOADER: CI ROBOT ".concat(robotNumber), "ENV: ".concat(env), "BRANCH: ".concat(commitInfo.branch), "BUILD TIME: ".concat(buildTime), "LAST COMMIT: ".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash)].concat(_toConsumableArray(parseUploadResult(previewResult))).map(function (item) {
                if (item.length > PREVIEW_IMG_MAX_WORD_LENGTH) return "".concat(item.slice(0, PREVIEW_IMG_MAX_WORD_LENGTH), "...");
                return item;
              });
              _context5.next = 1;
              return addTextForImg({
                width: 300,
                height: 300,
                imgPath: this.savePreviewPath,
                textList: textList
              });
            case 1:
              newPreviewImg = _context5.sent;
              _context5.next = 2;
              return saveBase64ImgToFile({
                imgUrl: newPreviewImg,
                savePath: this.savePreviewPath
              });
            case 2:
              this.uploadFiles([{
                key: this.getCosKey(),
                path: this.savePreviewPath
              }]);
            case 3:
            case "end":
              return _context5.stop();
          }
        }, _callee5, this);
      }));
    }
  }, {
    key: "getCosKey",
    value: function getCosKey() {
      var cosInfo = this.cosInfo,
        env = this.env,
        commitInfo = this.commitInfo;
      return "".concat(cosInfo.dir, "/").concat(commitInfo.branch.replace(/\//g, '-'), "_").concat(env, ".png");
    }
  }, {
    key: "getCOSFilePath",
    value: function getCOSFilePath() {
      var _this$cosInfo = this.cosInfo,
        bucket = _this$cosInfo.bucket,
        region = _this$cosInfo.region;
      var cosKey = this.getCosKey();
      return getCosUrlLink({
        bucket: bucket,
        region: region,
        dir: '',
        fileName: cosKey
      });
    }
    /**
     * 发送机器人消息
     */
  }, {
    key: "sendRobotMsg",
    value: function sendRobotMsg() {
      var hasImg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
        var robotNumber, webhookUrl, env, commitInfo, version, previewResult, appName, chatId, descList, buildUrl, template;
        return _regeneratorRuntime.wrap(function (_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              robotNumber = this.robotNumber, webhookUrl = this.webhookUrl, env = this.env, commitInfo = this.commitInfo, version = this.version, previewResult = this.previewResult, appName = this.appName;
              chatId = this.chatId;
              if (webhookUrl) {
                _context6.next = 1;
                break;
              }
              return _context6.abrupt("return");
            case 1:
              if (!chatId) {
                chatId = undefined;
              }
              descList = ["\u5206\u652F\uFF1A".concat(commitInfo.branch), "\u73AF\u5883\uFF1A".concat(env), "\u7248\u672C\uFF1A".concat(version || ''), "\u673A\u5668\u4EBA\uFF1A".concat(robotNumber), "\u6700\u540E\u63D0\u4EA4: ".concat(commitInfo.author, " - ").concat(commitInfo.message, " - ").concat(commitInfo.hash), "\u603B\u5305\uFF1A".concat(getFullPackageSize(previewResult)), "\u4E3B\u5305\uFF1A".concat(getMainPackageSize(previewResult)) // `${buildTime || ''}`,
              ];
              if (hasImg) {
                descList.push("[\u9884\u89C8\u56FE\u7247](".concat(this.getCOSFilePath(), ")"));
              }
              buildUrl = process.env.BK_CI_BUILD_URL;
              if (buildUrl) {
                descList.push("[\u6784\u5EFA\u5730\u5740](".concat(buildUrl, ")"));
              }
              template = "> \u2705\u3010".concat(appName || '', " WX MP\u3011").concat(descList.join('，'));
              sendWxRobotMarkdown({
                webhookUrl: webhookUrl,
                content: template,
                chatId: chatId
              });
            case 2:
            case "end":
              return _context6.stop();
          }
        }, _callee6, this);
      }));
    }
  }, {
    key: "uploadAndPreview",
    value: function uploadAndPreview() {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee7() {
        var webhookUrl, errorLink, commitInfo, env, appName, chatId, descList, errorContent, _t3;
        return _regeneratorRuntime.wrap(function (_context7) {
          while (1) switch (_context7.prev = _context7.next) {
            case 0:
              _context7.prev = 0;
              _context7.next = 1;
              return Promise.all([this.upload(), this.preview()]);
            case 1:
              _context7.next = 4;
              break;
            case 2:
              _context7.prev = 2;
              _t3 = _context7["catch"](0);
              console.log('[MpCI] err', _t3);
              webhookUrl = this.webhookUrl, errorLink = this.errorLink, commitInfo = this.commitInfo, env = this.env, appName = this.appName;
              chatId = this.chatId;
              if (webhookUrl) {
                _context7.next = 3;
                break;
              }
              return _context7.abrupt("return");
            case 3:
              if (!chatId) {
                chatId = undefined;
              }
              descList = ["\u5206\u652F\uFF1A".concat(commitInfo.branch), "\u73AF\u5883\uFF1A".concat(env), _t3.toString()];
              errorContent = "".concat(errorLink ? "[".concat(appName || '', "\u6784\u5EFA\u5931\u8D25](").concat(errorLink, ")") : '').concat(descList.join('，'));
              sendWxRobotMarkdown({
                webhookUrl: webhookUrl,
                content: errorContent,
                chatId: chatId
              });
            case 4:
            case "end":
              return _context7.stop();
          }
        }, _callee7, this, [[0, 2]]);
      }));
    }
  }, {
    key: "uploadFiles",
    value: function uploadFiles(files) {
      return __awaiter(this, void 0, void 0, /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
        var _ref, secretId, secretKey, bucket, region;
        return _regeneratorRuntime.wrap(function (_context8) {
          while (1) switch (_context8.prev = _context8.next) {
            case 0:
              _ref = this.cosInfo || {}, secretId = _ref.secretId, secretKey = _ref.secretKey, bucket = _ref.bucket, region = _ref.region;
              _context8.next = 1;
              return uploadCOSFile({
                files: files,
                secretId: secretId,
                secretKey: secretKey,
                bucket: bucket,
                region: region
              });
            case 1:
            case "end":
              return _context8.stop();
          }
        }, _callee8, this);
      }));
    }
  }]);
}();

export { MpCI };
