#include "QWHome.h"
#include "common/Spdlogger.h"
#include "app/Config.h"
#include "common/Utils.h"
#include "app/Application.h"
#include "app/AppData.h"
#include "app/Station.h"
#include "protocol/MqttEntity.h"

#include "qt/QWSwitch.h"

QWHome::QWHome(QWidget* parent) : MyWidget(parent)
{
    this->setObjectName("home");
    this->setStyleSheet("#home { background-color:rgba(100,100,100,50); }");

    int x = 10, y = 0;
    {
        //this->groupSys = MyQUI::GroupBox(this, x, y, 1190, 120, "系统");
        //auto pw = groupSys.get();
    }
    {
        x = 10;
        this->groupHttp = MyQUI::GroupBox(this, x, y, 390, 200, "HTTP");
        auto pw = groupHttp.get();
        this->addPair("http-t", pw, 20, 20, "服务类型: ", "服务端");
        this->addPair("http-p", pw, 20, 50, "服务端口: ", Utils::toStr(Config::option.http.port));
        this->addPair("http-s", pw, 20, 80, "服务状态: ", "运行");

        QWSwitch* switchBtn = new QWSwitch(this);
        switchBtn->setGeometry(30, 110, 50, 20);
    }
    {
        x += 400;
        this->groupMqtt = MyQUI::GroupBox(this, x, y, 390, 200, "MQTT");
        auto pw = groupMqtt.get();
        this->addPair("mqtt-t", pw, 20, 20, "服务类型: ", "客户端");
        this->addPair("mqtt-h", pw, 20, 50, "服务地址: ", Config::option.mqtt.host);
        this->addPair("mqtt-s", pw, 20, 80, "服务状态: ", "---");
    }
    {
        x += 400;
        this->groupDB = MyQUI::GroupBox(this, x, y, 390, 200, "数据库");
        auto pw = groupDB.get();
        this->addPair("db-n", pw, 20, 20, "数据库名: ", Config::option.database.dbname);
        this->addPair("db-h", pw, 20, 50, "主机地址: ", Config::option.database.host);
        this->addPair("db-u", pw, 20, 80, "用 户 名: ", Config::option.database.user);
    }

    QStringList headerTextList;
    headerTextList << "ID" << "站名" << "编号" << "状态" << "MQTT状态" << "召测(秒)"
        << "日充电\n电量" << "日放电\n电量" << "总充电\n电量" << "总放电\n电量"
        << "日充电\n费用" << "日放电\n费用" << "总充电\n费用" << "总放电\n费用"
        << "日收益" << "总收益" << "--";
    table = MyQUI::TableWidget(this, 10, y += 210, 1350, 265);
    // 设置为水平表头
    table->setColumnCount(headerTextList.size());
    table->setHorizontalHeaderLabels(headerTextList);
    table->setColumnWidth(0, 40);
    table->setColumnWidth(1, 120);
    table->setColumnWidth(2, 40);
    table->setColumnWidth(4, 80);
    table->setColumnWidth(5, 70);

    logFilter = MyQUI::PairLine(this, 10, y += 280, "日志过滤: ", "", false);
    btnLogClean = MyQUI::Button(this, 400, y-1, 80, 28, "清除");
    QObject::connect(btnLogClean.get(), &QPushButton::clicked, this, &QWHome::slotBtnClearLog);

    texteditLog = std::make_shared<QTextEdit>(this);
    texteditLog->setGeometry(10, y += 35, 1350, 340);
    texteditLog->setStyleSheet("background-color: transparent; border: 1px solid gray; font-weight: 400;");
    texteditLog->setReadOnly(true);
    texteditLog->document()->setMaximumBlockCount(1000);

    {
        ////////////////////////////////////////////////////////////////////////////////////////
        // QT显示spdlog: 方法一
        // 第二个参数是方法函数名称，即调用 QTextEdit的appeng函数；
        //auto qtSink = std::make_shared<spdlog::sinks::qt_sink_mt>(textLog.get(), "append");
        //spdlog::default_logger()->sinks().push_back(qtSink);

        ////////////////////////////////////////////////////////////////////////////////////////
        // QT显示spdlog: 方法二， 自定义实现 QtLogSink
        auto myqtSink = std::make_shared<QtLogSink>();
        spdlog::default_logger()->sinks().push_back(myqtSink);

        // 连接信号和槽，使用Qt::QueuedConnection确保线程安全
        QObject::connect(myqtSink.get(), &QtLogSink::logMessageReceived, this, &QWHome::onLogMessageReceived, Qt::QueuedConnection);
    }
}

