#include "RecordProductLog.h"
#include <io.h>
#include <direct.h>
#include <QMap>
#include<QFile>
#include<QDir>
#include<QTextStream>
#include "cmallsystem.h"
DWORD WINAPI ThreadProductLogRun(LPVOID lpVoid)
{
	CRecordProductLog* logEntity = (CRecordProductLog*)lpVoid;
	while(logEntity->m_bRunning){
		logEntity->AutoWriteLog();
		Sleep(200);
		if(!logEntity->m_bRunning)break;
		Sleep(150);
		if(!logEntity->m_bRunning)break;
		Sleep(150);
		if(!logEntity->m_bRunning)break;
	}
	return 0;
}
HANDLE CRecordProductLog::CreateThread()
{
	DWORD threadId;
	m_ThreadHandle=::CreateThread(NULL, 0,	ThreadProductLogRun, (LPVOID)this, 0, &threadId);
	Q_ASSERT(m_ThreadHandle);
	return m_ThreadHandle;
}

CRecordProductLog::CRecordProductLog()
{
	m_bRunning = true;
	CreateThread();
}


CRecordProductLog::~CRecordProductLog()
{
	Exit();
}

void CRecordProductLog::AddLog(const std::string& lotId, const std::string& waferId, const QString &msg)
{
	if(0 == m_ThreadHandle)return;
	QMutexLocker l(&m_AWLogMutex);
	m_LogVec.push_back(_TagProduct_LOG(waferId, msg.toUtf8().data(), lotId));
}

void CRecordProductLog::AutoWriteLog()
{
	QMutexLocker l(&m_AWLogMutex);
	if(m_LogVec.size()<=0)return;
    std::list<_TagProduct_LOG> lstTemp;
    lstTemp.swap(m_LogVec);
	l.unlock();
	if (!lstTemp.size())
		return;

	QMap<std::pair<std::string, std::string>, std::list<_TagProduct_LOG>> tempDic;
	for(auto iter=lstTemp.begin();iter!=lstTemp.end();iter++)
	{
		tempDic[make_pair((*iter).m_sWaferId, (*iter).m_sLotId)].emplace_back((*iter));
	}

	for (auto iter = tempDic.constBegin();iter!=tempDic.constEnd();iter++)
	{
		const std::string& waferId = iter.key().first;
		const std::string& lotId = iter.key().second;
		QString filePath = CreateFilePath("ProdcutData", lotId.c_str(), waferId.c_str());
		RecordInfo(filePath, iter.value());
	}
}

void CRecordProductLog::Exit()
{
	m_bRunning = false;
	AutoWriteLog();
	if(0 == m_ThreadHandle)
		return;
	
	
	WaitForSingleObject(m_ThreadHandle, 2000);
	CloseHandle(m_ThreadHandle);
	m_ThreadHandle = 0;
}

void CRecordProductLog::RecordInfo(const QString& filePath, const std::list<_TagProduct_LOG>& logData)
{
	if(logData.size()<=0)return;

	//如果不存在将会在表头记录数据
	bool bExists = QFile::exists(filePath);

	//记录数据
	QFile file(filePath);
	if(!file.open(QIODevice::Append))
	{
		//LOG(INFO)<<ERR_TITTLE()<<"Record Log open file failed"<<filePath.toStdString();
		return;
	}

	QTextStream outStream(&file);
	for (auto iter=logData.begin();iter!=logData.end();iter++)
	{
		if(!bExists){
			outStream<<"LotNo.:\t"<<(*iter).m_sLotId.c_str()<<"\n";
			outStream<<"WaferId:\t"<<(*iter).m_sWaferId.c_str()<<"\n";
			outStream<<"Recipe:\t"<<m_gSystem.GetCurFile().toStdString().c_str()<<"\n";
			bExists = true;
		}
		QString s = (*iter).m_msg.c_str();
		outStream<<s<<"\n";
	}
	//outStream.flush();
	file.close();
}

QString CRecordProductLog::CreateFilePath(const QString& parentFolder, const QString lotId,const QString& waferId)
{
	QDateTime curDateTime = QDateTime::currentDateTime();

	QString folderMonth = curDateTime.toString("yyyyMM");
	QString folderDay = curDateTime.toString("yyyy-MM-dd");
	QString fileName = waferId+".txt";
	QDir curPath = QDir(QDir::currentPath());
	curPath.cdUp();

	QString path = curPath.absoluteFilePath(parentFolder + "/" + folderMonth + "/" + folderDay+"/"+lotId);
	curPath.setPath(path);
	if(!curPath.exists()){
		if(false == curPath.mkpath(path)){
			//LOG(INFO)<<ERR_TITTLE()<<"create product record folder failed "<< path.toStdString();
		}
	}
	
	QString filePath = curPath.absoluteFilePath(fileName);
	return filePath;
}

QString CRecordProductLog::GetPicNameByCurTime()
{
	QString fullName;
	return fullName;
}
