#include "Cleanthread.h"
#include <QMutex>
#include <QDate>
#include <QDir>
#include <QFileInfoList>
#include <Windows.h>
#include <QSignalMapper>
#include <QIntValidator>
#include "common.h"///
extern SysConf g_sys_conf;///
CleanWorkThread::CleanWorkThread(QObject* parent) : QObject(parent)
{
}
CleanWorkThread::~CleanWorkThread()
{
}
void CleanWorkThread::setSelAuto() {
	delSelection = 1;
}
void CleanWorkThread::setSel() {
	delSelection = 2;
}
void CleanWorkThread::startWork()
{
	emit workStart();
	doWork();
}
void CleanWorkThread::startWorkAuto()
{
	emit workStartAuto();
	doWork();
}
void CleanWorkThread::doWork()
{
	qint64 spaceSize;
	qint64 dirSize;
	QString iDriver = "D:/";
	LPCWSTR strDriver = (LPCWSTR)iDriver.utf16();
	ULARGE_INTEGER freeDiskSpaceAvailable, totalDiskSpace, totalFreeDiskSpace;
	qint64 gb = (1024 * 1024 * 1024);
	QString dir("D:/image");

	if (delSelection == 2) 
	{
		CleanImageFile(dir, 1);
	}
	else 
	{
		qint64 delDays = g_sys_conf.save_days;///
		qint64 freeSize = g_sys_conf.freesize;
		CleanImageFile(dir, delDays--);
		//调用函数获取磁盘参数(单位为字节Byte),转化为GB，需要除以(1024*1024*1024)
		GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace);
		spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100/freeSize)) / (qint64)totalDiskSpace.QuadPart;
		dirSize = DirFileSize(dir) / gb;

		while ((spaceSize < 1) && (delDays > 1)) { //磁盘剩余空间小于百分之十
			CleanImageFile(dir, delDays--);
			GetDiskFreeSpaceEx(strDriver, &freeDiskSpaceAvailable, &totalDiskSpace, &totalFreeDiskSpace);
			spaceSize = ((qint64)totalFreeDiskSpace.QuadPart * (100 / freeSize)) / (qint64)totalDiskSpace.QuadPart;
		}
	}
	emit workFinished();
}
void CleanWorkThread::CleanImageFile(const QString& path, const qint64& delDays)
{
	QDir dir(path);
	QFileInfoList list;
	QFileInfo curFile;
	if (!dir.exists()) { return; }//文件不存，则返回false
	dir.setFilter(QDir::Dirs | QDir::Files);
	list = dir.entryInfoList(QDir::Dirs | QDir::Files
		| QDir::Readable | QDir::Writable
		| QDir::Hidden | QDir::NoDotAndDotDot
		, QDir::Time);
	if (list.isEmpty()) { return; }//文件夹为空，则返回false
	int i = list.size() - 1;
	do {
		QFileInfo fileInfo = list.at(i);
		// dir.removeRecursively();
		while (fileInfo.fileName() == "." || fileInfo.fileName() == ".." && i >= 0)
		{
			i--;
		}
		if (i < 0) {
			break;
		}
		bool bisDir = fileInfo.isDir();
		if (bisDir)
		{
			QRegExp rx("\\d{4}-\\d{2}-\\d{2}");
			QRegExpValidator v(rx, 0);
			int pos = 0;
			int match;
			QString name = fileInfo.fileName();
			match = v.validate(name, pos);
			if (match == 2)
			{
					QDate delDate = QDate::currentDate();
					QDate dirDate;
					QString name = fileInfo.fileName();
					dirDate = QDate::fromString(fileInfo.fileName(), "yyyy-MM-dd");
					qint64 nDays = dirDate.daysTo(delDate);
					if (nDays >= delDays)
					{
						if (fileInfo.isDir()) {
							QString n = fileInfo.absoluteFilePath();
							QDir subPath(fileInfo.absoluteFilePath());
							subPath.removeRecursively();
						}
						else
						{
							fileInfo.dir().remove(fileInfo.fileName());
						}
					}
			}
			else
			{
				CleanImageFile(fileInfo.filePath(), delDays);
			}
		}
		else
		{
			fileInfo.dir().remove(fileInfo.fileName());
		}
		i--;
	} while (i >= 0);
}

qint64 CleanWorkThread::DirFileSize(const QString& path)
{
	QDir dir(path);
	quint64 size = 0;
	//dir.entryInfoList(QDir::Files)返回文件信息
	foreach(QFileInfo fileInfo, dir.entryInfoList(QDir::Files))
	{
		//计算文件大小
		size += fileInfo.size();
	}
	//dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot)返回所有子目录，并进行过滤
	foreach(QString subDir, dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
	{
		//若存在子目录，则递归调用dirFileSize()函数
		size += DirFileSize(path + QDir::separator() + subDir);
	}
	return size;
}