#include "commandwidget.h"

#include "ui_commandwidget.h"

CommandWidget::CommandWidget(QWidget *parent)
    : QWidget(parent), ui(new Ui::CommandWidget) {
    ui->setupUi(this);
    ui->stopConnectionToolBtn->setDisabled(true);
    ui->settingToolBtn->setIcon(QIcon(":/images/settings.png"));
    ui->settingToolBtn->setText("通信设置");
    ui->settingToolBtn->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);

    udpSocket = new QUdpSocket(this);
    connect(&settingDlg, &CommunicationSettingDlg::sendErrorMessage, this,
            &CommandWidget::receiveMessageSlots);
}

CommandWidget::~CommandWidget() {
    delete ui;
    if (udpSocket) udpSocket->deleteLater();
}

void CommandWidget::on_settingToolBtn_clicked() {
    settingDlg.exec();
}

// 连接
void CommandWidget::on_startConnectionToolBtn_clicked() {
    ui->startConnectionToolBtn->setDisabled(true);

    if (!g_networkSettingInfo) {
        qWarning() << "Network settings are not initialized!";
        return;
    }

    int dataSourceType = g_networkSettingInfo->value("DataSource").toInt();
    QString groupName = "";

    switch (dataSourceType) {
    case 0:
        groupName = "LLink";
        break;
    case 1:
        groupName = "SATCOM1";
        break;
    case 2:
        groupName = "SATCOM2";
        break;
    default:
        qWarning() << "Unknown data source type:" << dataSourceType;
        return;
    }

    m_remoteIP = g_networkSettingInfo->value(groupName + "/remoteIP").toString();
    m_remotePort = g_networkSettingInfo->value(groupName + "/remotePort").toInt();
    int localPort = g_networkSettingInfo->value(groupName + "/localPort").toInt();
    QString localIP = g_networkSettingInfo->value(groupName + "/localIP").toString();

    // 校验 IP 和端口
    if (m_remoteIP.isEmpty() || m_remotePort <= 0 || localIP.isEmpty() || localPort <= 0) {
        qWarning() << "Invalid IP or port configuration!";
        return;
    }

    if (dataSourceType == 0) {  // 组播
        qDebug() << "Starting multicast connection to" << m_remoteIP << ":" << m_remotePort;
        emit startConnectionSignal(m_remoteIP, m_remotePort);
    } else {  // 单播
        qDebug() << "Starting unicast connection on" << localIP << ":" << localPort;
        emit startConnectionSignal(localIP, localPort);
    }

    ui->stopConnectionToolBtn->setDisabled(false);
}
// 断开
void CommandWidget::on_stopConnectionToolBtn_clicked() {
    ui->stopConnectionToolBtn->setDisabled(true);

    emit stopConnectionSignal();

    // ui->stopConnectionToolBtn->setDisabled(false);
    ui->startConnectionToolBtn->setDisabled(false);
}

void CommandWidget::receiveMessageSlots(QString message, int type) {
    emit sendErrorMessage(message, type);
}



unsigned char CommandWidget::getCrc(quint8* data, quint8 length)
{
    quint16 crc = 0;
    int i=0;
    while (length-- > 0)
    {
        crc = CRC8TAB[crc ^ (data[i]&0x00FF)];

        i++;
    }

    return crc&0x00ff;

}

ProtocalKB CommandWidget::EncodeCommandCmd(quint8 cmd)
{
    std::unique_ptr<ProtocalKB> pBuff = std::make_unique<ProtocalKB>();
    pBuff->head[0]   = PROTOCOL_HEAD_0;
    pBuff->head[1]   = PROTOCOL_HEAD_1;
    pBuff->reserved  = PROTOCOL_RESERVED;
    pBuff->data[0] = cmd;
    pBuff->data[1] = cmd;
    pBuff->data[2] = cmd;
    pBuff->curPage  = PROTOCOL_CUR_PAGE;
    quint8 *ptr = reinterpret_cast<quint8*>(&pBuff);
    pBuff->CHKSUM = getCrc(ptr, sizeof(pBuff) - sizeof(pBuff->CHKSUM));

    return *pBuff;
}





bool CommandWidget::writeBufferToClient(const QByteArray &data)
{
    // 目标地址和端口
    QHostAddress destination("172.10.1.216"); // 目标 IP 地址
    quint16 port = 9003;                       // 目标端口

    // 发送数据
    qint64 bytesSent = g_CommandudpSocket->writeDatagram(data, destination, port);
    if (bytesSent == -1) {
        qDebug() << "发送失败:" << g_CommandudpSocket->errorString();
        return false;
    } else {
        qDebug() << "发送成功,字节数:" << bytesSent;
        return true;
    }


}

void CommandWidget::buttonResponse(quint8 cmd)
{

    ProtocalKB packet = EncodeCommandCmd(cmd);
    // 将 ProtocalKB 结构体转换为 QByteArray
    QByteArray data;
    data.append(reinterpret_cast<const char*>(&packet), sizeof(ProtocalKB));
    for(int i=0;i<3;i++)
    {
        writeBufferToClient(data);
    }

}

void CommandWidget::on_pushButton_clicked()
{
    buttonResponse(0x75);

}


void CommandWidget::on_pushButton_2_clicked()
{
    buttonResponse(0x76);
}


void CommandWidget::on_pushButton_5_clicked()
{
   buttonResponse(0x7D);
}


void CommandWidget::on_pushButton_6_clicked()
{
   buttonResponse(0x7C);
}


void CommandWidget::on_pushButton_10_clicked()
{
   buttonResponse(0x69);
}


void CommandWidget::on_pushButton_9_clicked()
{
    buttonResponse(0x6A);
}


void CommandWidget::on_pushButton_4_clicked()
{
    buttonResponse(0x77);
}


void CommandWidget::on_pushButton_3_clicked()
{
     buttonResponse(0x78);
}


void CommandWidget::on_pushButton_14_clicked()
{
    buttonResponse(0x79);
}


void CommandWidget::on_pushButton_13_clicked()
{
    buttonResponse(0xC6);
}


void CommandWidget::on_pushButton_17_clicked()
{
    buttonResponse(0x66);
}


void CommandWidget::on_pushButton_8_clicked()
{
    buttonResponse(0x67);
}


void CommandWidget::on_pushButton_7_clicked()
{
    buttonResponse(0x68);
}


void CommandWidget::on_pushButton_12_clicked()
{
    buttonResponse(0x7B);
}


void CommandWidget::on_pushButton_11_clicked()
{
    buttonResponse(0x7A);
}


void CommandWidget::on_pushButton_16_clicked()
{
    buttonResponse(0xC8);
}


void CommandWidget::on_pushButton_15_clicked()
{
    buttonResponse(0xC9);
}