#include "applicationmanager.h"
#include "applicationmanagerpage.h"
#include "config.h"
#include "addapp.h"
#include "addcategory.h"
#include  "sqlitehelper.h"
#include <ctime>

#include "globalvariables.h"

ApplicationManager::ApplicationManager(QWidget *parent)
	: QWidget(parent)
{
	ui.setupUi(this);
	resize(parent->width(), parent->height());
	miniblink = new QMiniBlink(this);
	miniblink->init();
	miniblink->show();
	connect(this, &ApplicationManager::changeUrl, miniblink, &QMiniBlink::switchUrl);
	layout = new QVBoxLayout(this);
	layout_top = new QHBoxLayout(this);
	layout_top->setAlignment(Qt::AlignRight);
	layout_top->setMargin(5);
	layout_bottom = new QHBoxLayout(this);
	QList<Categrory> categrories;
	sqlite_helper.get_category(categrories);
	sqlite_helper.get_buttons(button_structs);
	for (auto button_struct : button_structs)
	{
		MiniButton* button = new MiniButton(button_struct, this);
		button->setText(button_struct.text);
		//button->show();
		button->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
		button->setMaximumWidth(TEXT_SIZE * button->text().length() * scale * 3 + 40);
		button->setMaximumHeight(TEXT_SIZE * scale * 3 + 20);
		//button->resize(TEXT_SIZE * button->text().length() * scale * 3 + 20, TEXT_SIZE * scale * 3 + 10);
		buttons << button;
		layout_top->addWidget(button, 1);
		connect(button, &MiniButton::click0, button, &MiniButton::onclick1);
		connect(button, &MiniButton::click1, this, &ApplicationManager::onclick1);
	}
	//ui.tabWidget->setStyleSheet("border:none;");
	//ui.tabWidget->setMinimumHeight(40);
	//ui.tabWidget->setMovable(false);
	//ui.tabWidget->setDocumentMode(false);
	//ui.tabWidget->setCurrentIndex(0);
	tab_bar = new QTabBar(this);
	tab_bar->addTab(QString::fromLocal8Bit("全部"));
	layout_bottom_top = new QVBoxLayout;

	for(int i=2;i<=8;i++)
	{
		tab_bar->addTab(categrories[i - 2].name);
	}
	layout_bottom_top->addWidget(tab_bar, 1);
	application_manager_page_all = new ApplicationManagerPage(ALL, this, this);
	connect(this, &ApplicationManager::refresh, application_manager_page_all, &ApplicationManagerPage::refresh);
	layout_bottom_top->addWidget(application_manager_page_all, 19);
	map.insert(1, application_manager_page_all);
	for(int i=2;i<=8;i++)
	{
		ApplicationManagerPage* application_manager_page = new ApplicationManagerPage(i, this, this);
		connect(this, &ApplicationManager::refresh, application_manager_page, &ApplicationManagerPage::refresh);
		layout_bottom_top->addWidget(application_manager_page, 19);
		application_manager_page->setHidden(true);
		map.insert(i, application_manager_page);
	}
	tab_bar->setCurrentIndex(0);
	connect(tab_bar, &QTabBar::currentChanged, this, &ApplicationManager::tabChange);
	QString style = "QTabBar::tab{height:80;width:150; border:2px} QTabBar::tab:hover{ border:2px;height:80;width:150;color:";
	style += DEFAULT_COVER_COLOR;
	style += ";}QTabBar::tab:selected { border:2px;height:80;width:150;color:";
	style += DEFAULT_COVER_COLOR;
	style += ";}";
	tab_bar->setStyleSheet(style);
	tab_bar->setDrawBase(false);
	/*ApplicationManagerPage* application_manager_page_all = new ApplicationManagerPage(ALL,this);
	QHBoxLayout *application_manager_page_all_layout = new QHBoxLayout;
	application_manager_page_all_layout->addWidget(application_manager_page_all);
	pages.insert(application_manager_page_all_layout, application_manager_page_all);
	ui.tab_1->setLayout(application_manager_page_all_layout);
	ui.tabWidget->setTabText(0,QString::fromLocal8Bit("全部"));

	ApplicationManagerPage* application_manager_page_elite = new ApplicationManagerPage(ELITE,this);
	QHBoxLayout* application_manager_page_elite_layout = new QHBoxLayout;
	application_manager_page_elite_layout->addWidget(application_manager_page_elite);
	ui.tab_2->setLayout(application_manager_page_elite_layout);
	pages.insert(application_manager_page_elite_layout, application_manager_page_elite);
	ui.tabWidget->setTabText(1, categrories[0].name);

	ApplicationManagerPage* application_manager_page_soft = new ApplicationManagerPage(SOFT,this);
	QHBoxLayout* application_manager_page_soft_layout = new QHBoxLayout;
	application_manager_page_soft_layout->addWidget(application_manager_page_soft);
	pages.insert(application_manager_page_soft_layout, application_manager_page_soft);
	ui.tab_3->setLayout(application_manager_page_soft_layout);
	ui.tabWidget->setTabText(2, categrories[1].name);

	ApplicationManagerPage* application_manager_page_system = new ApplicationManagerPage(SYSTEM,this);
	QHBoxLayout* application_manager_page_system_layout = new QHBoxLayout;
	application_manager_page_system_layout->addWidget(application_manager_page_system);
	pages.insert(application_manager_page_system_layout, application_manager_page_system);
	ui.tab_4->setLayout(application_manager_page_system_layout);
	ui.tabWidget->setTabText(3, categrories[2].name);

	ApplicationManagerPage* application_manager_page_inner = new ApplicationManagerPage(INNER,this);
	QHBoxLayout* application_manager_page_inner_layout = new QHBoxLayout;
	application_manager_page_inner_layout->addWidget(application_manager_page_inner);
	pages.insert(application_manager_page_inner_layout, application_manager_page_inner);
	ui.tab_5->setLayout(application_manager_page_inner_layout);
	ui.tabWidget->setTabText(4, categrories[3].name);

	ApplicationManagerPage* application_manager_page_custom_1 = new ApplicationManagerPage(CUSTOM_1, this);
	QHBoxLayout* application_manager_page_custom_1_layout = new QHBoxLayout;
	application_manager_page_custom_1_layout->addWidget(application_manager_page_custom_1);
	pages.insert(application_manager_page_custom_1_layout, application_manager_page_custom_1);
	ui.tab_6->setLayout(application_manager_page_custom_1_layout);
	ui.tabWidget->setTabText(5, categrories[4].name);

	ApplicationManagerPage* application_manager_page_custom_2 = new ApplicationManagerPage(CUSTOM_2, this);
	QHBoxLayout* application_manager_page_custom_2_layout = new QHBoxLayout;
	application_manager_page_custom_2_layout->addWidget(application_manager_page_custom_2);
	pages.insert(application_manager_page_custom_2_layout, application_manager_page_custom_2);
	ui.tab_7->setLayout(application_manager_page_custom_2_layout);
	ui.tabWidget->setTabText(6, categrories[5].name);

	ApplicationManagerPage* application_manager_page_others = new ApplicationManagerPage(OTHERS,this);
	QHBoxLayout* application_manager_page_others_layout = new QHBoxLayout;
	application_manager_page_others_layout->addWidget(application_manager_page_others);
	pages.insert(application_manager_page_others_layout, application_manager_page_others);
	ui.tab_8->setLayout(application_manager_page_others_layout);
	ui.tabWidget->setTabText(7, categrories[6].name);*/
	layout_bottom->addLayout(layout_bottom_top,7);
	layout_bottom->addWidget(miniblink, 3);
	layout->addLayout(layout_top, 1);
	layout->addLayout(layout_bottom, 9);
	setLayout(layout);
}

