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

#include "globalvariables.h"
#include "MyButton.h"
ApplicationManager::ApplicationManager(QWidget *parent)
	: QWidget(parent)
{
	application_manager = this;
	ui.setupUi(this);
	resize(parent->width(), parent->height());
	this->parent = parent;
	layout = new QVBoxLayout(this);
	layout_top_right = new QHBoxLayout(this);
	layout_top_right->setAlignment(Qt::AlignRight);
	layout_top_right->setMargin(5);
	layout_top= new QHBoxLayout(this);
	layout_top_left = new QHBoxLayout(this);
	layout_top_left->setMargin(0);
	layout_top_left->setAlignment(Qt::AlignLeft);
	layout_bottom = new QHBoxLayout(this);
	QList<Categrory> categrories;
	sqlite_helper.get_category(categrories,false);
	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_right->addWidget(button, 1);
		connect(button, &MiniButton::clicked, 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);
	layout_bottom_top = new QVBoxLayout;

	for(int i=0;i<categrories.length();i++)
	{
		tab_bar->addTab(categrories[i].name + "(" + QString::number(categrories[i].total) + ")");
		map2.insert(i, categrories[i].id);
	}
	layout_top_left->addWidget(tab_bar, 1);
	layout_top->addLayout(layout_top_left, 7);
	layout_top->addLayout(layout_top_right, 3);
	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(ALL, application_manager_page_all);
	for(int i=2;i<=CATEGORIES_NUM;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, 1);
		application_manager_page->setHidden(true);
		map.insert(i, application_manager_page);
	}
	//先不刷新，创建完navbar再刷新
	//emit refresh();
	connect(this,&ApplicationManager::refresh_tab,this,&ApplicationManager::onNumChange);
	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);
	layout_bottom->addLayout(layout_bottom_top,7);
	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 layout_top_left;
	delete layout_top_right;
	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_tab();
			}
		}
		else if (func == "app_update")
		{
			bool software_ok = sqlite_helper.update_software();
			bool app_ok = sqlite_helper.update_app();
			QFile file(QApplication::applicationDirPath() + DEFAULT_FILE);
			if(file.open(QIODevice::ReadOnly))
			{
				QByteArray ba = file.readAll();
				file.close();
				QJsonParseError json_error;
				QJsonDocument jsonDoc(QJsonDocument::fromJson(ba, &json_error));
				if (json_error.error == QJsonParseError::NoError)
				{
					QJsonObject rootObj = jsonDoc.object();
					agree=rootObj.value("agree").toBool();
				}
				else
				{
					QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("配置文件损坏"));
				}
			}else
			{
				UserImprove user_improve;
				user_improve.exec();
				if(file.open(QIODevice::WriteOnly|QIODevice::Text))
				{
					QJsonObject rootObj;
					rootObj.insert("agree", agree);
					QJsonDocument jsonDoc;
					jsonDoc.setObject(rootObj);
					file.write(jsonDoc.toJson());
					file.close();
				}
			}
			
			if(agree)
			{
				DeviceRequest *device_request = new DeviceRequest;//构造函数里面会自动发送请求
				delete device_request;
			}
			if(software_ok&&app_ok)
			{
				QMessageBox::information(this, QString::fromLocal8Bit("提示"), QString::fromLocal8Bit("更新成功"));
				emit refresh_tab();
			}
			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<add_category.categrories.length();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("添加失败，分类是否重名？"));
				}
				emit refresh_tab();

			}
		}
	}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)
{
	sqlite_helper.use_software(orig_name);
	if (op == "app")
	{
		if (application_manager_page_all->rows[orig_name].func == "openwechat") {
			emit application_manager_page_all->onclick3(orig_name,application_manager_page_all->rows[orig_name].op, application_manager_page_all->rows[orig_name].func, application_manager_page_all->rows[orig_name].exe_file, application_manager_page_all->rows[orig_name].url);
		}
		else {
			emit changeUrl(application_manager_page_all->rows[orig_name].url);
			WinExec((QApplication::applicationDirPath()+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("编辑失败"));
			}
			emit refresh_tab();

		}
	}
	else {
		emit application_manager_page_all->onclick3(orig_name,application_manager_page_all->rows[orig_name].op, 
			application_manager_page_all->rows[orig_name].func,
			application_manager_page_all->rows[orig_name].url,
			application_manager_page_all->rows[orig_name].exe_file
			);
	}
}

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

void ApplicationManager::onNumChange() {
	int count = tab_bar->count();
	disconnect(tab_bar, &QTabBar::currentChanged, this, &ApplicationManager::tabChange);
	for(int i=0;i<count;i++)
	{
		tab_bar->removeTab(0);
	}
	for(auto i:map.values())
	{
		delete i;
	}
	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(ALL, application_manager_page_all);
	for (int i = 2; i <= CATEGORIES_NUM; 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, 1);
		application_manager_page->setHidden(true);
		map.insert(i, application_manager_page);
	}
	QList<Categrory> categories;
	map2.clear();
	sqlite_helper.get_category(categories,false);
	for (int i = 0; i < categories.size(); i++) {
		tab_bar->addTab(categories[i].name + "(" + QString::number(categories[i].total) + ")");
		map2.insert(i, categories[i].id);
	}
	connect(tab_bar, &QTabBar::currentChanged, this, &ApplicationManager::tabChange);

	tab_bar->setCurrentIndex(0);
	emit refresh();
}
ApplicationManager *application_manager;