#include "QWMonitor.h"

#include "app/Application.h"
#include "app/AppData.h"
#include "app/Station.h"
#include "app/Device.h"
#include "common/Utils.h"
#include "app/DataStruct.h"

QWMonitor::QWMonitor(QWidget* parent) : MyWidget(parent) 
{
	//this->setStyleSheet("background-color: red;");
	int x = 10, y = 10;
	for (auto& iter: Application::data().mapStation)
	{
		auto station = iter.second;
		auto btn = make_shared<QPushButton>(station->name.c_str(), this);
		btn->setGeometry(x, y, 120, 36);
		btn->setStyleSheet(QSS_BTN.c_str());
		x += 130;

		if (!curActiveBtn)
		{
			curActiveBtn = btn;
			curActiveBtn->setStyleSheet(QSS_BTN_ACTIVE.c_str());
		}
		mapBtnStation[btn] = station;

		connect(btn.get(), &QPushButton::clicked, this, [=]()
			{
				if (btn != curActiveBtn)
				{
					if (curActiveBtn) { curActiveBtn->setStyleSheet(QSS_BTN.c_str()); }
					if (btn) { btn->setStyleSheet(QSS_BTN_ACTIVE.c_str()); }
					curActiveBtn = btn;
					this->initStation(station);
				}
			});
	}

	QStringList headerTextList;
	headerTextList << "ID" << "类型ID" << "类型名称" << "设备名称" << "编号" << "状态" << "通讯\n状态" << "工作\n状态" << "故障\n状态" << "--";

	table = MyQUI::TableWidget(this, 10, y += 50, 700, 800);
	// 设置为水平表头
	table->setColumnCount(headerTextList.size());
	table->setHorizontalHeaderLabels(headerTextList);
	table->setColumnWidth(0, 50);
	table->setColumnWidth(1, 60);
	table->setColumnWidth(2, 120);
	table->setColumnWidth(3, 160);

	connect(table.get(), &QTableWidget::currentCellChanged, this, &QWMonitor::onCurrentCellChanged);

	if (curActiveBtn)
	{
		this->initStation(mapBtnStation[curActiveBtn]);
	}

	this->groupStation = MyQUI::GroupBox(this, 730, y, 480, 800, "设备信息");

	labDeviceInfo = std::make_shared<QLabel>(groupStation.get());
	labDeviceInfo->setGeometry(10, 20, 400, 26);

	// 将内容widget设置为滚动区域的widget
	uiReg.scroll = new QScrollArea(groupStation.get());
	uiReg.scroll->setFixedHeight(600); // 设置滚动区域固定高度600px
	uiReg.scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); // 垂直滚动条在需要时出现
	//scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); // 水平滚动条在需要时出现
	uiReg.scroll->setGeometry(10, 90, 460, 700);
	uiReg.scroll->setObjectName("MyScroll");
	uiReg.scroll->setStyleSheet("#MyScroll {background-color: transparent; border: 1px solid gray;}");
	uiReg.scroll->setWidgetResizable(true);

	std::string QSS_LISTVIEW =
		"QListView { background-color: transparent; color: white; outline: 1px solid #409EFF;}"
		"QListView::item { background-color: transparent; border-bottom: 0px solid gray; padding: 0px; height: 20px; }";

	uiReg.listReg = new QListWidget(groupStation.get());
	uiReg.listReg->setStyleSheet(QSS_LISTVIEW.c_str());
	uiReg.scroll->setWidget(uiReg.listReg);
};

QWMonitor::~QWMonitor()
{
	curDevice = nullptr;
	curStation = nullptr;
	curActiveBtn = nullptr;
	mapBtnStation.clear();
	table->clear();
}

void QWMonitor::initStation(shared_ptr<Station> station)
{
	table->clearSelection();
	this->curDevice = NULL;
	if (uiReg.listReg) 
	{
		uiReg.listReg->clearSelection();
		uiReg.listReg->clear();
	}
	this->updateStation(station);
}

void QWMonitor::updateStation(shared_ptr<Station> station)
{
	auto& appdata = Application::data();
	//table->clearContents();
	int row = 0;
	for (auto& iter : station->mapDevice)
	{
		auto& device = iter.second;
		MyQUI::setTableCellText(table, row, 0, Utils::toStr(device->deviceId));
		MyQUI::setTableCellText(table, row, 1, Utils::toStr(device->type));
		MyQUI::setTableCellText(table, row, 2, appdata.getDeviceNameById(device->type));
		MyQUI::setTableCellText(table, row, 3, device->name);
		MyQUI::setTableCellText(table, row, 4, device->code);
		MyQUI::setTableCellText(table, row, 5, device->isOpen ? "启用" : "未启用", device->isOpen ? "OK" : "ERR");
		MyQUI::setTableCellText(table, row, 6, device->online ? "在线" : "离线", device->online ? "OK" : "ERR");
		MyQUI::setTableCellText(table, row, 7, device->running ? "工作" : "空闲", device->running ? "OK" : "WARN");
		MyQUI::setTableCellText(table, row, 8, device->err ? "故障" : "正常", device->err ? "ERR" : "OK");
		++row;
	}

	int rowCount = table->rowCount();
	for (int i = station->mapDevice.size(); i<rowCount; ++i)
	{
		table->removeRow(i);
	}
}


shared_ptr<Station> QWMonitor::getCurrentStation()
{
	return curActiveBtn ? mapBtnStation[curActiveBtn] : nullptr;
}

void QWMonitor::onCurrentCellChanged(int row, int col, int oldRow, int oldCol)
{
	auto station = getCurrentStation();
	if (!station)
	{
		labDeviceInfo->setText("--");
		return;
	}
	if (row != oldRow)
	{
		auto item = table->item(row, 0);
		if (item)
		{
			auto deviceId = item->text().toInt();
			curDevice = station->getDevice(deviceId);
			if (curDevice)
			{
				string info = curDevice->name + "    ";
				info += (curDevice->ts > 0) ? Utils::timeStr(curDevice->ts) : "--";
				labDeviceInfo->setText(info.c_str());
				return;
			}
		}
	}
}

void QWMonitor::onTimer()
{
	auto station = getCurrentStation();
	if (!station) return;

	this->updateStation(station);

	if (curDevice)
	{
		auto mapRegPtr = REGAddr::getRegMapByDeviceType(curDevice->type);
		auto& mapDeviceParams = curDevice->mapParams;

		stringstream ss;
		int ind = 0;
		for (auto& iter : mapDeviceParams)
		{
			ss.str("");

			auto& addr = iter.first;
			ss << std::setw(3) << std::setfill('0') << ind << ":  " << addr << ": " << iter.second;
			if (mapRegPtr) {
				auto iter = mapRegPtr->find(addr);
				if (iter != mapRegPtr->end())
				{
					ss << " (" << iter->second.name << ")";
				}
			}
			ss << "\n";

			if (ind < uiReg.listReg->count())
			{
				uiReg.listReg->item(ind)->setText(ss.str().c_str());
			}
			else
			{
				uiReg.listReg->addItem(ss.str().c_str());
			}
			++ind;
		}
		for (int i = uiReg.listReg->count()-1; i>=ind; --i)
		{
			uiReg.listReg->takeItem(i);
		}
	}
}