#include "CounterProtocolXH.h"
#include <iostream>

CounterProtocolXH::CounterProtocolXH(QObject *parent) : QObject(parent)
{

}

bool CounterProtocolXH::parseMessureData(QByteArray rawData, CounterDataDto * counterData)
{
    int start = rawData.indexOf(COUNTER_FRAME_CONTENT_SEP);
    int dataLen = rawData.mid(COUNTER_FRAME_HEAD.size() + COUNTER_FRAME_DEVCODE_LENGTH + COUNTER_FRAME_TIME_LENGTH, 3).toInt();

    QString dataTime = rawData.mid(COUNTER_FRAME_HEAD.size() + COUNTER_FRAME_DEVCODE_LENGTH, COUNTER_FRAME_TIME_LENGTH);
    QString frameId = dataTime.mid(6, 6);
    counterData->frameId = frameId;

    QByteArray content = rawData.mid(start + 1, dataLen - 1);
    QString contentStr = QString(content);
    QStringList subList = contentStr.split(COUNTER_FRAME_CONTENT_SEP);

    QString statusStr = subList.at(0);
    QString refType = statusStr.mid(0, 1);
    counterData->refType = refType;

    QString channelStatus = statusStr.mid(1, COUNTER_MESSURE_CHANNEL);
    qint8 channelRefNo = statusStr.mid(17, 2).toInt();
    counterData->channelRefId = channelRefNo;

    for (int i = 0; i < COUNTER_MESSURE_CHANNEL; i++)
    {
        // 通道1的有效性在最后
        counterData->channelActiveArray.append(channelStatus.mid(COUNTER_MESSURE_CHANNEL - i - 1, 1));
        if (channelStatus.mid(COUNTER_MESSURE_CHANNEL - i - 1, 1) == "0")
        {
            counterData->channelDataArray.append("0.00");
        } else
        {
            counterData->channelDataArray.append(subList.at(i + 1));
        }
    }

    return true;
}

QList<QByteArray> CounterProtocolXH::extractFrameList(QByteArray rawData)
{
    QList<QByteArray> resultList;
    int head = rawData.indexOf(COUNTER_FRAME_HEAD);
    if (head < 0)
    {
        return resultList;
    }

    rawData = rawData.mid(head, rawData.size() - head + 2);

    if (rawData.startsWith("$XHTS") == true)
    {
        QByteArray ba;
        for (int i = 0; i < rawData.size() - 1; i++)
        {
            if (rawData.at(i) != '\r')
            {
                ba.append(rawData.at(i));
            } else
            {
                if (rawData.at(i + 1) == '\n')
                {
                    resultList.append(ba);
                    ba.clear();
                    i++;
                } else
                {
                    ba.append(rawData.at(i));
                }
            }
        }
    }

    return resultList;
}


bool CounterProtocolXH::checkFrame(QByteArray rawData)
{
    // 帧长度小于最小的长度
    if (rawData.size() < COUNTER_FRAME_MIN_LENGTH)
    {
        return false;
    }

    // 帧头不是$XHTS
    if (COUNTER_FRAME_HEAD.toLocal8Bit() != rawData.mid(0, COUNTER_FRAME_HEAD.size()))
    {
        return false;
    }

    return true;
}
