#include "applicationmanagerpage.h"

#include <QSvgRenderer>
#include <QPainter>
#include <ctime>
#include "applicationmanager.h"
#include "config.h"
#include "mainscreen.h"
#include "mainwindowlayout.h"
ApplicationManagerPage::ApplicationManagerPage(int category, ApplicationManager *application_manager,QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	this->category = category;
	this->parent = parent;
	this->application_manager = application_manager;
	sqlite_helper.get_buttons(button_structs);
	layout = new QVBoxLayout;
	sqlite_helper.get_all_software(softwares, category);
	table = new QTableWidget(this);
	table->setColumnCount(9);
	QStringList titles;
	titles<< QString::fromLocal8Bit("图标") << QString::fromLocal8Bit("名称") << QString::fromLocal8Bit("全名") << QString::fromLocal8Bit("开发者") << QString::fromLocal8Bit("最后使用日期")<<QString::fromLocal8Bit("排序") << QString::fromLocal8Bit("添加到导航条") <<QString::fromLocal8Bit("设置") << QString::fromLocal8Bit("打开");
	table->setHorizontalHeaderLabels(titles);
	table->setEditTriggers(QAbstractItemView::NoEditTriggers);
	table->setStyleSheet("QTableWidget{border:1px;outline:1px;align: center;}  QQTableWidget::widget  QTableWidget::item {text-align: center;}");
	table->horizontalHeader()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
	int i = 0;
	for (i = 0; i < 9; i++)
	{
		table->horizontalHeader()->setSectionResizeMode(i, QHeaderView::Stretch);
		
	}
	i = 0;
	QTableWidgetItem* item = new QTableWidgetItem;
	item->setTextAlignment(Qt::AlignCenter);
	table->setItemPrototype(item);
	layout->addWidget(table);
	setLayout(layout);

}
ApplicationManagerPage::~ApplicationManagerPage()
{
	for (auto button : buttons)
	{
		delete button;
	}
	delete table;
	delete layout;
}

