#include "CounterWindow.h"
#include "ui_CounterWindow.h"

#include <iostream>
#include <QTimer>
#include <QDateTime>
#include <QLabel>
#include <QGroupBox>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QDesktopWidget>
#include <QThread>

CounterWindow::CounterWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CounterWindow)
{
    ui->setupUi(this);

    // 无边框
    this->setWindowFlags(Qt::FramelessWindowHint);

    // 窗口大小为占满一屏
    QRect screenRect = QApplication::desktop()->screenGeometry();
    resize(screenRect.width(), screenRect.height());

    // 将窗口移动到左上角
    move(0, 0);
    ui->exitButt->move(screenRect.width() - 80, 10);
    ui->minButt->move(screenRect.width() - 140, 10);
    ui->line->setGeometry(0, 59, screenRect.width(), 1);

    // 设置主体区域的大小和位置
    ui->scrollArea->setGeometry(0, 60, screenRect.width(), screenRect.height() - 60);
    ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);

    httpReq = new HttpRequestController(this);
    // 1. 获取访问接口需要的token
    int retCode = this->initHttpToken();
    if (retCode != 200)
    {
        QMessageBox::information(this, "错误", "获取http请求的token失败，程序即将退出");

        QTimer::singleShot(1000, qApp, SLOT(quit()));
    }
    // 2. 获取字典值：设备类型
    retCode = this->initDictDeviceTypes();

    // 3. 获取计数器设备列表
    QJsonObject devListRes = this->initDeviceList();
    if (devListRes.find("code")->toInt() == 200)
    {
        ui->devSelect->clear();

        // 4. 将获取到的设备添加到下拉列表框中
        QJsonArray devArray = devListRes.find("data")->toArray();
        for (int i =0; i < devArray.size(); i++)
        {
            QJsonObject devItem = devArray.at(i).toObject();
            ui->devSelect->addItem(devItem.find("deviceName")->toString(), devItem.find("deviceNo")->toString());

            CounterDevice * device = new CounterDevice(this);
            deviceList.append(device);

            device->setComName(devItem.find("linkComName")->toString());
            device->setBaudRate(SettingConfig::getInstance().BAUD_RATE);
            device->setDevCode(devItem.find("deviceNo")->toString());
            device->setDeviceId(devItem.find("deviceId")->toString());

            connect(device, &CounterDevice::sendDataToDraw,
                    this, &CounterWindow::drawCounterDataOnPage);

            device->initSerialPort();

            QThread::msleep(200);
        }
        // 5. 设置下拉框的样式
        QStandardItemModel * model = qobject_cast<QStandardItemModel*>(ui->devSelect->model());
        for (int i = 0; i < model->rowCount(); ++i)
        {
            QStandardItem * item = model->item(i);
            item->setSizeHint({ 0, 30 });
        }
    }

    // 6. 绘制一个设备的多个通道数据面板
    this->generateWidgetForDevice();
}

CounterWindow::~CounterWindow()
{
    delete ui;
}

