#include "ctai_cmd.h"

ctai_cmd::ctai_cmd()
{
    QVBoxLayout *layout = new QVBoxLayout(this);
    textEdit = new QPlainTextEdit(this);
    textEdit->setReadOnly(true); // 允许编辑，以便模拟命令行输入输出环境
    layout->addWidget(textEdit);

    QLineEdit *lineEdit = new QLineEdit(this);
    layout->addWidget(lineEdit);
    layout->setStretch(0, 8);
    layout->setStretch(1, 2);
    connect(lineEdit, &QLineEdit::returnPressed, this, [this, lineEdit]()
            {
                slots_executeCommand(lineEdit->text());
                lineEdit->clear(); // 清空输入框
            });
    process = new QProcess(this);
    process->setProcessChannelMode(QProcess::MergedChannels); // 合并输出通道
    connect(process, &QProcess::readyRead, this, &ctai_cmd::slots_readProcessOutput);
    connect(process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
    [](int code, QProcess::ExitStatus status){
        QMessageBox::warning(nullptr, "Process", 
            QString("进程异常退出，代码：%1").arg(code));
    });
    // 启动Shell
#ifdef Q_OS_WIN
    process->start("cmd.exe");
#else
    process->start("/bin/bash");
#endif
}
ctai_cmd::~ctai_cmd()
{
    
}
void ctai_cmd::slots_readProcessOutput() {
    // 实时读取输出
    QByteArray output = process->readAll();
    textEdit->appendPlainText(QString::fromLocal8Bit(output));
    
    // 自动滚动到底部
    QTextCursor cursor = textEdit->textCursor();
    cursor.movePosition(QTextCursor::End);
    textEdit->setTextCursor(cursor);
}
void ctai_cmd::slots_executeCommand(const QString &command)
{
    if (!command.isEmpty()) {
        // 写入命令到进程
        process->write(command.toLocal8Bit() + "\n");
        textEdit->appendPlainText("> " + command); // 显示输入命令
    }
}