"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
// import inquirer from 'inquirer'
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const git_1 = require("../../utils/git");
const npm_1 = require("../../utils/npm");
const file_1 = require("../../utils/file");
const shell = require('shelljs');
const inquirer = require('inquirer');
const fsEx = require('fs-extra');
// 更新r3项目依赖
function updateR3Dependencies() {
    return __awaiter(this, void 0, void 0, function* () {
        const R3Version = yield (0, npm_1.getPackageLatestVersion)('@syman/burgeon-r3');
        const ARKVersion = yield (0, npm_1.getPackageLatestVersion)('@syman/ark-ui');
        const BCLVersion = yield (0, npm_1.getPackageLatestVersion)('@syman/ark-ui-bcl');
        let writePath = path_1.default.resolve(process.cwd(), './index.html');
        yield (0, file_1.ejsWriteFile)(writePath, writePath, {
            R3_VERSION: R3Version,
            BCL_VERSION: BCLVersion,
            ARK_VERSION: ARKVersion,
        });
        writePath = path_1.default.resolve(process.cwd(), './package.json');
        yield (0, file_1.ejsWriteFile)(writePath, writePath, {
            R3_VERSION: R3Version,
            ARK_VERSION: ARKVersion,
        });
    });
}
// 更新r3项目依赖
function updateArkUiDependencies() {
    return __awaiter(this, void 0, void 0, function* () {
        const ARKVersion = yield (0, npm_1.getPackageLatestVersion)('@syman/ark-ui');
        const writePath = path_1.default.resolve(process.cwd(), './index.html');
        yield (0, file_1.ejsWriteFile)(writePath, writePath, {
            ARK_VERSION: ARKVersion,
        });
    });
}
const templateList = {
    r3: {
        name: 'r3框架项目',
        git: 'https://gitee.com/bojun_front_end/r3-project-template.git',
        branch: 'r3-template',
        script: 'npm start',
        updateDependencies: updateR3Dependencies,
    },
    'ark-ui': {
        name: 'ark-ui项目',
        git: 'https://gitee.com/bojun_front_end/r3-project-template.git',
        branch: 'ark-ui-template',
        script: 'npm start',
        updateDependencies: updateArkUiDependencies,
    },
};
// init命令执行逻辑
function execInit() {
    return __awaiter(this, void 0, void 0, function* () {
        const templateChoices = Object.keys(templateList).map((key) => {
            return {
                name: templateList[key].name,
                value: key,
            };
        });
        const { projectName } = yield inquirer.prompt({
            type: 'input',
            name: 'projectName',
            message: '请输入项目名称',
            validate: function (value) {
                const done = this.async();
                // 检查是否输入项目名称
                if (!value) {
                    done('项目名称不能空，请重新输入');
                }
                // 检查是否含有中文
                if (/[\u4e00-\u9fa5]/.test(value)) {
                    done('项目名称不能包含中文，请重新输入');
                }
                // 校验项目名称是否重复
                if (fsEx.pathExistsSync(value)) {
                    done('项目名称已存在，请重新输入');
                }
                else {
                    done(null, true);
                }
            },
        });
        const { template } = yield inquirer.prompt({
            type: 'list',
            name: 'template',
            message: '请选择模板',
            choices: [...templateChoices],
        });
        // 调试
        if (process.env.debug) {
            console.log(chalk_1.default.yellow(`debug: 已选择模板:${template}`));
            console.log(chalk_1.default.yellow(`debug: 执行git操作: git clone ${templateList[template].git} -b ${templateList[template].branch}`));
        }
        // 下载模板
        const spinner = (0, ora_1.default)('正在下载模板，请稍等...').start();
        console.log('');
        const createStatus = (0, git_1.downloadRepo)(templateList[template], {}, projectName);
        if (!createStatus) {
            spinner.fail(chalk_1.default.red('模板下载失败'));
            return;
        }
        spinner.succeed(chalk_1.default.green('模板下载成功'));
        // 去掉模板里的git
        shell.cd(projectName);
        shell.rm('-rf', '.git');
        // 检查依赖是否需要更新
        spinner.start('正在更新模板依赖版本，请稍等...');
        yield templateList[template].updateDependencies();
        spinner.succeed(chalk_1.default.green('模板依赖版本更新成功'));
        // 安装项目依赖
        spinner.start('开始安装所需依赖，请稍等...');
        console.log('');
        const { status: installStatus } = (yield (0, npm_1.npm)(['install']));
        if (installStatus === 0) {
            spinner.succeed(chalk_1.default.green('依赖安装成功'));
            console.log('');
            console.log('使用如下命令可运行项目：');
            console.log('');
            console.log(chalk_1.default.blue(`cd ${projectName}`)); // 进入项目根目录
            console.log(chalk_1.default.blue(templateList[template].script)); // 执行启动脚本
            console.log('');
        }
        else {
            spinner.fail(chalk_1.default.red('依赖安装失败'));
        }
    });
}
exports.default = execInit;
//# sourceMappingURL=data:application/json;base64, 