void CounterWindow::generateWidgetForDevice()
{
    // 获取设备数据
    int channelNum = 16;

    QRect screenRect = QApplication::desktop()->screenGeometry();

    ui->scrollContents->setGeometry(0, 60, screenRect.width(), channelNum * 90);

    QVBoxLayout * layout = new QVBoxLayout(ui->scrollContents);
    const QFont labelFont("微软雅黑", 10);

    for (int i = 0; i < channelNum; i++)
    {
        QGroupBox * group = new QGroupBox(ui->scrollContents);
        group->setTitle(QString("通道 - %1").arg(i + 1));
        group->setFont(QFont("微软雅黑", 12));
        group->setGeometry(20, i * 80 + 10, screenRect.width() - 40, 80);

        QHBoxLayout * vbox = new QHBoxLayout(group);

        QLabel * tmLabel = new QLabel();
        tmLabel->setText("时间");
        tmLabel->setFont(labelFont);
        tmLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(tmLabel);
        QLineEdit * tmValue = new QLineEdit();
        tmValue->setFixedWidth(200);
        tmValue->setFont(labelFont);
        vbox->addWidget(tmValue);

        QLabel * dataLabel = new QLabel();
        dataLabel->setText("测量数据");
        dataLabel->setFont(labelFont);
        dataLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(dataLabel);
        QLineEdit * dataValue = new QLineEdit();
        dataValue->setFixedWidth(200);
        dataValue->setFont(labelFont);
        vbox->addWidget(dataValue);

        QLabel * idLabel = new QLabel();
        idLabel->setText("数据ID");
        idLabel->setFont(labelFont);
        idLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(idLabel);
        QLineEdit * idValue = new QLineEdit();
        idValue->setFixedWidth(75);
        idValue->setFont(labelFont);
        vbox->addWidget(idValue);

        QLabel * refChLabel = new QLabel();
        refChLabel->setText("参考通道");
        refChLabel->setFont(labelFont);
        refChLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(refChLabel);
        QLineEdit * refChValue = new QLineEdit();
        refChValue->setFixedWidth(60);
        refChValue->setFont(labelFont);
        vbox->addWidget(refChValue);

        QLabel * loadLabel = new QLabel();
        loadLabel->setText("负载");
        loadLabel->setFont(labelFont);
        loadLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(loadLabel);
        QLineEdit * loadValue = new QLineEdit();
        loadValue->setFixedWidth(60);
        loadValue->setFont(labelFont);
        vbox->addWidget(loadValue);

        QLabel * levelLabel = new QLabel();
        levelLabel->setText("触发电平");
        levelLabel->setFont(labelFont);
        levelLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(levelLabel);
        QLineEdit * levelValue = new QLineEdit();
        levelValue->setFixedWidth(60);
        levelValue->setFont(labelFont);
        vbox->addWidget(levelValue);

        QLabel * validLabel = new QLabel();
        validLabel->setText("-");
        validLabel->setFont(labelFont);
        validLabel->setStyleSheet("margin-left:20;");
        vbox->addWidget(validLabel);

        QSpacerItem * hSpace = new QSpacerItem(20, 20);
        hSpace->changeSize(20, 20, QSizePolicy::Expanding);
        vbox->addItem(hSpace);

        group->setLayout(vbox);

        layout->addWidget(group);
    }
}

void CounterWindow::drawCounterDataOnPage(CounterDataDto * counterData)
{
    // 当前显示的设备编号
    QString currentDevCode = ui->devSelect->currentData().toString();

    // 如果不是当前设备的帧，直接返回
    if (counterData->devCode != currentDevCode)
    {
        return;
    }

    // 1. 判断数据属于哪个设备，显示在不同的widget上
//    qDebug() << counterData->toJSON() << counterData->devCode << "---" << counterData->frameId;

    // 获取对应的通道BOX
    QGroupBox * channelBox = (QGroupBox *)ui->scrollContents->children().at(counterData->channelId);

    // 赋值，对应的lineEdit/label
    ((QLineEdit *)channelBox->children().at(2))->setText(counterData->timestamp);
    ((QLineEdit *)channelBox->children().at(4))->setText(QString("%1 s").arg(counterData->channelClockValueStr));
    ((QLineEdit *)channelBox->children().at(6))->setText(counterData->frameId);
    ((QLineEdit *)channelBox->children().at(8))->setText(QString("%1").arg(counterData->channelRefId));
    ((QLineEdit *)channelBox->children().at(10))->setText(QString("%1 Ω").arg(counterData->load == 1 ? "1M" : "50"));
    ((QLineEdit *)channelBox->children().at(12))->setText(QString("%1 V").arg(counterData->level));
    ((QLabel *)channelBox->children().at(13))->setText(counterData->channelActive == 1 ? "有效" : "无效");

}

int CounterWindow::initHttpToken()
{
    QJsonObject response = httpReq->getTokenByClientId(SettingConfig::getInstance().CLIENT_ID,
                                                       SettingConfig::getInstance().APP_KEY);
    return response.find("code")->toInt();
}
int CounterWindow::initDictDeviceTypes()
{
    QJsonObject response = httpReq->initDictDeviceType();
    return response.find("code")->toInt();
}
QJsonObject CounterWindow::initDeviceList()
{
    QJsonObject response = httpReq->initDeviceList("计数器");
    return response;
}

void CounterWindow::on_exitButt_clicked()
{
    QApplication::exit(0);
}

void CounterWindow::on_minButt_clicked()
{
    setWindowState(Qt::WindowMinimized | windowState());
}