void ApplicationManagerPage::onclicked(int state)
{
	for(int i=0;i<table->rowCount();i++)
	{
		if(((QCheckBox *)table->cellWidget(i,6))->checkState()==Qt::Checked)
		{
			if(!checked[table->item(i,2)->text()])
			{
				QString orig_name = table->item(i, 2)->text();
				bool ok=sqlite_helper.edit_software(table->item(i, 1)->text(), orig_name, rows[orig_name].exe_file, QString::number(rows[orig_name].sort), rows[orig_name].categories,"navbar");
				if(!ok)
				{
					QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("更新部分或全部失败"));
					break;
				}
				checked[table->item(i, 2)->text()] = true;
			}
		}else
		{
			if (checked[table->item(i, 2)->text()])
			{
				QString orig_name = table->item(i, 2)->text();
				bool ok = sqlite_helper.edit_software(table->item(i, 1)->text(), orig_name, rows[orig_name].exe_file, QString::number(rows[orig_name].sort), rows[orig_name].categories, "app");
				if (!ok)
				{
					QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("更新部分或全部失败"));
					break;
				}
				checked[table->item(i, 2)->text()] = false;
			}
		}
	}
	//在后面refresh，避免因为refresh导致信号和槽断开
}
//刷新页面
void ApplicationManagerPage::refresh()
{
	for(auto button:application_manager->buttons)
	{
		button->update();
	}
	int rowcount = table->rowCount();
	for(auto i : connections)
	{
		disconnect(i);
	}
	for(int i=0;i<rowcount;i++)
	{
		table->removeRow(0);
	}
	
	softwares.clear();
	sqlite_helper.get_all_software(softwares, category);
	int i = 0;
	for (auto software : softwares)
	{
		table->insertRow(i);

		table->setItem(i, 1, new QTableWidgetItem(software.name));
		table->setItem(i, 2, new QTableWidgetItem(software.orig_name));
		table->setItem(i, 3, new QTableWidgetItem(software.dev));
		QString date;
		std::tm* time;
		if(software.use_time!=0)
		{
			time = std::localtime(&software.use_time);
			date = QString::number(1900 + time->tm_year, 10);
			date += "/";
			date += QString::number(1 + time->tm_mon, 10);
			date += "/";
			date += QString::number(time->tm_mday, 10);
			table->setItem(i, 4, new QTableWidgetItem(date));
		}
		else
		{
			table->setItem(i, 4, new QTableWidgetItem(QString::fromLocal8Bit("从未使用")));
		}
		Record2 record2;
		record2.name = software.name;
		record2.icon = new QLabel;
		QFile file(software.img);
		record2.icon->setMaximumSize(50, 50);
		record2.icon->setScaledContents(true);
		if (file.exists())
		{
			QPixmap pixmap(software.img);
			//pixmap.scaled(40, 40);
			record2.icon->setPixmap(pixmap);
		}
		else {
			QPixmap pixmap(QApplication::applicationDirPath() + DEFAULT_PNG);
			//pixmap.scaled(40, 40);
			record2.icon->setPixmap(pixmap);
		}
		
		table->setCellWidget(i, 0, record2.icon);
		
		if(!software.locked)
		{
			record2.settings = new MiniButton(software.orig_name, "settings");
			record2.settings->setText(QString::fromLocal8Bit("设置"));
			record2.settings->setMaximumSize(60, 40);
			QMetaObject::Connection connect1 = connect(record2.settings, &MiniButton::clicked, record2.settings, &MiniButton::onclick2);
			connections << connect1;
			QMetaObject::Connection connect2 = connect(record2.settings, &MiniButton::click2, application_manager, &ApplicationManager::onclick2);
			connections << connect2;
			table->setCellWidget(i, 7, record2.settings);
		}
		record2.open = new MiniButton(software.orig_name, "open");
		record2.open->setText(QString::fromLocal8Bit("打开"));
		record2.open->setMaximumSize(60, 40);
		QMetaObject::Connection connect3=connect(record2.open, &MiniButton::clicked, record2.open, &MiniButton::onclick2);
		connections << connect3;
		QMetaObject::Connection connect4=connect(record2.open, &MiniButton::click2, application_manager, &ApplicationManager::onclick2);
		connections << connect4;
		record2.exe_file = software.path;
		record2.orig_name = software.orig_name;
		record2.url = software.url;
		for (int i = 0; i < CATEGORIES_NUM; i++)
		{
			record2.categories[i] = false;
		}
		for (int i = 0; i < CATEGORIES_NUM; i++)
		{
			if (software.category_id.contains(QString::number(i+1)))
			{
				record2.categories[i] = true;
			}
		}
		record2.op = software.op;
		record2.func = software.func;
		QMetaObject::Connection connect5 = connect(this, &ApplicationManagerPage::onclick3, (MainWindowLayout*)((MainScreen*)application_manager->parent)->parent, &MainWindowLayout::clickButton);
		connections<<connect5;
		record2.sort = software.sort;
		record2.check_box = new QCheckBox;
		if (software.is_navbar)
		{
			record2.check_box->setCheckState(Qt::Checked);
			checked.insert(software.orig_name, true);
		}
		else
		{
			record2.check_box->setCheckState(Qt::Unchecked);
			checked.insert(software.orig_name, false);
		}
		if(software.locked)
		{
			record2.check_box->setEnabled(false);
		}
		else
		{
			record2.check_box->setEnabled(true);
		}
		
		QMetaObject::Connection connect6 = connect(record2.check_box, &QCheckBox::stateChanged, this, &ApplicationManagerPage::onclicked);
		connections << connect6;
		QMetaObject::Connection connect7 = connect(record2.check_box, &QCheckBox::stateChanged, mainWindowLayout->navBar, &NavBar::refresh);
		connections << connect7;
		table->setItem(i, 5, new QTableWidgetItem(QString::number(software.sort)));
		QTableWidgetItem* check_box_item = new QTableWidgetItem;
		table->setItem(i, 6, check_box_item);
		table->setCellWidget(i, 6, record2.check_box);
		check_box_item->setTextAlignment(Qt::AlignCenter);
		table->setCellWidget(i, 8, record2.open);
		rows.insert(software.orig_name, record2);
		table->resizeColumnToContents(0);
		i++;
	}
}
