#include "DevStatusWindow.h"
#include "ui_DevStatusWindow.h"

#include <QTimer>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QStandardItemModel>

DevStatusWindow::DevStatusWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DevStatusWindow)
{
    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);

    // 设置stackWidget的大小
    ui->stackedWidget->setGeometry(0, 60, screenRect.width(), screenRect.height() - 60);

    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();

    sigGenDevice = new SignalGenerator(this);
    freqTunDevice = new FrequencyTuning(this);
    timeSwitDevice = new TimeSwitcher(this);
    freqSwitDevice = new FreqSwitcher(this);
    timeRepDevice = new TimeReplicator(this);
    freqRepDevice = new FreqReplicator(this);
    bCodeTermDevice = new BCodeTerminal(this);

    connect(freqTunDevice, &FrequencyTuning::sendDataToDraw,
            this, &DevStatusWindow::drawFrameDataOnPage);

    this->kafkaConsumer = new QKafkaConsumer(this);

    connect(kafkaConsumer, &QKafkaConsumer::messageRecieved,
            this, &DevStatusWindow::devSettingCommandRecieved);

    kafkaConsumer->setBrokers("111.198.10.15:12502");
    kafkaConsumer->setTopic("cppTest");
    kafkaConsumer->createConsumer();
    kafkaConsumer->start();

}

DevStatusWindow::~DevStatusWindow()
{
    kafkaConsumer->deleteLater();

    delete ui;
    delete kafkaConsumer;
}

void DevStatusWindow::drawFrameDataOnPage(DeviceFrameBaseDto * frameData)
{
    // 当前显示的设备编号
    if (frameData->frameType == "0301")
    {
        FrequencyTuningStatusFreqDto * freqFrameDto = (FrequencyTuningStatusFreqDto *) frameData;
        ui->ftDevStatus->setText(freqFrameDto->devStatus == "1" ? "正常" : "异常");
        ui->ftInputValid->setText(freqFrameDto->inputValid == "1" ? "有效" : "无效");
        ui->ftInputTimeType->setText(freqFrameDto->inputTimeType == "1" ? "5MHz" : "10MHz");
        ui->ftFreqAdjustAcc->setText(QString("%1 pHz").arg(freqFrameDto->freqAdjustAcc));
        ui->ftPulseAdjustAcc->setText(QString("%1 fs").arg((float) freqFrameDto->pulseAdjustAcc * 0.1));
    } else if (frameData->frameType == "0302")
    {
        FrequencyTuningStatusPulseDto * pulseFrameDto = (FrequencyTuningStatusPulseDto *) frameData;
        ui->ftSynchStatus->setText(pulseFrameDto->synchStatus == "1" ? "正常" : "异常");
        ui->ftRefValid->setText(pulseFrameDto->refValid == "1" ? "有效" : "无效");
        ui->ftSecondDiff->setText(QString("%1 ns").arg(pulseFrameDto->secondDiff));
        ui->ftPhaseShiftAcc->setText(QString("%1 ps").arg(pulseFrameDto->phaseShiftAcc));
        ui->ftPulseWidth->setText(QString("%1 ns").arg(pulseFrameDto->pulseWidth));
    }
}

