const fs = require("fs");
const path = require("path");
const ci = require("miniprogram-ci");
const execSync = require("child_process").execSync;

const distDir = path.resolve(__dirname, "../dist");

// 实例化小程序 ci
const project = new ci.Project({
  appid: "wx090cc3b016e45bfe",
  type: "miniProgram",
  projectPath: path.resolve(distDir, "./build/mp-weixin"),
  privateKeyPath: path.resolve(__dirname, "./private.wx090cc3b016e45bfe.key"),
  ignores: [],
});

const gitCommitMsg = execSync("git log --pretty=format:“%s” -1")
  .toString()
  .trim()
  .replace(/(^["“])|(["”]$)/g, "");
const gitCommitName = execSync("git log --pretty=format:“%cn” -1")
  .toString()
  .trim()
  .replace(/(^["“])|(["”]$)/g, "");

let desc = `${gitCommitName}: ${gitCommitMsg}`;

if (process.env.change_desc && process.env.operator) {
  desc = `${process.env.operator}: ${process.env.change_desc}`;
}

const onProgressUpdate = (taskStatus) => {
  switch (taskStatus._status) {
    case "doing":
      console.log("上传中: ", taskStatus._msg);
      break;
    case "done":
      console.log("上传完成: ", taskStatus._msg);
      break;
  }
};

// 测试环境用开发版，不上传至小程序后台
const preview = async () => {
  try {
    fs.mkdirSync(path.resolve(distDir, `./qrcode`));
  } catch (e) {}

  await ci.preview({
    project,
    desc,
    setting: {},
    qrcodeFormat: "image",
    qrcodeOutputDest: path.resolve(distDir, `./qrcode/preview.jpg`),
    onProgressUpdate,
    pagePath: "pages/index/index", // 预览页面
    // searchQuery: 'a=1&b=2',  // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`\&`
  });

  console.log(
    "小程序上传完成🚀 ",
    path.resolve(distDir, `./qrcode/preview.jpg`)
  );
};

// 正式环境用体验版，上传至小程序后台
const publish = async () => {
  const version =
    process.env.MP_VERSON || process.env.version
      ? `1.0.${process.env.version}`
      : "1.0.0";
  try {
    const uploadResult = await ci.upload({
      project,
      version,
      desc,
      setting: {},
      onProgressUpdate,
    });
    console.log("小程序上传完成🚀 ", uploadResult);
  } catch (e) {
    console.info("上传出错，请检查网络或过会再试 ❌", e);
    throw new Error(e);
  }
};

(async () => {
  if (process.argv.includes("--publish")) {
    console.log("发布小程序🚀");
    publish();
  } else {
    console.log("上传预览小程序🚀");
    preview();
  }
})();
