#include "controltestwidget.h"
#include "ui_controltestwidget.h"
#include "base/x_uimsgboxok.h"
#include "QFileDialog"
#include "QDir"
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>
#include <globaldefine.h>
#include <QTcpSocket>
#include <QHostAddress>
#include "tools.h"
ControlTestWidget::ControlTestWidget(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlTestWidget)
{
    m_pLedlist=list;
    ui->setupUi(this);
    refreshLable();
setStyleSheet(css);
    ui->pushButtonStartLine->setProperty("ssType", "progManageTool");
    ui->pushButtonStartGray->setProperty("ssType", "progManageTool");
    ui->pushButtonStartColor->setProperty("ssType", "progManageTool");
    ui->pushButtonStopTest->setProperty("ssType", "progManageTool");
    ui->pushButton->setProperty("ssType", "progManageTool");
    ui->pushButton_2->setProperty("ssType", "progManageTool");
    ui->pushButton_3->setProperty("ssType", "progManageTool");
    ui->pushButton_4->setProperty("ssType", "progManageTool");
    ui->pushButton_5->setProperty("ssType", "progManageTool");
    ui->pushButton_6->setProperty("ssType", "progManageTool");
    ui->pushButton_7->setProperty("ssType", "progManageTool");
    ui->pushButton_8->setProperty("ssType", "progManageTool");
    ui->pushButton_9->setProperty("ssType", "progManageTool");
    ui->pushButton_10->setProperty("ssType", "progManageTool");
    ui->pushButton_11->setProperty("ssType", "progManageTool");
    ui->pushButton_12->setProperty("ssType", "progManageTool");
    ui->pushButton_13->setProperty("ssType", "progManageTool");

    ui->spinBoxLineSpeed->setValue(10);
    ui->spinBoxLineDistance->setValue(15);
    ui->spinBoxGraySpeed->setValue(10);
    ui->spinBoxGrayValue->setValue(0);
    ui->radioButtonWhite->setChecked(true);
    ui->radioButton_White->setChecked(true);
    ui->checkBoxHorizontal->setChecked(true);
    ui->checkBoxVertical->setChecked(true);
    ui->checkBoxSlash->setChecked(true);
    ui->checkBox_red->setChecked(true);
    ui->checkBox_green->setChecked(true);
    ui->checkBox_blue->setChecked(true);
    ui->checkBox_white->setChecked(true);


    connect(ui->pushButtonStartLine,SIGNAL(clicked()),this,SLOT(OnStartTestLine()));
    connect(ui->pushButtonStartGray,SIGNAL(clicked()),this,SLOT(OnStartTestGray()));
    connect(ui->pushButtonStartColor,SIGNAL(clicked()),this,SLOT(OnStartTestColor()));
    connect(ui->pushButtonStopTest,SIGNAL(clicked()),this,SLOT(OnStopTest()));

    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(OnpushButton1()));
    connect(ui->pushButton_2,SIGNAL(clicked()),this,SLOT(OnpushButton2()));
    connect(ui->pushButton_3,SIGNAL(clicked()),this,SLOT(OnpushButton3()));
    connect(ui->pushButton_4,SIGNAL(clicked()),this,SLOT(OnpushButton4()));
    connect(ui->pushButton_5,SIGNAL(clicked()),this,SLOT(OnpushButton5()));
    connect(ui->pushButton_6,SIGNAL(clicked()),this,SLOT(OnpushButton6()));
    connect(ui->pushButton_7,SIGNAL(clicked()),this,SLOT(OnpushButton7()));
    connect(ui->pushButton_8,SIGNAL(clicked()),this,SLOT(OnpushButton8()));
    connect(ui->pushButton_9,SIGNAL(clicked()),this,SLOT(OnpushButton9()));
    connect(ui->pushButton_10,SIGNAL(clicked()),this,SLOT(OnpushButton0()));
    connect(ui->pushButton_11,SIGNAL(clicked()),this,SLOT(OnpushButtonClear()));
    connect(ui->pushButton_12,SIGNAL(clicked()),this,SLOT(OnpushButtonReset()));
    connect(ui->pushButton_13,SIGNAL(clicked()),this,SLOT(OnpushButtonAnycast()));

    ui->pushButton_13->setEnabled(false);

    MARCO_DEFINE_CONTROL_FUNC2(parent->parent(),parent)

            connect(this,SIGNAL(sigTcpSend(int)),parent->parent(),SLOT(OnControlTcpSend(int)));
    ui->lineEdit->setValidator(new QIntValidator(0, 100, this));


}

