const ci = require("miniprogram-ci");
const path = require("path");

/**
 * 获取环境参数
 * type 操作类型 preview | publish
 * version:版本号 上传操作必填
 * desc:版本描述  上传操作必填
 * appid:应用id,测试人员有时需要切换应用Id
 * buildId: 构建id
 */
let { type="preview", version = "", desc = "", appid = "wxe16bf9293671506c", buildId = "43", env = "prod" } = getEnvParams(
  process.argv
);

console.log(process.argv);

const ENVMAP = {
  prod: "build",
  dev: "dev"
};

const build = ENVMAP[env];

// 请求参数
const reqParams = {
  appid,
  type: "miniProgram",
  projectPath: path.resolve(__dirname, `./dist/${build}/mp-weixin`), //项目路径
  privateKeyPath: path.resolve(__dirname, `./build/key/private.${appid}.key`), //小程序后台的上传密匙
  ignores: ["node_modules/**/*"]
};
// 上传文件处理设置参数
const uploadParams = {
  urlCheck: true,
  postcss: true,
  minified: true,
  babelSetting: {
    ignore: [],
    disablePlugins: [],
    outputPath: ""
  }
};

const project = new ci.Project({ ...reqParams });

// 任何时候都生成二维码
(async() => {
  const previewResult = await ci.preview({
    project,
    desc: "预览", // 此备注将显示在“小程序助手”开发版列表中
    setting: uploadParams,
    qrcodeFormat: "image",
    qrcodeOutputDest: `./build/qrcode-${buildId}.jpg`
    // onProgressUpdate: console.log,
    // pagePath: 'pages/index/index', // 预览页面
    // searchQuery: 'a=1&b=2',  // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`\&`
  });
  console.log(previewResult);
})();

if (type === "publish") {
  (async () => {
    const uploadResult = await ci.upload({
      project,
      version,
      desc,
      setting: uploadParams
      // onProgressUpdate: console.log,
    });
    console.log(uploadResult);
  })();
}

/**
 * 获取node命令行参数
 * @param {array} options 命令行数组
 */
function getEnvParams(options) {
  let envParams = {};
  // 从第三个参数开始,是自定义参数
  for (let i = 2, len = options.length; i < len; i++) {
    let arg = options[i].split("=");
    envParams[arg[0]] = arg[1];
  }
  return envParams;
}
