#include "DialogPop.h"

DialogPop::DialogPop(QWidget* parent, const Fields& rowdata, string oper) 
	: QDialog(parent), originData(rowdata), oper(oper)
{
	// 设置背景色
	QPalette palette(this->palette());
	palette.setColor(QPalette::Window, QColor(36, 56, 90));
	this->setAutoFillBackground(true);
	this->setPalette(palette);
	this->setStyleSheet("color: white;");

	vecWidgetParams.reserve(20);
	btnOk.setParent(this);
	btnOk.setText("确  定");
	btnOk.setStyleSheet(QSS_BTN.c_str());

	btnCancel.setParent(this);
	btnCancel.setText("取  消");
	btnCancel.setStyleSheet(QSS_BTN.c_str());

	QObject::connect(&btnOk, &QPushButton::clicked, this, &DialogPop::slotBtnAccept);
	QObject::connect(&btnCancel, &QPushButton::clicked, this, &DialogPop::reject);

	this->setFixedSize(500, 500);
}

void  DialogPop::addParam(string key, string title, shared_ptr<QWidget> widget)
{
	auto label = make_shared<QLabel>(title.c_str(), this);
	int n = vecWidgetParams.size();
	vecWidgetParams.push_back({ label, widget });
	int y = 60 + 40 * n;
	label->setGeometry(60, y, 80, 30);
	widget->setGeometry(140, y, 280, 30);
	widget->setObjectName(key.c_str());
}

void DialogPop::addParamLine(string key, string title, bool readlonly /*= false*/)
{
	auto lineedit = make_shared<QLineEdit>(this);
	lineedit->setStyleSheet(QSS_LINE.c_str());
	lineedit->setText(originData.value(key).c_str());
	if (readlonly) { lineedit->setReadOnly(true); }
	this->addParam(key, title, lineedit);

	QObject::connect(lineedit.get(), &QLineEdit::textChanged, this, &DialogPop::slotLineTextChanged);
}

void DialogPop::addParamCombox(string key, string title, const vector<pair<string, string>>& mapping)
{
	auto combox = make_shared<QComboBox>(this);
	combox->setStyleSheet(QSS_BTN_COMBOX.c_str());
	this->addParam(key, title, combox);


	string val = originData.value(key);
	for (int i = 0; i < mapping.size(); ++i)
	{
		auto& item = mapping[i];
		combox->insertItem(i, item.second.c_str());
		combox->setItemData(i, item.first.c_str());
		if (val == item.first) combox->setCurrentText(item.second.c_str());
	}
	QObject::connect(combox.get(), &QComboBox::currentIndexChanged, this, &DialogPop::slotComboxIndexChanged);
}

void DialogPop::slotLineTextChanged(const QString& s)
{
	auto lineedit = dynamic_cast<QLineEdit*>(sender());
	string key = lineedit->objectName().toStdString();
	curData.set(key, s.toStdString());
}

void DialogPop::slotComboxIndexChanged(int index)
{
	auto combox = dynamic_cast<QComboBox*>(sender());
	string key = combox->objectName().toStdString();
	string val = combox->itemData(index).toString().toStdString();
	curData.set(key, val);
}

void DialogPop::slotBtnAccept()
{
	this->onAccept();
	this->accept();
}

void DialogPop::slotBtnReject()
{
}

void DialogPop::resizeEvent(QResizeEvent* e)
{
	int w = 100, offset = 30;
	int x = e->size().width() * 0.5 - w - offset;
	int y = e->size().height() - 80;
	btnOk.setGeometry(x, y, w, 40);
	btnCancel.setGeometry(x + w + offset*2, y, w, 40);
}