ControlTestWidget::~ControlTestWidget()
{
    delete ui;
    if(pHpptClient != nullptr)
    {
        qDebug() <<"delete pHpptClient in ~NetComm";
        delete pHpptClient;
        pHpptClient=nullptr;
    }
    if(pHpptClientAll != nullptr)
    {
        qDebug() <<"delete pHpptClientAll in ~NetComm";
        delete pHpptClientAll;
        pHpptClientAll=nullptr;
    }
}
void ControlTestWidget::refreshLable()
{
    ui->labelTestScreen->setText(tr("Test Screen"));
    ui->groupBox->setTitle(tr("Line test"));
    ui->radioButtonRed->setText(tr("Red"));
    ui->radioButtonGreen->setText(tr("Green"));
    ui->radioButtonBlue->setText(tr("Blue"));
    ui->radioButtonWhite->setText(tr("White"));
    ui->radioButton_red->setText(tr("Red"));
    ui->radioButton_Green->setText(tr("Green"));
    ui->radioButton_Blue->setText(tr("Blue"));
    ui->radioButton_White->setText(tr("White"));
    ui->checkBoxVertical->setText(tr("Vertical"));
    ui->checkBoxHorizontal->setText(tr("Horizontal"));
    ui->checkBoxSlash->setText(tr("Slash"));
    ui->label->setText(tr("Speed"));
    ui->label_5->setText(tr("ms(>10)"));
    ui->checkBoxHorizontal->setText(tr("Horizontal"));
    ui->label_2->setText(tr("Line Distance"));
    ui->pushButtonStartLine->setText(tr("Test"));
    ui->groupBox_2->setTitle(tr("Gradation test"));
    ui->checkBoxShowInfo->setText(tr("Only the gray value is displayed"));
    ui->checkBox_red->setText(tr("Red"));
    ui->checkBox_green->setText(tr("Green"));
    ui->checkBox_blue->setText(tr("Blue"));
    ui->checkBox_white->setText(tr("White"));
    ui->label_3->setText(tr("Speed"));
    ui->label_4->setText(tr("GrayValue"));
    ui->pushButtonStartGray->setText(tr("Test"));
    ui->groupBox_3->setTitle(tr("Color test"));
    ui->checkBoxGradient->setText(tr("Gradient"));
    ui->radioButton_red->setText(tr("Red"));
    ui->radioButton_Green->setText(tr("Green"));
    ui->radioButton_Blue->setText(tr("Blue"));
    ui->radioButton_White->setText(tr("White"));
    ui->pushButtonStopTest->setText(tr("Stop"));
    ui->pushButton_11->setText(tr("Clear"));
    ui->pushButton_12->setText(tr("Reset"));
    ui->pushButton_13->setText(tr("Anycast"));

}
void ControlTestWidget::OnStartTestLine()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()<=1)
    {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0)
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
            pDlg->exec();
            return;
        }
    }

    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "TestScreen");
    json.insert("mode", 1);// 0：停止； 1：斜线； 2：灰度; 3:颜色；4：渐变
    json.insert("speed", ui->spinBoxLineSpeed->value());
    if(ui->radioButtonRed->isChecked())
        json.insert("color", "#FFFF0000");
    else if(ui->radioButtonGreen->isChecked())
        json.insert("color", "#FF00FF00");
    else if(ui->radioButtonBlue->isChecked())
        json.insert("color", "#FF0000FF");
     else
        json.insert("color", "#FFFFFFFF");

    json.insert("interval", ui->spinBoxLineDistance->value());
    json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked());
    json.insert("verticalLine", ui->checkBoxVertical->isChecked());
    json.insert("slantLine", ui->checkBoxSlash->isChecked());
    json.insert("runLimit", ui->spinBoxGrayValue->value());
    json.insert("showInfo", !ui->checkBoxShowInfo->isChecked());
    json.insert("red", ui->checkBox_red->isChecked());
    json.insert("green", ui->checkBox_green->isChecked());
    json.insert("blue", ui->checkBox_blue->isChecked());
    json.insert("white", ui->checkBox_white->isChecked());

    MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed"))

}
void ControlTestWidget::OnStartTestGray()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()<=1)
    {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0)
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
            pDlg->exec();
            return;
        }
    }

    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "TestScreen");
    json.insert("mode", 2);// 0：停止； 1：斜线； 2：灰度; 3:颜色；4：渐变
    json.insert("speed", ui->spinBoxGraySpeed->value());
 //   qDebug()<<"speed="<<ui->spinBoxGraySpeed->value();
    if(ui->radioButtonRed->isChecked())
        json.insert("color", "#FFFF0000");
    else if(ui->radioButtonGreen->isChecked())
        json.insert("color", "#FF00FF00");
    else if(ui->radioButtonBlue->isChecked())
        json.insert("color", "#FF0000FF");
     else
        json.insert("color", "#FFFFFFFF");
    json.insert("interval", ui->spinBoxLineDistance->value());
    json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked());
    json.insert("verticalLine", ui->checkBoxVertical->isChecked());
    json.insert("slantLine", ui->checkBoxSlash->isChecked());
    json.insert("runLimit", ui->spinBoxGrayValue->value());
    json.insert("showInfo", !ui->checkBoxShowInfo->isChecked());
    json.insert("red", ui->checkBox_red->isChecked());
    json.insert("green", ui->checkBox_green->isChecked());
    json.insert("blue", ui->checkBox_blue->isChecked());
    json.insert("white", ui->checkBox_white->isChecked());

    MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed"))

}
void ControlTestWidget::OnStartTestColor()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()<=1)
    {
        if(m_pLedCard==nullptr||m_pLedlist->count()==0)
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
            pDlg->exec();
            return;
        }
    }

    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "TestScreen");
    if(ui->checkBoxGradient->isChecked())
        json.insert("mode", 4);// 0：停止； 1：斜线； 2：灰度; 3:颜色；4：渐变
    else
        json.insert("mode", 3);// 0：停止； 1：斜线； 2：灰度; 3:颜色；4：渐变
    json.insert("speed", ui->spinBoxLineSpeed->value());
    if(ui->radioButton_red->isChecked())
        json.insert("color", "#FFFF0000");
    else if(ui->radioButton_Green->isChecked())
        json.insert("color", "#FF00FF00");
    else if(ui->radioButton_Blue->isChecked())
        json.insert("color", "#FF0000FF");
     else
        json.insert("color", "#FFFFFFFF");

    json.insert("interval", ui->spinBoxLineDistance->value());
    json.insert("horizonalLine", ui->checkBoxHorizontal->isChecked());
    json.insert("verticalLine", ui->checkBoxVertical->isChecked());
    json.insert("slantLine", ui->checkBoxSlash->isChecked());
    json.insert("runLimit", ui->spinBoxGrayValue->value());
    json.insert("showInfo", !ui->checkBoxShowInfo->isChecked());
    json.insert("red", ui->checkBox_red->isChecked());
    json.insert("green", ui->checkBox_green->isChecked());
    json.insert("blue", ui->checkBox_blue->isChecked());
    json.insert("white", ui->checkBox_white->isChecked());

    MACRO_DEFINE_TIPDLG_FUCN(tr("StartTest"),tr("Success"),tr("failed"))

}
void ControlTestWidget::OnStopTest()
{

    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "TestScreen");
    json.insert("mode", 0);
    MACRO_DEFINE_TIPDLG_FUCN(tr("StopTest"),tr("Success"),tr("failed"))
}