void DevStatusWindow::devSettingCommandRecieved(QString commandJsonStr)
{
    std::cout << commandJsonStr.toStdString() << std::endl;
    QJsonParseError jsonErr;
    QJsonDocument doc = QJsonDocument::fromJson(commandJsonStr.toUtf8(), &jsonErr);
    if (jsonErr.error == QJsonParseError::NoError)
    {
        QJsonObject commandJson = doc.object();
        QString deviceId;
        QString deviceType;
        QString command;
        QString params;
        if (commandJson.contains("deviceType") == true)
        {
            deviceType = commandJson.value("deviceType").toString();
            if (deviceType.isEmpty() == false)
            {
                for (int i = 0; i < ui->devTypeSelect->count(); i++)
                {
                    if (ui->devTypeSelect->itemData(i).toString() == deviceType)
                    {
                        ui->devTypeSelect->setCurrentIndex(i);
                    }
                }
            }
        }

        if (commandJson.contains("deviceId") == true)
        {
            deviceId = commandJson.value("deviceId").toString();
            if (deviceId.isEmpty() == false)
            {
                for (int i = 0; i < ui->devSelect->count(); i++)
                {
                    if (ui->devSelect->itemData(i).toJsonObject().find("deviceId")->toString() == deviceId)
                    {
                        ui->devSelect->setCurrentIndex(i);
                    }
                }
            }
        }

        if (commandJson.contains("command") == true)
        {
            command = commandJson.value("command").toString();
        }
        if (commandJson.contains("params") == true)
        {
            params = commandJson.value("params").toString();
        }

        std::cout << deviceId.toStdString() << " " << deviceType.toStdString() << " " << command.toStdString() << " " << params.toStdString() << std::endl;

        if (deviceType == "03")
        {
            QByteArray commandBytes = freqTunDevice->protocol->generateSettingCommand(command, params);
            freqTunDevice->sendDataToSerial(commandBytes);
        }
    }
}

int DevStatusWindow::initHttpToken()
{
    QJsonObject response = httpReq->getTokenByClientId(SettingConfig::getInstance().CLIENT_ID,
                                                       SettingConfig::getInstance().APP_KEY);
    return response.find("code")->toInt();
}
int DevStatusWindow::initDictDeviceTypes()
{
    QJsonObject response = httpReq->initDictDeviceType();
    QJsonArray typeArray = response.find("data")->toArray();
    for (int i = 3; i < typeArray.size(); i++)
    {
        QJsonObject typeItem = typeArray.at(i).toObject();
        ui->devTypeSelect->addItem(typeItem.find("name")->toString(), typeItem.find("value")->toString());
    }

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

    return response.find("code")->toInt();
}
QJsonObject DevStatusWindow::initDeviceList()
{
    QString devType = ui->devTypeSelect->currentText();
    QJsonObject response = httpReq->initDeviceList(devType);

    qDebug() << response;

    ui->devSelect->clear();

    QJsonArray devArray = response.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);
    }

    // 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 });
    }

    return response;
}

void DevStatusWindow::on_sigGenButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    sigGenDevice->setComName("SignalGenerator");
    sigGenDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    sigGenDevice->setDevCode(devItem.find("deviceNo")->toString());
    sigGenDevice->setDeviceId(devItem.find("deviceId")->toString());

    sigGenDevice->initSerialPort();
}

void DevStatusWindow::on_freqTunButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    freqTunDevice->setComName("FrequencyTuning");
    freqTunDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    freqTunDevice->setDevCode(devItem.find("deviceNo")->toString());
    freqTunDevice->setDeviceId(devItem.find("deviceId")->toString());

    freqTunDevice->initSerialPort();
}

void DevStatusWindow::on_tmSwiButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    timeSwitDevice->setComName("TimeSwitcher");
    timeSwitDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    timeSwitDevice->setDevCode(devItem.find("deviceNo")->toString());
    timeSwitDevice->setDeviceId(devItem.find("deviceId")->toString());

    timeSwitDevice->initSerialPort();
}

void DevStatusWindow::on_freqSwiButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    freqSwitDevice->setComName("FreqSwitcher");
    freqSwitDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    freqSwitDevice->setDevCode(devItem.find("deviceNo")->toString());
    freqSwitDevice->setDeviceId(devItem.find("deviceId")->toString());

    freqSwitDevice->initSerialPort();
}

void DevStatusWindow::on_tmRepButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    timeRepDevice->setComName("TimeReplicator");
    timeRepDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    timeRepDevice->setDevCode(devItem.find("deviceNo")->toString());
    timeRepDevice->setDeviceId(devItem.find("deviceId")->toString());

    timeRepDevice->initSerialPort();
}

