#include "stable.h"
#include "cdlglotcode.h"
#include "qmymessagebox.h"
#include "mainwindow.h"
#include "cgemdriver.h"

#include <QMessageBox>
CDlgLotCode::CDlgLotCode(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);
}

CDlgLotCode::~CDlgLotCode()
{

}
void CDlgLotCode::on_btnLoadRecipe_clicked()
{

	CGEMDriver* pDriverGEM=GET_CARD(GEM_DRIVER_JNG, CGEMDriver);
	QString operatorPath = pDriverGEM->m_Variants.get_VData(Var_MES_RecipeRoot)->toString();

	QString dirPath = CMakePath::make_data_path("");
	QString rootPath = dirPath;
	CWorker* pWorker=GET_CHDIRECT(M_WORKER,CWorker);
	if(pWorker->m_workLevel<=LEVEL_OPERATOR){
		dirPath = CMakePath::make_data_path(operatorPath);
	}

	QDir dir;
	QStringList filters;
	filters << ui.txtProductNo->text()+".lpf";
	dir.setPath(dirPath);
	dir.setNameFilters(filters);
	QDirIterator iter(dir ,QDirIterator::Subdirectories);
	QList<QFileInfo> fileList;
	while (iter.hasNext())
	{
		iter.next();
		QFileInfo info=iter.fileInfo();
		if (info.isFile())
		{
			MqDebug() << info.absoluteFilePath();
			fileList.append(info);
		}
	}
	
	if(fileList.size()==0){
		//m_gSystem.m_SysMsg.SetMsg();
		QMyMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("No associated Recipe found"), QMessageBox::Yes);
		msgBox.SetMySize(300, 250);
		msgBox.setStandardButtons(QMessageBox::Yes);
		msgBox.setButtonText(QMessageBox::Yes, tr("OK"));
		//QMessageBox::critical(this, tr("Warning"), tr("Not find recipe"), tr("OK"));
		msgBox.exec();
		return;
	}

	if(fileList.size()>1){
		QMyMessageBox msgBox(QMessageBox::Critical, tr("Error"), tr("Found multi Recipe"), QMessageBox::Yes);
		msgBox.SetMySize(300, 250);
		msgBox.setStandardButtons(QMessageBox::Yes);
		msgBox.setButtonText(QMessageBox::Yes, tr("OK"));
		//QMessageBox::critical(this, tr("Warning"), tr("Not find recipe"), tr("OK"));
		msgBox.exec();
		return;
	}


	QFileInfo fileInfo = fileList[0];
	QString filePath = fileInfo.absoluteFilePath();
	QString filePathRecord = fileInfo.absoluteFilePath().replace(rootPath+"/", "");
	if(true == m_gMainWindow->load_File(filePath, filePathRecord)){
		m_gSystem.SetLotId(ui.txtLotNo->text());
		accept();
	}else{
		reject();
	}
	return;
}

void CDlgLotCode::on_btnCancel_clicked()
{
	reject();
}

void CDlgLotCode::on_btnBarcodeLotNo_clicked()
{
	ui.txtLotNo->setFocus();
	ui.txtLotNo->selectAll();
}

void CDlgLotCode::on_btnBarcodeRecipe_clicked()
{
	ui.txtProductNo->setFocus();
	ui.txtProductNo->selectAll();
}

void CDlgLotCode::showEvent(QShowEvent *)
{

	ui.lblCurLotNo->setText(tr("LotNo:")+ m_gSystem.GetLotId().c_str());
	ui.lblCurRecipe->setText(tr("RecipeNo:") + m_gSystem.GetCurFile());

	QFileInfo fileInfo(m_gSystem.GetCurFile());
	

	ui.txtProductNo->setText(fileInfo.fileName().replace(".lpf", ""));
	ui.txtLotNo->setText(m_gSystem.GetLotId().c_str());
	ui.txtLotNo->setFocus();
	ui.txtLotNo->selectAll();
}
