const path = require('path');
const fs = require('fs');
const fsextra = require('fs-extra');
const { execSync } = require('child_process');
const { dirOptions } = require('./options');

const consoleColor = '\x1B[31m%s\x1b[0m';

const gitAddrMap = {
  H5: 'git@git.quantgroup.cn:ui/vue-standard-h5-project.git',
  PC: 'git@git.quantgroup.cn:ui/vue-standard-h5-project.git'
}

// 创建目录
function createDir (projectName, options) {
  console.log(options);
  fs.mkdir(`./${projectName}`, function (err) {
    if (err) {
      console.log(consoleColor, '创建失败')
      return;
    }
  })
  const { projectType } = options;
  if (projectType && gitAddrMap[projectType]) {
    console.log(gitAddrMap[projectType])
    execSync(`cd ${projectName} && git clone ${gitAddrMap[projectType]} './' && npm install --registry=http://npmprivate.quantgroups.com`, {
      stdio: [2, 2, 2],
      shell: process.platform === 'win32'
    })
  }
}
// 替换package.json的内容
function replacePackageJsonContent() {}

const createProject = async (projectName, cmd, options) => {
  const cwd = process.cwd(); // 获取当前命令执行时的工作目录
  const targetDir = path.join(cwd,projectName); // 目标目录
  if (fsextra.existsSync(targetDir)) {
    // 目录已创建
    if (cmd.force) {
      // 删除目标目录并创建
      await fsextra.remove(targetDir);
      createDir(projectName, options)
    } else {
      // 提示选择是否覆盖创建
      const { dirOperation } = await dirOptions();
      if (+dirOperation === 1) {
        await fsextra.remove(targetDir);
        createDir(projectName, options)
        return;
      }
      return;
    }
  } else {
    // 目录未创建，直接创建目录即可
    createDir(projectName, options);
  }
};

module.exports = {
  createProject
}