const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");

const inquirer = require("inquirer");

const { createManifestConfig } = require("./manifest");
const getEnvList = require("./getQaInfo");

const CUSTOM_FILE_ROOT = path.join("./customization");
console.log("jhb", path, CUSTOM_FILE_ROOT);
const ENV_MAP = {
  dev: "测试",
  prod: "生产",
};

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

const appIdMap = [];
let optionMap = [];
let envMap = [
  {
    key: "development",
    value: "development",
    name: "测试环境",
  },
  {
    key: "pre",
    value: "pre",
    name: "预发布环境",
  },
  {
    key: "production",
    value: "production",
    name: "生产环境",
  },
];
let currentData = {};

// 选择appid
const getOption = async () => {
  const optionInfo = [
    {
      type: "list",
      name: "projectIndex",
      default: "",
      message: "请选择小程序",
      choices: optionMap,
      filter(val) {
        return val;
      },
    },
  ];
  return inquirer.prompt(optionInfo);
};
// 选择api env
const setApiEnv = async () => {
  const envMapInfo = [
    {
      type: "list",
      name: "projectIndex",
      default: "",
      message: "请选择接口运行环境",
      choices: envMap,
      filter(val) {
        return val;
      },
    },
  ];
  return inquirer.prompt(envMapInfo);
};

// 写入配置信息
const setAppConfig = async (config) => {
  const configData = config.config || {};
  const filePath = path.resolve(process.cwd(), "./src/config/config.json");
  let configStr = `${JSON.stringify(configData)}`;

  try {
    fs.statSync(filePath).isFile();
  } catch (err) {
    fs.appendFileSync(filePath, configStr);
  }
  fs.writeFileSync(filePath, configStr, {});
  createManifestConfig(
    config.config.tenantName,
    config.appId,
    config.config.mp
  );
  return config.env;
};

// 获取配置信息
const getAllConfig = async () => {
  const dirs = fs.readdirSync(CUSTOM_FILE_ROOT);
  dirs.forEach((node) => {
    const childrenNode = fs.readdirSync(`${CUSTOM_FILE_ROOT}/${node}`);
    if (!childrenNode) return;
    childrenNode.forEach((childNode) => {
      const basename = path.basename(childNode, ".js").split("-");
      appIdMap.push({
        appId: basename[1],
        env: basename[0],
        config: require(path.resolve(
          `${CUSTOM_FILE_ROOT}/${node}/${childNode}`
        )),
        // config: fs.readFileSync(`${CUSTOM_FILE_ROOT}/${node}/${childNode}`, 'utf-8')
      });
    });
  });
  optionMap = appIdMap.map((item, index) => {
    return {
      name: `【${ENV_MAP[item.env]}】${item.config.appName}-${
        item.config.tenantName
      }-${item.appId}`,
      value: index,
      key: index,
    };
  });
};

// 执行编译命令
const execShell = (env, apiEnv, mpConfig) => {
  process.env.VUE_APP_API_ENV = apiEnv;
  const cmdStr = `${process.platform === "win32" ? "npm.cmd" : "npm"} run ${
    ENV_MENT[env]
  }:${mpConfig.mp}`;
  const cmdArr = cmdStr.split(" ");
  spawn(cmdArr[0], [cmdArr[1], cmdArr[2]], {
    stdio: [2, 2, 2],
  });
};

const run = async () => {
  await getAllConfig();
  const { projectIndex } = await getOption();
  currentData = appIdMap;
  const selectEnv = await setApiEnv();
  const mpConfig = currentData[projectIndex];
  const env = await setAppConfig(mpConfig);
  getEnvList();
  execShell(env, selectEnv.projectIndex, mpConfig.config);
};

run();