QWHome::~QWHome()
{
    table->clear();
    mapPairs.clear();
}

void QWHome::addPair(string name, QWidget* parent, int x, int y, string k, string v, bool readonly /*= true*/)
{
    if (name.empty()) name = k;
    mapPairs[name] = MyQUI::PairLine(parent, x, y, k, v);
}

void QWHome::onTimer()
{
    if (!this->isVisible()) { return; }

    auto& appdata = Application().data();
    int rowNo = 0;
    int tsNow = Utils::time();
    for (auto& item : appdata.mapStation)
    {
        auto& station = item.second;
        if (rowNo >= table->rowCount())
        {
            table->insertRow(rowNo);
        }
        bool isOpen = station->status > 0;
        bool isConnected = station->mqttCli->isConnected;

        MyQUI::setTableCellText(table, rowNo, 0, std::to_string(station->stationId));
        MyQUI::setTableCellText(table, rowNo, 1, station->name);
        MyQUI::setTableCellText(table, rowNo, 2, station->code);
        MyQUI::setTableCellText(table, rowNo, 3, isOpen ? "启用" : "未启用", isOpen ? "OK" : "ERR");
        MyQUI::setTableCellText(table, rowNo, 4, isConnected ? "连接成功" : "未连接", isConnected ? "OK" : "ERR");

        int tsPolling = station->getPollingTS();
        MyQUI::setTableCellText(table, rowNo, 5, tsPolling > 0 ? std::to_string(tsNow - tsPolling) + "/" + std::to_string(Config::option.mqtt.interval) : "--");
        MyQUI::setTableCellText(table, rowNo, 6, Utils::toStr(station->statData.dayElectIn, 0));
        MyQUI::setTableCellText(table, rowNo, 7, Utils::toStr(station->statData.dayElectOut, 0));
        MyQUI::setTableCellText(table, rowNo, 8, Utils::toStr(station->statData.totalElectIn, 0));
        MyQUI::setTableCellText(table, rowNo, 9, Utils::toStr(station->statData.totalElectOut, 0));
        MyQUI::setTableCellText(table, rowNo, 10, Utils::toStr(station->statData.dayFeeIn, 0));
        MyQUI::setTableCellText(table, rowNo, 11, Utils::toStr(station->statData.dayFeeOut, 0));
        MyQUI::setTableCellText(table, rowNo, 12, Utils::toStr(station->statData.totalFeeIn, 0));
        MyQUI::setTableCellText(table, rowNo, 13, Utils::toStr(station->statData.totalFeeOut, 0));
        MyQUI::setTableCellText(table, rowNo, 14, Utils::toStr(station->statData.dayIncome, 0));
        MyQUI::setTableCellText(table, rowNo, 15, Utils::toStr(station->statData.totalIncome, 0));
        MyQUI::setTableCellText(table, rowNo, 16, station->statData.ts > 0 ? Utils::timeStr(station->statData.ts) : "--");
        rowNo++;
    }
}

void QWHome::onLogMessageReceived(const QString& message)
{
    if (!this->isVisible()) { return; }

    bool show = true;
    if (logFilter.second)
    {
        auto filter = logFilter.second->text();
        if (!filter.isEmpty() && !message.contains(filter))
        {
            show = false;
        }
    }
    if (show)
    {
        texteditLog->append(message.trimmed());
    }
}

void QWHome::slotBtnClearLog()
{
    texteditLog->clear();
}