#include "controlbrightnessautowidget.h"
#include "ui_controlbrightnessautowidget.h"
#include "QIntValidator"
#include "LoUIClass/x_uimsgboxok.h"
#include "QFileDialog"
#include "QDir"
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>
#include <globaldefine.h>
//#include <LoQClass/qexcel.h>
#include <QThread>
#include <QtXlsx/QtXlsx>
ControlBrightnessAutoWidget::ControlBrightnessAutoWidget(QWidget *parent,QList<LedCard *> *list) :
    QWidget(parent),
    ui(new Ui::ControlBrightnessAutoWidget)
{
    ui->setupUi(this);
    refreshLable();
    ui->pushButtonSet1->setProperty("ssType", "progManageTool");
    ui->pushButtonSet1->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonSet->setProperty("ssType", "progManageTool");
    ui->pushButtonSet->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonReadback1->setProperty("ssType", "progManageTool");
    ui->pushButtonReadback1->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonUpload->setProperty("ssType", "progManageTool");
    ui->pushButtonUpload->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonReadback->setProperty("ssType", "progManageTool");
    ui->pushButtonReadback->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonReadbackTab->setProperty("ssType", "progManageTool");
    ui->pushButtonReadbackTab->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");
    ui->pushButtonCurSensorTypeAndValue->setProperty("ssType", "progManageTool");
    ui->pushButtonCurSensorTypeAndValue->setStyleSheet("QPushButton{background:rgba(28,154,210,1);}");

    ui->lineEditSensitivity->setStyleSheet("QLineEdit{background:rgba(255,255,255,1);}" "QLineEdit:disable{background:rgba(245,245,245,1);}");
    ui->lineEditMinBrightnessValue->setStyleSheet("QLineEdit{background:rgba(255,255,255,1);}" "QLineEdit:disable{background:rgba(245,245,245,1);}");
    ui->lineEditSensitivity->setValidator(new QIntValidator(1,100,this));//设置最大值和最小值
    ui->lineEditSensitivity->setMaxLength(3);//设置最大输入个数
    ui->lineEditMinBrightnessValue->setValidator(new QIntValidator(1,255,this));//设置最大值和最小值
    ui->lineEditMinBrightnessValue->setMaxLength(3);//设置最大输入个数
//按钮槽函数绑定
    connect(ui->pushButtonSet1,SIGNAL(clicked()),this,SLOT(OnClickSet()));
    connect(ui->pushButtonReadback,SIGNAL(clicked()),this,SLOT(OnAutoReadbackMin()));
    connect(ui->pushButtonReadback1,SIGNAL(clicked()),this,SLOT(OnAutoReadback()));
    connect(ui->pushButtonReadbackTab,SIGNAL(clicked()),this,SLOT(OnAutoReadbackTab()));
    connect(ui->pushButtonSet,SIGNAL(clicked()),this,SLOT(OnClickSetMin()));
    connect(ui->pushButtonUpload,SIGNAL(clicked()),this,SLOT(OnClickUpload()));
    connect(ui->pushButtonCurSensorTypeAndValue,SIGNAL(clicked()),this,SLOT(OnCurSensorTypeAndValue()));


    m_buttonGroup = new QButtonGroup;
    m_buttonGroup->addButton(ui->radioButton,0);
    m_buttonGroup->addButton(ui->radioButton_2,1);

    MARCO_DEFINE_CONTROL_FUNC2(parent->parent()->parent(),parent->parent())
}

