#include "CMDExcuteApp.h"
#include <QProcess>
#include <QDebug>
#include <QThread>
#include <QTimer>

CMDExcuteApp::CMDExcuteApp(QWidget* parent)
{
	this->ui.setupUi(this);
	this->cmd = new QProcess();
	connect(this->cmd, SIGNAL(readyReadStandardOutput()), this, SLOT(on_readoutput()));
	connect(this->cmd, SIGNAL(readyReadStandardError()), this, SLOT(on_readerror()));
	
}

CMDExcuteApp::~CMDExcuteApp()
{
	if (nullptr != this->cmd) {
		
		delete this->cmd;
		this->cmd = nullptr;

	}
}

int CMDExcuteApp::excuteCmd(QString cmdText)
{
	qDebug() << u8"执行命令：" << cmdText ;
	this->ui.textEdit->append("cmd.exe\n");   
	this->cmd->start("cmd.exe");
	this->cmd->waitForStarted(); //等待程序启动
	this->ui.textEdit->append(QString::QString(cmdText));
	this->ui.textEdit->append("\n");
	this->cmd->write(cmdText.toUtf8().constData());

	this->cmd->close();
	this->waitExcutedFinish();
	return 0;
}

int CMDExcuteApp::excuteCmd(QString exePath, QString params)
{
	qDebug() << u8"执行命令：" << exePath<<u8" "<< params;
	this->setWindowTitle(exePath);
	QString program = QString::QString(exePath);
	QStringList prams_txt;
	prams_txt.append(QString::QString(params));
	this->cmd->start(program, prams_txt);
	//this->cmd->waitForFinished();
	this->show();
	this->waitExcutedFinish();
	return 0;
}

int CMDExcuteApp::waitExcutedFinish()
{
	while (!this->cmd->waitForFinished()) {
		qDebug() << u8"运行状态：" << this->cmd->state();
		QCoreApplication::processEvents();
	}
	qDebug() << u8"退出循环运行状态：" << this->cmd->state();
	qDebug() << u8"退出循环码：" << this->cmd->exitCode();
	this->on_readerror();
	this->on_readoutput();
	emit this->callbackExcuteResult();
	return 0;
}

int CMDExcuteApp::on_readerror()
{
	QString out = this->cmd->readAllStandardError().data();
	qDebug()<<u8"on_readerror:\t" << out;
	this->ui.textEdit->append(out);
	return 0;
}
int CMDExcuteApp::on_readoutput()
{
	QString out = this->cmd->readAllStandardOutput().data();
	qDebug() << u8"on_readoutput:\t" << out;
	this->ui.textEdit->append(out);   //将输出信息读取到编辑框
	return 0;
}