ApplicationManager::~ApplicationManager()
{
	for(auto button:buttons)
	{
		delete button;
	}
	for(auto layout:pages.keys())
	{
		delete pages[layout];
		delete layout;
	}
	delete miniblink;
	delete layout_top;
	delete layout_bottom;
	delete layout;
}

void ApplicationManager::onclick1(QString op, QString func, QString path, QString url)
{
	if(op=="self")
	{
		if(func=="app_add")
		{
			AddApp add_app;
			add_app.exec();
			if(add_app.changed)
			{
				bool ok = sqlite_helper.insert_software(add_app.get_name(), add_app.get_orig_name(), add_app.get_exe_path(),
					add_app.get_sort(), add_app.get_categories());
				if (!ok)
				{
					QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("插入失败"));
				}

				emit refresh();
				/*table->insertRow(table->rowCount()-1);
				table->setItem(table->rowCount(), 0, new QTableWidgetItem(add_app.get_name()));
				table->setItem(table->rowCount(), 1, new QTableWidgetItem(add_app.get_orig_name()));
				Record2 record2;
				srand(time(nullptr));

				int id = rand();
				if(id<RAND_MAX-100000)
				{
					id += 100000;
				}
				record2.settings = new MiniButton(id, "settings");
				record2.settings->setText(QString::fromLocal8Bit("设置"));
				connect(record2.settings, &MiniButton::click0, record2.settings, &MiniButton::onclick2);
				connect(record2.settings, &MiniButton::click2, this, &ApplicationManager::onclick2);
				record2.open = new MiniButton(id, "open");
				record2.open->setText(QString::fromLocal8Bit("打开"));
				connect(record2.open, &MiniButton::click0, record2.open, &MiniButton::onclick2);
				connect(record2.open, &MiniButton::click2, this, &ApplicationManager::onclick2);
				record2.exe_file = add_app.get_exe_path();
				record2.orig_name = add_app.get_orig_name();
				table->setCellWidget(table->rowCount(), 4, record2.settings);
				table->setCellWidget(table->rowCount(), 5, record2.open);
				rows.insert(id, record2);*/
			}
		}
		else if (func == "app_update")
		{
			bool software_ok = sqlite_helper.update_software();
			bool app_ok = sqlite_helper.update_app();
			if(software_ok&&app_ok)
			{
				QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("更新成功"));
			}
			else
			{
				QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("更新部分或全部失败"));
			}
		}else if(func=="app_category")
		{
			AddCategory add_category;
			add_category.exec();
			if(add_category.changed)
			{
				for(int i=0;i<7;i++)
				{
					tab_bar->setTabText(i + 1, add_category.categrories[i].name);
				}
				bool ok = sqlite_helper.set_category(add_category.categrories);
				if (!ok)
				{
					QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("添加失败"));
				}
			}
		}
	}else if(op=="soft")
	{
		emit changeUrl(url);
		ShellExecute(GetDesktopWindow(), L"open", path.toStdWString().c_str(), L"", L"", SW_SHOW);
	}else if(op=="app")
	{
		emit changeUrl(url);
		QString str = QApplication::applicationDirPath() + path;
		ShellExecute(GetDesktopWindow(), L"open",str.toStdWString().c_str(), L"", L"", SW_SHOW);
	}else if(op=="url")
	{
		emit changeUrl(url);
	}
}

void ApplicationManager::onclick2(QString orig_name, QString op)
{
	if (op == "open")
	{
		emit changeUrl(application_manager_page_all->rows[orig_name].url);
		WinExec(application_manager_page_all->rows[orig_name].exe_file.toStdString().c_str(), SW_SHOW);
	}
	else if (op == "settings")
	{
		AddApp add_app(true, &application_manager_page_all->rows[orig_name]);
		add_app.exec();
		if (add_app.changed)
		{
			bool ok = sqlite_helper.edit_software(add_app.get_name(), add_app.get_orig_name(), add_app.get_exe_path(), add_app.get_sort(), add_app.get_categories());
			if (!ok)
			{
				QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("编辑失败"));
			}
		}
	}
}

void ApplicationManager::tabChange(int index)
{
	tab_bar->setHidden(false);
	for(auto i:map.keys())
	{
		map[i]->setHidden(true);
	}
	map[index + 1]->setHidden(false);
}