ControlBrightnessAutoWidget::~ControlBrightnessAutoWidget()
{
    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 ControlBrightnessAutoWidget::refreshLable()
{
    ui->label_tip1->setText(tr("BrightnessTip1"));
    ui->label_tip2->setText(tr("BrightnessTip2"));
    ui->label_sensitivity->setText(tr("Sensitivity"));
    ui->label_minbrightness->setText(tr("Minbrightness"));
    ui->pushButtonSet->setText(tr("Set"));
    ui->pushButtonSet1->setText(tr("Set"));
    ui->pushButtonUpload->setText(tr("Upload"));
    ui->pushButtonReadback->setText(tr("Readback"));
    ui->pushButtonReadback1->setText(tr("Readback"));
    ui->pushButtonReadbackTab->setText(tr("ReadbackTable"));
    ui->pushButtonCurSensorTypeAndValue->setText(tr("Refresh"));
    ui->labelCurSensorValue->setText(tr("Cur brigntness:0"));
}
void ControlBrightnessAutoWidget::OnClickSetMin()
{
    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;
        }
    }
    if(ui->lineEditMinBrightnessValue->text().isEmpty()||ui->lineEditMinBrightnessValue->text().toInt()>255)
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("MinBrightnessInputTip"),this,1);
        pDlg->exec();
        ui->lineEditMinBrightnessValue->setFocus();
        return;
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetMinBrightness");
    json.insert("brightness", ui->lineEditMinBrightnessValue->text().toInt());
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetMinBrightness"),tr("Success"),tr("failed"))

}
void ControlBrightnessAutoWidget::OnClickSet()
{
    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    if(ui->lineEditSensitivity->text().isEmpty()||ui->lineEditSensitivity->text().toInt()>100)
    {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("SensitivityInputTip"),this,1);
        pDlg->exec();
        ui->lineEditSensitivity->setFocus();
        return;
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SetBrightnessSensitivity");
    json.insert("sensitivity", ui->lineEditSensitivity->text().toInt());
    MACRO_DEFINE_TIPDLG_FUCN(tr("SetBrightnessSensitivity"),tr("Success"),tr("failed"))



}
void ControlBrightnessAutoWidget::OnClickUpload()
{


    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    int idd=m_buttonGroup->checkedId();
    strSensorType="";
    if(idd==0)
        strSensorType=ui->radioButton->text();
    else if(idd==1)
        strSensorType=ui->radioButton_2->text();
    else {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NeedSelectSensorTypeTip"),this,1);
        pDlg->exec();
        return;
    }
    QString s = QFileDialog::getOpenFileName(this, "open file dialog",
                   "/",
                   "brightness files(*.xlsx)");
    if(s.isEmpty())
        return;
    if(isFileExist(s))
    {

        QXlsx::Document xlsx(s);

        xlsx.selectSheet(strSensorType);
        QStringList strList;
        for(int j=0;j<255;j++)
            strList.append(xlsx.read(3,j+3).toString());

        xlsx.save();
        QVariant variant;
        variant.setValue(strList);
        QJsonObject json;
        json.insert("_id", getRandomString(10));
        json.insert("_type", "SensorBrightnessTable");
        json.insert("values", variant.toJsonValue());
        MACRO_DEFINE_TIPDLG_FUCN(tr("SensorBrightnessTable"),tr("Success"),tr("failed"))

//        QExcel tempReadExcel(s);
//        if(tempReadExcel.m_bSupportExcel)
//        {
//            tempReadExcel.selectSheet(strSensorType);
//            QStringList strList;
//            for(int j=0;j<255;j++)
//                strList.append(tempReadExcel.getCellValue(3,j+3).toString());
//            tempReadExcel.close();
//            QVariant variant;
//            variant.setValue(strList);
//            QJsonObject json;
//            json.insert("_id", getRandomString(10));
//            json.insert("_type", "SensorBrightnessTable");
//            json.insert("values", variant.toJsonValue());
//            MACRO_DEFINE_TIPDLG_FUCN(tr("SensorBrightnessTable"),tr("Success"),tr("failed"))

//        }
    }
}
void ControlBrightnessAutoWidget::OnAutoReadbackMin()
{
    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetMinBrightness");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetMinBrightness"),tr("Success"),tr("failed"))
}
void ControlBrightnessAutoWidget::OnAutoReadback()
{
    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetBrightnessSensitivity");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetBrightnessSensitivity"),tr("Success"),tr("failed"))

}
void ControlBrightnessAutoWidget::OnAutoReadbackTab()
{
    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    int idd=m_buttonGroup->checkedId();
    strSensorType="";
    if(idd==0)
        strSensorType=ui->radioButton->text();
    else if(idd==1)
        strSensorType=ui->radioButton_2->text();
    else {
        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("NeedSelectSensorTypeTip"),this,1);
        pDlg->exec();

        return;
    }
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetSensorBrightnessTable");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetSensorBrightnessTable"),tr("Success"),tr("failed"))
}
//获取到httpPost的应答，如果参数变化需要出发修改控件item的内容
void ControlBrightnessAutoWidget::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("wDevicesItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "SetBrightnessSensitivity")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "SetMinBrightness")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "SetMaxBrightness")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }

            else if(strType == "GetBrightnessSensitivity")
            {
                int iTemp=jsonObject["sensitivity"].toInt();
                QString strSensitivity=QString::number(iTemp);
                ui->lineEditSensitivity->setText(strSensitivity);
                MACRO_ASKTIME_STOP
                 MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetCurrentSensorBrightness")
            {
                bool b485=jsonObject["is485"].toBool();
                ui->radioButton->setChecked(!b485);
                ui->radioButton_2->setChecked(b485);
                int iTempValue=jsonObject["value"].toInt();
                QString strSensorValue=QString::number(iTempValue);
                ui->labelCurSensorValue->setText(tr("Cur brightness")+":"+strSensorValue);
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetMinBrightness")
            {
                int iTemp=jsonObject["brightness"].toInt();
                QString strMinBrightness=QString::number(iTemp);
                ui->lineEditMinBrightnessValue->setText(strMinBrightness);
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
            }
            else if(strType == "GetSensorBrightnessTable")
            {
                QVariant iTemp=jsonObject["values"].toVariant();
                QStringList data=iTemp.value<QStringList>();
                if(data.count()>0)
                {
                    QString strBrightnessTab="[";
                    for(int i=0;i<data.count();i++)
                        strBrightnessTab+=data.at(i)+" ";
                    strBrightnessTab+="]";
                    if(m_pGetAskTimer->isActive())
                        m_pGetAskTimer->stop();
                    MACRO_POSTING_DLG_UNLOCK

                    QFileDialog m_QFileDialog;
                    QString FilePathName=QCoreApplication::applicationDirPath()+"/"+"BrightnessTable.xlsx";
                    //!-- 得到原文件的后缀名
                    QString suffix_save = QFileInfo(FilePathName).suffix();
                    //!--- 设置过滤匹配文件格式
                    QString setFilter = "brightness(*.xlsx );";
                    //!--- selectFilter为弹出对话框中的文件格式，dirString为文件路径，这里显示文件名
                    QString selectFilter,dirString;
                    if( FilePathName.isEmpty() ) return;
                    else dirString = m_pLedCard->m_strCardId+QFileInfo(FilePathName).fileName();
                    //!--- 判断文件后缀名以及文件格式，看是否匹配，没有做出相应操作
                    if( !suffix_save.isEmpty() && setFilter.contains( selectFilter ) ) selectFilter = suffix_save.insert(0,"*.");
                    if( !suffix_save.isEmpty() && !setFilter.contains( selectFilter ) ) selectFilter = "*.*";

                    QString strBtbModle=QCoreApplication::applicationDirPath()+"/"+"Btb";
                    QFile file(strBtbModle);
                    //if( selectFilter.compare("*.*") ) saveFileName = saveFileName+selectFilter.remove(0,1);
                    if(file.exists())
                    {
                        //!--- 复制文件
                        //!
                        QString saveFileName = m_QFileDialog.getSaveFileName(this,tr("Save file"),dirString,setFilter,&selectFilter,
                                                                             QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
                        if( saveFileName.isEmpty() )
                            return;
                        bool copy_error =  file.copy(saveFileName );
                        int isectemp=0;
                        while(!isFileExist(saveFileName))
                        {
                            QThread::sleep(1);
                            isectemp++;
                            if(isectemp>5)
                                break;
                        }
                        if(isectemp<=5)
                        {
                               // QString sss=QString::number(data.count());


                                QXlsx::Document xlsx(saveFileName);

                                xlsx.selectSheet(strSensorType);
                                for(int m=0;m<data.count();m++)
                                {
                                    xlsx.write(3,m+3,data.at(m).toInt());
                                }
                                xlsx.save();

                        }

                    }
                    else {

                        X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),strBtbModle+" is not exist",this,1);
                        pDlg->exec();
                    }
                }
                else
                {
                    X_UIMsgBoxOk *pDlg=new X_UIMsgBoxOk(tr("Tip"),tr("no sensorBrightnessTable"),this,1);
                    pDlg->exec();

                }

                 //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("GetMinBrightness")+tr("success")+","+tr("Tab")+"="+strBrightnessTab);

            }
            else if(strType == "SensorBrightnessTable")
            {
                MACRO_ASKTIME_STOP
                MACRO_POSTING_DLG_UNLOCK
                //emit sigOutputInfo(m_pLedCard->m_strCardId+":"+tr("receive")+"<-"+tr("SetSensorBrightnessTable")+":"+tr("success"));
            }

        }
    }
}
void  ControlBrightnessAutoWidget::onReadbackAllThisPage()
{
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()!=1)
        return;
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetBrightnessSensitivity");
    ui->lineEditSensitivity->clear();
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json);
    QJsonObject json1;
    json1.insert("_id", getRandomString(10));
    json1.insert("_type", "GetMinBrightness");
    ui->lineEditMinBrightnessValue->clear();
    HttpPostByTypeJsonObject(pHpptClientAll,m_strUrl,json1);
    MACRO_DEFINE_TIPDLG_ALL_FUCN(tr("Readback"),tr("Success"),tr("failed"))
}
void ControlBrightnessAutoWidget::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("wDevicesItem OnProHttpResponse 解析json文件错误！");
            return;
        }
        QJsonObject jsonObject = document.object();
        QString strType=jsonObject["_type"].toString();
        if(jsonObject["success"].toBool()==true)
        {
            qDebug()<<m_pLedCard->m_strCardId +"---------"+ strType;
            if(strType == "GetBrightnessSensitivity")
            {
                int iTemp=jsonObject["sensitivity"].toInt();
                if(iTemp==0)
                {
                    emit sigAuto(false);
                }
                else {
                     emit sigAuto(true);
                }
                QString strSensitivity=QString::number(iTemp);
                ui->lineEditSensitivity->setText(strSensitivity);
                if(m_pGetAskTimer->isActive())
                    m_pGetAskTimer->stop();
                MACRO_POSTING_DLG_UNLOCK
             }
            else if(strType == "GetMinBrightness")
            {
                int iTemp=jsonObject["brightness"].toInt();
                QString strMinBrightness=QString::number(iTemp);
                ui->lineEditMinBrightnessValue->setText(strMinBrightness);
            }
        }
    }
}

