#include "CounterDevice.h"

#include <iostream>
#include <QDateTime>
#include <QDebug>

CounterDevice::CounterDevice(QObject *parent) : QObject(parent)
{
    connect(&this->serialUtil, &QSerialPortUtil::dataRecieved,
                this, &CounterDevice::dataReceivedHandler);

    kafkaUtil.setBrokers(SettingConfig::getInstance().KAFKA_BROKERS);
    kafkaUtil.setTopic(SettingConfig::getInstance().KAFKA_DATA_TOPIC);
    kafkaUtil.createProducer();
}

CounterDevice::~CounterDevice()
{
    disconnect(&this->serialUtil, &QSerialPortUtil::dataRecieved,
                this, &CounterDevice::dataReceivedHandler);
}

void CounterDevice::setComName(QString comName)
{
    this->comName = comName;
}
void CounterDevice::setBaudRate(int baudRate)
{
    this->baudRate = baudRate;
}
QString CounterDevice::getDevCode()
{
    return this->devCode;
}
void CounterDevice::setDevCode(QString devCode)
{
    this->devCode = devCode;
}
void CounterDevice::setDeviceId(QString deviceId)
{
    this->deviceId = deviceId;
}

bool CounterDevice::isSerialOpen()
{
    return this->serialUtil.isOpen();
}

void CounterDevice::initSerialPort()
{
    int master = SettingConfig::getInstance().MASTER;
    QStringList comNameList = this->comName.split(",");
    if (comNameList.isEmpty() == true)
    {
        return;
    }

    // 如果是主程序则打开主串口 备程序则打开备串口
    if (master == 1)
    {
        this->serialUtil.openSerialPort(comNameList.at(0), this->baudRate);
    } else
    {
        this->serialUtil.openSerialPort(comNameList.at(1), this->baudRate);
    }
}


void CounterDevice::dataReceivedHandler(QByteArray data)
{
    this->dataBuff.append(data);
//    std::cout << QByteUtil::binToHexString(this->dataBuff).toStdString() << std::endl;

    CounterDataDto * counterData = new CounterDataDto(this);
    if (CounterProtocolXH::checkFrame(this->dataBuff) == true)
    {
        counterData->rawFrame = this->dataBuff;

        // ★解析成数据对象
        bool parse = CounterProtocolXH::parseMessureData(this->dataBuff, counterData);

        // 解析成功
        if (parse == true)
        {
            this->dataBuff.clear();
            QDateTime now = QDateTime::currentDateTime();
            counterData->devCode = this->devCode;
            counterData->timestamp = now.toString("yyyy-MM-dd HH:mm:ss.zzz");
            counterData->milisecond = now.toMSecsSinceEpoch();
            this->afterFramePhase(counterData);
        }
    } else if (this->dataBuff.size() > COUNTER_FRAME_MIN_LENGTH)
    {
        std::cout << QString("%1").arg(this->dataBuff.size()).toStdString() << std::endl;
        this->dataBuff.clear();
    }

    // 在此处释放内存，不影响后续显示
    // 不在此处释放内存则会导致内存持续增加
    // 具体原因不明
    delete counterData;
}


void CounterDevice::afterFramePhase(CounterDataDto * counterData)
{
    // 0. 输出到日志文件中
    QString date = counterData->timestamp.mid(0, 10);

    // 1. 原始字节数组数据
    QString filename = "raw_" + devCode + ".log";
    QString content = counterData->timestamp + " " + counterData->rawFrame;
    QLogUtil::writeRawDataLogByDate(date, filename, content);

    QJsonArray messageArray;
    QString msgLogFilename = "msg_" + devCode + ".log";

    // 2. 各个通道的clock diff数据
    for (int i = 1; i <= counterData->channelActiveArray.size(); i++)
    {
        if (counterData->channelRefId == i)
        {
            continue;
        }
        if (counterData->channelActiveArray.at(i-1).toUInt() == 1)
        {
            QString chFilename("%1_CH_%2.log");
            chFilename = chFilename.arg(devCode);
            if (i < 10)
            {
                chFilename = chFilename.arg(QString("0%1").arg(i));
            } else
            {
                chFilename = chFilename.arg(i);
            }
            QString channelDataStr = QString("%1 [%2] %3").arg(counterData->timestamp).arg(counterData->frameId).arg(counterData->channelDataArray.at(i-1));

            QLogUtil::writeChannelDataLogByDate(date, chFilename, channelDataStr);

            QJsonObject jsonObj = counterData->toJSON(i - 1);
            jsonObj.insert("clientId", SettingConfig::getInstance().CLIENT_ID);
            jsonObj.insert("master", SettingConfig::getInstance().MASTER);
            jsonObj.insert("deviceId", deviceId);
            messageArray.append(jsonObj);
        }
    }

    // 3. 输出到中间件，执行后续处理过程
    QJsonObject statusObj = counterData->toStatusJSON();
    statusObj.insert("clientId", SettingConfig::getInstance().CLIENT_ID);
    statusObj.insert("master", SettingConfig::getInstance().MASTER);
    statusObj.insert("deviceId", deviceId);

    if (SettingConfig::getInstance().NEED_KAFKA == 1)
    {
        kafkaUtil.produceMessage(QString(QJsonDocument(messageArray).toJson(QJsonDocument::Compact)));
        kafkaUtil.produceMessage(SettingConfig::getInstance().KAFKA_STATUS_TOPIC, QString(QJsonDocument(statusObj).toJson(QJsonDocument::Compact)));
    }

    QLogUtil::writeChannelDataLogByDate(date, msgLogFilename, QString(QJsonDocument(messageArray).toJson(QJsonDocument::Compact)));

    // 4. 在界面上简单显示相差数据结果
    emit this->sendDataToDraw(counterData);
}