void DevStatusWindow::on_freqRepButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    freqRepDevice->setComName("FreqReplicator");
    freqRepDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    freqRepDevice->setDevCode(devItem.find("deviceNo")->toString());
    freqRepDevice->setDeviceId(devItem.find("deviceId")->toString());

    freqRepDevice->initSerialPort();
}

void DevStatusWindow::on_bctButt_clicked()
{
    // 获取设备对象
    QJsonObject devItem = ui->devSelect->currentData().toJsonObject();

    bCodeTermDevice->setComName("BCodeTerminal");
    bCodeTermDevice->setBaudRate(devItem.find("baudRate")->toString().toInt());
    bCodeTermDevice->setDevCode(devItem.find("deviceNo")->toString());
    bCodeTermDevice->setDeviceId(devItem.find("deviceId")->toString());

    bCodeTermDevice->initSerialPort();
}

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

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

void DevStatusWindow::on_devTypeSelect_currentIndexChanged(int index)
{
    this->initDeviceList();

    ui->stackedWidget->setCurrentIndex(index);
}

void DevStatusWindow::on_ftSetFreqTurnButt_clicked()
{
    freqTunDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qlonglong value = ui->ftSetFreqTurn->text().toLongLong();
    if (value < -2E12 || value > 2E12)
    {
        QMessageBox::information(this, "数据错误", "调整范围-2E-7 ~ 2E-7，（单位：1E-19）");
    } else
    {
        QByteArray setBytes = freqTunDevice->protocol->generateSettingCommand("GLF,20", ui->ftSetFreqTurn->text());
        ui->ftSetFreqTurnRaw->setText(setBytes);
        freqTunDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_ftSetPhaseTunnButt_clicked()
{
    freqTunDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qlonglong value = ui->ftSetPhaseTunn->text().toLongLong();
    if (value < -1E10 || value > 1E10)
    {
        QMessageBox::information(this, "数据错误", "调整范围-1us~+1us，（单位：0.1fs）");
    } else
    {
        QByteArray setBytes = freqTunDevice->protocol->generateSettingCommand("GLF,21", ui->ftSetPhaseTunn->text());
        ui->ftSetPhaseTunnRaw->setText(setBytes);
        freqTunDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_ftSetPhaseShiftButt_clicked()
{
    freqTunDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qlonglong value = ui->ftSetPhaseShift->text().toLongLong();
    if (value < -5E11 || value > 5E11)
    {
        QMessageBox::information(this, "数据错误", "取值范围-500ms - 500ms");
    } else
    {
        QByteArray setBytes = freqTunDevice->protocol->generateSettingCommand("GLP,01", ui->ftSetPhaseShift->text());
        ui->ftSetPhaseShiftRaw->setText(setBytes);
        freqTunDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_ftSetSynchButt_clicked()
{
    freqTunDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qint8 value = ui->ftSetSynch->text().toInt();
    if (value != 1)
    {
        QMessageBox::information(this, "数据错误", "1：有效；其他无效");
    } else
    {
        QByteArray setBytes = freqTunDevice->protocol->generateSettingCommand("GLP,02", ui->ftSetSynch->text());
        ui->ftSetSynchRaw->setText(setBytes);
        freqTunDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_ftSetPulseWidthButt_clicked()
{
    freqTunDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qlonglong value = ui->ftSetPulseWidth->text().toLongLong();
    if (value < 10 * 1000 || value > 500 * 1000 * 1000)
    {
        QMessageBox::information(this, "数据错误", "取值范围10us - 500ms");
    } else
    {
        QByteArray setBytes = freqTunDevice->protocol->generateSettingCommand("GLP,03", ui->ftSetPulseWidth->text());
        ui->ftSetPulseWidthRaw->setText(setBytes);
        freqTunDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgLeapSecondSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qint8 value = ui->sgLeapSecondSet->text().toInt();
    if (value != 1 && value != 2 && value != 3)
    {
        QMessageBox::information(this, "数据错误", "取值范围0 / 1 / 2");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,01", ui->sgLeapSecondSet->text());
        ui->sgLeapSecondSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgSingleSynchSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qint8 value = ui->sgSingleSynchSet->text().toInt();
    if (value != 1)
    {
        QMessageBox::information(this, "数据错误", "1：有效；其他无效");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,02", ui->sgSingleSynchSet->text());
        ui->sgSingleSynchSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgDateSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    QString value = ui->sgDateSet->text();
    if (value.length() != 8)
    {
        QMessageBox::information(this, "数据错误", "年月日格式：YYYYMMDD");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,03", ui->sgDateSet->text());
        ui->sgDateSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgSecondWidthSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qlonglong value = ui->sgSecondWidthSet->text().toLongLong();
    if (value < 10 * 1000 || value > 500 * 1000 * 1000)
    {
        QMessageBox::information(this, "数据错误", "取值范围10us - 500ms");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,04", ui->sgSecondWidthSet->text());
        ui->sgSecondWidthSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgBacRatioSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qint8 value = ui->sgBacRatioSet->text().toInt();
    if (value < 2 || value > 6)
    {
        QMessageBox::information(this, "数据错误", "取值范围2 - 6");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,05", ui->sgBacRatioSet->text());
        ui->sgBacRatioSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgBacRangeSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    float value = ui->sgBacRangeSet->text().toFloat();
    if (value < 5 || value > 100)
    {
        QMessageBox::information(this, "数据错误", "取值范围5 - 100");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,06", ui->sgBacRangeSet->text());
        ui->sgBacRangeSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgOppsPhaseShiftSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    qlonglong value = ui->sgOppsPhaseShiftSet->text().toLongLong();
    if (value < -1E12 || value > 1E12)
    {
        QMessageBox::information(this, "数据错误", "取值范围-1s - 1s");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,07", ui->sgOppsPhaseShiftSet->text());
        ui->sgOppsPhaseShiftSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgLeapTimestampSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    QString value = ui->sgLeapTimestampSet->text();
    if (value.length() != 8)
    {
        QMessageBox::information(this, "数据错误", "年月日格式：YYYYMMDD");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,08", ui->sgLeapTimestampSet->text());
        ui->sgLeapTimestampSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgMJDDateSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    QString value = ui->sgMJDDateSet->text();
    if (value.length() != 5)
    {
        QMessageBox::information(this, "数据错误", "MJD");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,09", ui->sgMJDDateSet->text());
        ui->sgMJDDateSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgTimeSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    QString value = ui->sgTimeSet->text();
    if (value.length() != 6)
    {
        QMessageBox::information(this, "数据错误", "hhmmss");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLF,10", ui->sgTimeSet->text());
        ui->sgTimeSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgKeyControlSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    QString value = ui->sgKeyControlSet->text();
    if (value != "0" && value != "1")
    {
        QMessageBox::information(this, "数据错误", "0 / 1");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLC,01", ui->sgKeyControlSet->text());
        ui->sgKeyControlSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}

void DevStatusWindow::on_sgTimeTypeSetButt_clicked()
{
    sigGenDevice->setDevCode(ui->devSelect->currentData().toJsonObject().find("deviceNo")->toString());
    QString value = ui->sgTimeTypeSet->text();
    if (value != "0" && value != "1")
    {
        QMessageBox::information(this, "数据错误", "0 / 1");
    } else
    {
        QByteArray setBytes = sigGenDevice->protocol->generateSettingCommand("GLC,02", ui->sgTimeTypeSet->text());
        ui->sgTimeTypeSetRaw->setText(setBytes);
        sigGenDevice->sendDataToSerial(setBytes);
    }
}