void ControlBrightnessAutoWidget::onSelectedDeviceList(QList<LedCard*> *list)
{
    m_pLedlist=list;
    if(m_pLedlist==nullptr)
        return;
    if(m_pLedlist->count()==1)
    {
        ui->pushButtonReadbackTab->setEnabled(true);
    }
    else {
        ui->pushButtonReadbackTab->setEnabled(false);
    }
    MACRO_DEFINE_CONTROL_FUNC3
}
void ControlBrightnessAutoWidget::OnControlTypeSwitchIndexChanged(int index)
{
    if(index==ENUM_CONTRL_WIDGET_BRIGHTNESS)
    {
        m_bSelected=true;
        if(m_pLedCard!=nullptr)
            onReadbackAllThisPage();
    }
    else {
        m_bSelected=false;
    }
}
void ControlBrightnessAutoWidget::OnCurSensorTypeAndValue()
{
    MACRO_DEFINE_NO_SELECTED_CARD_TIP
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "GetCurrentSensorBrightness");
    MACRO_DEFINE_TIPDLG_FUCN(tr("GetCurrentSensorBrightness"),tr("Success"),tr("failed"))

}
void ControlBrightnessAutoWidget::DeletePostingDlg()
{
    if(m_PostingDlg!=nullptr)
    {
        delete m_PostingDlg;
        m_PostingDlg=nullptr;
    }
}