void ControlTestWidget::OnpushButton1()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"1");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton2()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"2");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton3()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"3");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton4()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"4");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton5()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"5");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton6()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"6");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton7()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"7");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton8()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"8");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton9()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"9");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButton0()
{
    if(ui->lineEdit->text().contains("-"))
        ui->lineEdit->clear();
    ui->lineEdit->setText(ui->lineEdit->text()+"0");
    ui->pushButton_13->setEnabled(true);
}
void ControlTestWidget::OnpushButtonClear()
{
    ui->lineEdit->clear();
    ui->pushButton_13->setEnabled(false);
}

void ControlTestWidget::OnpushButtonReset()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedCard==nullptr||m_pLedlist->count()==0)
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
        pDlg->exec();
        return;
    }
    int iIndex= ui->lineEdit->text().toInt();
    if(m_pLedlist->count()==1)
   {

       SendAnycastCmd(m_pLedCard->m_strCardIp,0);
   }
   else {
        emit sigTcpSend(iIndex);

   }
    ui->lineEdit->setText("-"+tr("loopback mode")+"-");
    ui->pushButton_13->setEnabled(false);
}
void ControlTestWidget::OnpushButtonAnycast()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedCard==nullptr||m_pLedlist->count()==0)
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NoSelectedController"),this,1);
        pDlg->exec();
        return;
    }
    int iIndex= ui->lineEdit->text().toInt();
    if(m_pLedlist->count()==1)
   {

       SendAnycastCmd(m_pLedCard->m_strCardIp,iIndex);
   }
   else {
        emit sigTcpSend(iIndex);

   }





    ui->lineEdit->setText(tr("Anycast")+" - "+ui->lineEdit->text());
    ui->pushButton_13->setEnabled(false);
}
void ControlTestWidget::SendAnycastCmd(QString strIp,int iProgramIndex)
{

    QTcpSocket *send = new QTcpSocket();
    connect(send, SIGNAL(connected()), this, SLOT(connect_sucessful()));
    connect(send, SIGNAL(error(QAbstractSocket::SocketError)),this, SLOT(show_error(QAbstractSocket::SocketError)));
    send->connectToHost(QHostAddress(strIp),31299);

    ST_ANSY_PROGRAM_PACKET tempStreadPakcet;
    tempStreadPakcet.SyncHead[0]=0x7e;
    tempStreadPakcet.SyncHead[1]=0x7e;
    tempStreadPakcet.SyncHead[2]=0x55;
    tempStreadPakcet.ucCommType=0x97;
    tempStreadPakcet.iBaoLiu=0;
    tempStreadPakcet.iLength=4;
    unsigned char uctemp[4]={0};
    uctemp[0]=iProgramIndex;

    memcpy(tempStreadPakcet.pDataBuffer,uctemp,4);
    tempStreadPakcet.pDataBuffer[tempStreadPakcet.iLength]=GetCheckCodeIn8(&tempStreadPakcet.ucCommType,tempStreadPakcet.iLength+sizeof(tempStreadPakcet.iBaoLiu)+sizeof(tempStreadPakcet.ucCommType)+sizeof(tempStreadPakcet.iLength));
    int iLenPacket=3*sizeof(unsigned char)+sizeof(char)+sizeof(int)+sizeof(int)+tempStreadPakcet.iLength+sizeof(char);/////除正文外的协议结构大小；
    QByteArray databuf = QByteArray(reinterpret_cast<char*>(&tempStreadPakcet), iLenPacket);
    if(!send->waitForConnected(10000))              //等待连接返回
    {
        qDebug()<<strIp<<"Connect timeout ";
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Connect timeout"),this,1);
        pDlg->exec();
        send->close();
        delete send;
        return ;
    }
    send->write(databuf);
    if(send->waitForBytesWritten(3000))
    {
        QByteArray readBuf=send->read(send->bytesAvailable());
        qDebug()<<"recv anycast success ack";
        if(iProgramIndex==0)
        {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Reset loop mode")+":"+tr("success"),this,1);
            pDlg->exec();

        }
        else {
            X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("Anycast")+":"+tr("success"),this,1);
            pDlg->exec();

        }
        //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("Anycast")+":"+tr("success"));
    }
    send->close();
    delete send;

}
void ControlTestWidget::onSelectedDeviceList(QList<LedCard*> *list)
{
    m_pLedlist=list;
    MACRO_DEFINE_CONTROL_FUNC3
}
void ControlTestWidget::OnControlTypeSwitchIndexChanged(int index)
{
    if(index==Setting_Encrypt)
    {
        m_bSelected=true;
        if(m_pLedCard!=nullptr)
            onReadbackAllThisPage();
    }
    else {
        m_bSelected=false;
    }
}
void  ControlTestWidget::onReadbackAllThisPage()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()!=1)
        return;
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlTestWidget::OnProHttpResponse(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK
        }
    }
}

//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlTestWidget::OnProHttpResponseAll(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
        QJsonParseError parseJsonErr;
        QJsonDocument document = QJsonDocument::fromJson(data,&parseJsonErr);
        if(!(parseJsonErr.error == QJsonParseError::NoError))
        {
            if(data.size()==0)
                qDebug()<<"json is empty";
            else
                qDebug()<<tr("DeviceItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            MACRO_ASKTIME_STOP
            MACRO_POSTING_DLG_UNLOCK
        }
    }
}
void ControlTestWidget::DeletePostingDlg()
{
    if(m_PostingDlg!=nullptr)
    {
        delete m_PostingDlg;
        m_PostingDlg=nullptr;
    }
}


