#include "addcategory.h"
#include <QString>
AddCategory::AddCategory(QWidget* parent)
	: QDialog(parent)
{
	ui.setupUi(this);
	setWindowFlags(Qt::WindowCloseButtonHint);
	setFixedSize(900, 600);
	//connect(ui.submit, &QPushButton::click, this, &AddCategory::submit);
	QStringList title;
	ui.tableWidget->setColumnCount(3);
	title << QString::fromLocal8Bit("名称") << QString::fromLocal8Bit("显示") << QString::fromLocal8Bit("排序");
	ui.tableWidget->setHorizontalHeaderLabels(title);
	sqlite_helper.get_category(categrories);
	ui.tableWidget->setRowCount(categrories.count());
	int i = 0;
	for(auto category : categrories)
	{
		ui.tableWidget->setItem(i, 0, new QTableWidgetItem(category.name));
		if(category.id==1&&category.id==8)
		{
			ui.tableWidget->item(i, 0)->setFlags(ui.tableWidget->item(i, 0)->flags() & (~Qt::ItemIsEditable));
		}
		QComboBox* combo_box = new QComboBox;
		combo_box->addItem(QString::fromLocal8Bit("显示"), true);
		combo_box->addItem(QString::fromLocal8Bit("不显示"), false);
		if(category.display==true)
		{
			combo_box->setCurrentIndex(0);
		}else
		{
			combo_box->setCurrentIndex(1);
		}
		ui.tableWidget->setCellWidget(i, 1, combo_box);
		ui.tableWidget->setItem(i, 2, new QTableWidgetItem(QString::number(category.sort)));
		combo_boxes << combo_box;
		i++;
	}
	//submit_btn = new QPushButton(QString::fromLocal8Bit("提交"));
	connect(ui.submit, &QPushButton::clicked, this, &AddCategory::submit);
}
AddCategory::~AddCategory()
{
	for(auto combo_box : combo_boxes)
	{
		delete combo_box;
	}
}
void AddCategory::submit()
{
	int num = categrories.count();
	QList<Categrory> categrories_new;
	int i=0;
	for(Categrory categrory:categrories)
	{
		categrory.name = ui.tableWidget->item(i, 0)->text();
		QComboBox * combox =(QComboBox *)ui.tableWidget->cellWidget(i, 1);
		categrory.display = combox->currentData().toBool();
		bool ok;
		categrory.sort = ui.tableWidget->item(i, 2)->text().toInt(&ok, 10);
		if(!ok)
		{
			QMessageBox::critical(this, QString::fromLocal8Bit("错误"), QString::fromLocal8Bit("排序列中有一行不是数字"));
			return;
		}
		categrories_new << categrory;
		i++;
	}
	categrories.clear();
	categrories = categrories_new;
	changed = true;
	close();
}
