const path = require('path');
const consola = require('consola');
const { exec } = require('child_process');

const Fs = require('./fs');

class Index {
    constructor() {
        this.fs = new Fs();
    }

    start() {
        // console.log('argv', argv);
        console.log('✨ Start');
        this.command = process.argv[2];
        this.appname = process.argv[3];
        this.initConfig();
        const check = this.checkCommand();
        if (check) {
            consola.success(`参数校验完成`);
            this.executeCommand();
        }
    }

    initConfig() {
        consola.info('正在初始化配置');
        try {
            const string = this.fs.readFile(
                path.join(__dirname, '../config/index.json')
            );
            this.appConfig = JSON.parse(string);
        } catch (error) {
            consola.error('初始化失败, 错误信息如下：', error);
        }
    }

    checkCommand() {
        consola.success('初始化完成');
        if (!['dev', 'build'].includes(this.command)) {
            consola.error('命令输入错误，请检查⚠️⚠️⚠️');
            return false;
        }
        if (!this.appname) {
            consola.error('appname不能为空⚠️⚠️⚠️');
            return false;
        }
        const applist = Object.keys(this.appConfig);
        if (!applist.includes(this.appname)) {
            consola.error(`app"${this.appname}"不在预期范围内，请检查⚠️⚠️⚠️`);
            return false;
        }
        return true;
    }

    executeCommand() {
        const config = JSON.stringify(this.appConfig[this.appname]);
        const string = `VITE_APP_CONFIG="${config}"\nVITE_APP_NAME=${this.appname}`;
        if (this.command === 'build') {
            consola.info(`正在写入build配置`);
            const prodFilePath = path.join(__dirname, '../.env.production');
            this.fs.writeFile(prodFilePath, string, (status) => {
                if (status) {
                    consola.success(`配置完成，开始打包`);
                    this.build();
                }
            });
        }
        if (this.command === 'dev') {
            consola.info(`正在写入服务配置`);
            const devFilePath = path.join(__dirname, '../.env.development');
            this.fs.writeFile(devFilePath, string, (status) => {
                if (status) {
                    consola.success(`配置完成，开始启动服务`);
                    this.server();
                }
            });
        }
    }

    build() {
        const ls = exec('vite build');

        ls.stdout.on('data', (data) => {
            consola.info(`build data: ${data}`);
        });

        ls.stderr.on('data', (data) => {
            consola.error(`error: ${data}`);
        });

        ls.on('close', (code) => {
            consola.success(`打包完成✅`);
        });
    }

    server() {
        const ls = exec('vite --port 3001 --host');
        ls.stdout.on('data', (data) => {
            console.log(data);
        });

        ls.stderr.on('data', (data) => {
            console.log(data);
        });

        ls.on('close', (code) => {
            consola.success(`服务已经关闭`);
        });
    }
}

const index = new Index();
index.start();
