#include "wupgradeapkitem.h"
#include "loapptools.h"
#include "LoUIClass/x_uimsgboxok.h"
//#include "LoUIClass/louimsgboxokcancel.h"
#include <QMessageBox>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
#include <QProgressBar>
#include <wDevicesManager/inputpassworddialog.h>
#include <globaldefine.h>
#include <QSizePolicy>
#include <QUuid>
#include <QMap>
#include <QMessageBox>
#include <QHostAddress>
#include "QTextCodec"

wUpgradeApkItem::wUpgradeApkItem(LedCard *pLedCard, LoQTreeWidget *parent,QWidget *pWnd,QString strProgramName,QString strProgramPath) :
    QObject(parent),
    QTreeWidgetItem(UserType),
    m_parent(parent)
{
    m_strProgramName=strProgramName;
    m_strProgramPath=strProgramPath;
    m_pWnd=pWnd;
    m_pLedCard=pLedCard;
    pHpptClient = new HpptClient(this);
    connect(pHpptClient,SIGNAL(httpPostRspReady(QString , QString , QByteArray )),this,SLOT(OnProHttpResponse(QString , QString , QByteArray)));
    init();

}
wUpgradeApkItem::~wUpgradeApkItem()
{
    if(pHpptClient!=nullptr)
    {
        qDebug() <<"delete pHpptClient in ~wUpgradeApkItem";
        delete pHpptClient;
        pHpptClient=nullptr;
    }
}

void wUpgradeApkItem::init()
{
    setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
    setCheckState(0, Qt::Unchecked);
    m_parent->addTopLevelItem(this);
    m_ImageOnline = new QLabel();
    m_ImageOnline->setStyleSheet("margin-top:12px; margin-bottom:12px");
    m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ONLINE, m_ImageOnline);
    m_ImageOnline->setAlignment(Qt::AlignCenter);
    for(int i=1; i<ENUM_DEVICE_PUBLISH_HEADE_END; i++) {
        setTextAlignment(i, Qt::AlignCenter);

    }

    //setTextAlignment(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, Qt::AlignCenter);
    SetItemParam(m_pLedCard);
    m_pProgress = new QProgressBar();
    // progress->setMaximumHeight(16);
    m_pProgress->setStyleSheet("margin-top:12px; margin-bottom:12px");
    //setData(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS,)
    m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_PROGRESS, m_pProgress);
    m_pProgress->setAlignment(Qt::AlignCenter);
    QSizePolicy policy = m_pProgress->sizePolicy();
    policy.setHorizontalStretch(1);
    policy.setVerticalStretch(1);
    policy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_pProgress->setSizePolicy(policy);
    m_pProgress->setValue(0);
    m_pProgress->setFixedWidth(100);
    //启动心跳，监测设备在线和下线，3次超时表示下线
    OnCheckSoftVersions();
    OnCheckFpgaVersions();

}
void wUpgradeApkItem::SetLockFlagFalse()
{
    m_lockFlag=false;

}

void wUpgradeApkItem::refreshLable()
{

}
void wUpgradeApkItem::OnCheckFpgaVersions()
{
    m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";
   QJsonObject json1;
  json1.insert("_id", getRandomString(10));
  json1.insert("_type", "CheckHardwareVersions");
  HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json1);
}
void wUpgradeApkItem::OnCheckSoftVersions()
{
    m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";
    QJsonObject json;
   json.insert("_id", getRandomString(10));
   json.insert("_type", "CheckSoftVersions");
   HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);

}
void wUpgradeApkItem::onVerifyLockPassword()
{
    InputPasswordDialog *pDlg=new InputPasswordDialog(m_parent,1);
    connect(pDlg, SIGNAL(sigAcceptData(QString)), this, SLOT(onInputPasswordPro(QString)));
    pDlg->setWindowModality(Qt::WindowModal);
    pDlg->exec();
}
void wUpgradeApkItem::onInputPasswordPro(QString strPassword)
{
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "VerifyPassword");
    json.insert("pwd", strPassword);
    m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";
    HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
}
void wUpgradeApkItem::SetPasswordItem(LedCard *p)
{
    qDebug()<<"p->bPassword:"<<p->bPassword;
    qDebug()<<"p->m_bLockStatus:"<<p->m_bLockStatus;



    if(p->bPassword)//加过密
    {
        if(m_bnLock==nullptr)
        {
            m_bnLock = new QPushButton(m_pWnd);
            m_bnLock->setStyleSheet("background-color:transparent;");
            m_bnLock->setStyleSheet("margin-left:12px; margin-right:12px;margin-top:12px; margin-bottom:12px;");
            m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock);
            connect(m_bnLock, SIGNAL(clicked()), this, SLOT(onVerifyLockPassword()));

        }
        //如果已经验证通过密码显示绿色图标
        if(p->m_bLockStatus)
            m_bnLock->setIcon(QIcon(":/res/DeviceManager/Lock.png"));
        else//如果没有验证显示蓝色锁图标
            m_bnLock->setIcon(QIcon(":/res/DeviceManager/UnLock.png"));
        m_parent->setItemWidget(this, ENUM_DEVICE_PUBLISH_HEADE_ENCRYPT, m_bnLock);

    }
    else {
        //显示空白
       // m_bnLock->setIcon(QIcon(":/res/DeviceManager/Transparent.png"));
    }

}
void wUpgradeApkItem::onUninstallApk(QString strApkName)
{
             QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "UninstallSoftware");
            json.insert("packageName", strApkName);
            m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";
            HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
            if(strApkName=="com.xixun.xixunplayer")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION);
                if(strtemp.isEmpty())
                    return;
            }
            else if(strApkName=="com.xixun.joey.cardsystem")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION);
                if(strtemp.isEmpty())
                    return;

            }
            else if(strApkName=="net.sysolution.taxiapp")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION);
                if(strtemp.isEmpty())
                    return;

            }
            else if(strApkName=="net.sysolution.starter")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION);
                if(strtemp.isEmpty())
                    return;

            }
            else if(strApkName=="com.xixun.display")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION);
                if(strtemp.isEmpty())
                    return;

            }
            else if(strApkName=="com.xixun.xy.conn")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION);
                if(strtemp.isEmpty())
                    return;

            }
            else if(strApkName=="com.xixun.xy.update")
            {
                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION);
                if(strtemp.isEmpty())
                    return;

            }
//            else if(strApkName=="net.sysolution.basicapp")
//            {
//                QString strtemp=this->text(ENUM_DEVICE_PUBLISH_HEADE_BASICAPP_VERSION);
//                if(strtemp.isEmpty())
//                    return;

//            }
            OnSendStatusTip(tr("uninstalling"),Qt::blue);
}
void wUpgradeApkItem::onCheckRuningState(QString strApkName)
{
             QJsonObject json;
            json.insert("_id", getRandomString(10));
            json.insert("_type", "IsSoftwareRunning");
            json.insert("packageName", strApkName);
            m_strUrl="http://"+m_pLedCard->m_strCardIp+":2016/settings";
            HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
            OnSendStatusTip(tr("IsSoftwareRunning"),Qt::blue);
}

void wUpgradeApkItem::onUpgradeApk(QString strFileName)
{
    if(m_pLedCard->bPassword)
    {
        if(m_pLedCard->m_bLockStatus&&m_lockFlag == true)
        {
            OnSendStatusTip(tr("This screen is encrypted"),Qt::red);
            return;
        }
    }

    if(m_iSendingFlag==1)
    {
        return;
    }
    m_strApkFilePathName=strFileName;
    OnSendStatusTip(tr("Start upgrading"),Qt::blue);

    /* 发送连接请求 */
    ThreadUpgradeApk *m_pThreadSendPro=nullptr;
    QString url="http://"+m_pLedCard->m_strCardIp+":2016/upload?type=software";
    m_pThreadSendPro = new ThreadUpgradeApk(strFileName,url,0);
    this->moveToThread(m_pThreadSendPro);

    connect(m_pThreadSendPro,SIGNAL(sigSetLableText(QString)),this,SLOT(OnSendStatusTip(QString)));
    connect(m_pThreadSendPro,SIGNAL(sigSetProgressValue(int)),m_pProgress,SLOT(setValue(int)));
    connect(m_pThreadSendPro,SIGNAL(sigTimerOut()),m_pProgress,SLOT(slotTimeout()));


    m_pProgress->setMaximum(100);
   // connect(m_pThreadSendPro,SIGNAL(sigSetProgressMax(int)),m_pProgress,SLOT(setMaximum(int)));
    connect(m_pThreadSendPro,SIGNAL(sigFinished()),this,SLOT(OnThreadFinished()));
    connect(this,SIGNAL(sigUpgradeSuccess()),m_pThreadSendPro,SLOT(OnUpgradeSuccess()));
    connect(this,SIGNAL(sigUpgradeFail()),m_pThreadSendPro,SLOT(OnUpgradeFail()));
    m_iSendingFlag=1;
    m_pProgress->setValue(0);
    m_pThreadSendPro->start();
 }
void wUpgradeApkItem::onUpgradeFpga(QString strFileName)
{
    if(m_pLedCard->bPassword)
    {
        if(m_pLedCard->m_bLockStatus&&m_lockFlag == true)
        {
            OnSendStatusTip(tr("This screen is encrypted"),Qt::red);
            return;
        }
    }

    if(m_iSendingFlag==1)
    {
        return;
    }
    m_strFpgaFilePathName=strFileName;
    OnSendStatusTip(tr("Start upgrading"),Qt::blue);
    /* 发送连接请求 */
    ThreadUpgradeApk *m_pThreadSendPro=nullptr;
    QString url="http://"+m_pLedCard->m_strCardIp+":2016/upload?type=hardware";

    m_pThreadSendPro = new ThreadUpgradeApk(strFileName,url,1);
    this->moveToThread(m_pThreadSendPro);
    connect(m_pThreadSendPro,SIGNAL(sigSetLableText(QString)),this,SLOT(OnSendStatusTip(QString)));
    connect(m_pThreadSendPro,SIGNAL(sigSetProgressValue(int)),m_pProgress,SLOT(setValue(int)));
    connect(m_pThreadSendPro,SIGNAL(sigTimerOut()),m_pProgress,SLOT(slotTimeout()));
    m_pProgress->setMaximum(100);
   // connect(m_pThreadSendPro,SIGNAL(sigSetProgressMax(int)),m_pProgress,SLOT(setMaximum(int)));
    connect(m_pThreadSendPro,SIGNAL(sigFpgaFinished()),this,SLOT(OnThreadFpgaFinished()));
    connect(this,SIGNAL(sigUpgradeSuccess()),m_pThreadSendPro,SLOT(OnUpgradeSuccess()));
    connect(this,SIGNAL(sigUpgradeFail()),m_pThreadSendPro,SLOT(OnUpgradeFail()));
    m_iSendingFlag=1;
    m_pProgress->setValue(0);
    m_pThreadSendPro->start();
 }

void wUpgradeApkItem::slotTimeout()
{
    OnSendStatusTip(tr("Timeout"));
    m_iSendingFlag=0;
    OnCheckSoftVersions();
    OnCheckFpgaVersions();
}
void wUpgradeApkItem::OnSendStatusTip(QString strTip)
{
    QCoreApplication::processEvents();

    setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip);
    this->setTextColor(ENUM_DEVICE_PUBLISH_HEADE_REMARKS,Qt::blue);
    if(strTip==tr("Timeout"))
    {

    }

}
void wUpgradeApkItem::OnSendStatusTip(QString strTip,QColor cr)
{
    QCoreApplication::processEvents();

    setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip);
    this->setTextColor(ENUM_DEVICE_PUBLISH_HEADE_REMARKS,cr);

}
void wUpgradeApkItem::onAttrChanged()
{

}
void wUpgradeApkItem::OnThreadFinished()
{
    m_iSendingFlag=0;
    m_pProgress->setValue(100);
    qDebug()<<"OnThreadFinished";
    QFileInfo file(m_strApkFilePathName);
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "UpgradeSoftware");
    json.insert("fileName", file.fileName());
    json.insert("isCustom", true);
    HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
    OnSendStatusTip(tr("install start..."),Qt::blue);
    HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);

}
void wUpgradeApkItem::OnThreadFpgaFinished()
{
    m_iSendingFlag=0;
    m_pProgress->setValue(100);
    qDebug()<<"OnThreadFinished";
    QJsonObject json;
    json.insert("_id", getRandomString(10));
    json.insert("_type", "SynchronousHardwareVersion");
    HttpPostByTypeJsonObject(pHpptClient,m_strUrl,json);
    OnSendStatusTip(tr("SynchronousHardwareVersion"),Qt::blue);

}


QString wUpgradeApkItem::GetLedCardId()
{
    return m_pLedCard->m_strCardId;
}



void wUpgradeApkItem::SetItemParam(LedCard *p)
{

    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, p->m_strCardId);
    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, p->m_strCardIp);
    m_pLedCard->m_strCardId=p->m_strCardId;
    m_pLedCard->m_strCardIp=p->m_strCardIp;
    m_pLedCard->m_bOnLine=p->m_bOnLine;
 //    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_SIZE, 0, QString("%1 x %2").arg(p->m_iWidth).arg(p->m_iHeight));
    if(m_pLedCard->m_bOnLine)
    {
        m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Online.png"));
    }
    else
    {
        m_ImageOnline->setPixmap(QPixmap(":/res/DeviceManager/O_Offline.png"));
    }
    SetPasswordItem(m_pLedCard);
    setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, p->m_strCardRemarkName);
    OnCheckSoftVersions();
    OnCheckFpgaVersions();
//    //progresss.append(progress);
//    QTableWidgetItem *topLevelItem = new QTableWidgetItem();     //创建一个 TreeItem 容器用于后来装载控件
//    topLevelItem->setData(0,listProgramName->at(i));
//    topLevelItem->setFlags(topLevelItem->flags() & ~Qt::ItemIsEnabled & ~Qt::ItemIsSelectable);
//    /*上面用到的两个枚举中：~Qt::ItemIsEnabled可以保证单击该Item时不会被选中，但是在启用Ctrl + A时，全选操作会导致Item被选中。
//     * ~Qt::ItemIsSelectable的使用可以保证全选状态下也不会被选中，但是在单独使用时出现了虚线框，没有真正实现“不存在”的效果。所以必须两个同用。*/
//    ctrlProgramList->setItem(i,0,topLevelItem);
//    ctrlProgramList->setCellWidget(i, 1, progress);

}



QString wUpgradeApkItem::getRandomString(int length)
{
    qsrand(QDateTime::currentMSecsSinceEpoch());

    const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int size = sizeof(ch);

    char* str = new char[length + 1];

    int num = 0;
    for (int i = 0; i < length; ++i)
    {
        num = rand() % (size - 1);
        str[i] = ch[num];
    }

    QString res(str);
    return res;
}
/////////////////////////////////////////////////

void wUpgradeApkItem::OnProHttpResponse(QString url, QString postMD5, QByteArray data)
{
    Q_UNUSED(postMD5)
    //qDebug()<< url + "\r\n"+m_strUrl;
    if(url == m_strUrl)
    {
//        qDebug()<<"POST";
        //qDebug()<<postMD5;
        //qDebug()<<data;
        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=="TaskCommand"  )//发送节目命令应答
            {
                qDebug()<<"commandXixunPlayer response successed！";
            }

            else if(strType == "HasControllerPassword")
            {
                //if(m_pLedCard->bPassword!=jsonObject["result"].toBool())
                {
                    m_pLedCard->bPassword=jsonObject["result"].toBool();
                    SetPasswordItem(m_pLedCard);
                }
            }
             else if(strType == "VerifyPassword")
            {
                bool bStatus=jsonObject["result"].toBool();
                if(bStatus)//解密成功
                {
                    qDebug()<<"解密成功";
                    m_pLedCard->m_bLockStatus=false;
                }
                else
                {
                    qDebug()<<"解密失败";
                    m_pLedCard->m_bLockStatus=true;
                    X_UIMsgBoxOk *mb = new X_UIMsgBoxOk(tr("Tip Info"),tr("password is wrong"), m_pWnd,0);
                    mb->exec();

                }
                SetPasswordItem(m_pLedCard);
            }
            else if(strType == "UninstallSoftware")
            {
                OnSendStatusTip(tr("UninstallSoftware")+tr("Success")+"!",Qt::green);
            }
            else if(strType == "IsSoftwareRunning")
            {
                if(jsonObject["running"].toBool())
                {
                    OnSendStatusTip(tr("Running")+"!",Qt::green);

                }
                else {
                    OnSendStatusTip(tr("NoRunning")+"!",Qt::red);

                }

            }
            else if(strType =="UpgradeSoftware")
            {
                emit sigUpgradeSuccess();
                OnSendStatusTip(tr("install success"),Qt::green);
                OnCheckSoftVersions();


            }
            else if(strType == "SynchronousHardwareVersion"){
                        emit sigUpgradeSuccess();
                        OnSendStatusTip(tr("SynchronousHardwareVersion")+tr("Success"),Qt::green);
                        OnCheckFpgaVersions();

            }
            else if(strType =="CheckHardwareVersions")
            {
                QString strtempVer="";
                int itempVerCount=0;
                foreach(QJsonValue value, jsonObject["versions"].toArray()) {
                    QString strtempIcount=QString::number(itempVerCount);
                    if(itempVerCount==0)
                        strtempVer += "["+strtempIcount+"]:"+value.toString();
                    else
                        strtempVer +="\r\n["+strtempIcount+"]:"+value.toString();
                    itempVerCount++;

                }
                setData(ENUM_DEVICE_PUBLISH_HEADE_FPAG_VERSION, 0, strtempVer);
            }
            else if(strType == "CheckSoftVersions"){
                QString strTip="";
                QStringList strtempApkPackList;
                foreach(QJsonValue value, jsonObject["apps"].toArray()) {
                    QJsonObject oApp = value.toObject();
                    QString strtempApkPackageName=oApp["packageName"].toString();
                    QString strtempVersion=oApp["versionName"].toString();
                    if(strtempApkPackageName=="com.xixun.xixunplayer")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_XIXUNPLAYER_VERSION, 0, strtempVersion);
                    else if(strtempApkPackageName=="com.xixun.joey.cardsystem")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_CARDSYSTEM_VERSION, 0, strtempVersion);
                    else if(strtempApkPackageName=="net.sysolution.starter")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_STARTER_VERSION, 0, strtempVersion);
                    else if(strtempApkPackageName=="net.sysolution.taxiapp")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_TAXIAPP_VERSION, 0, strtempVersion);
                    else if(strtempApkPackageName=="com.xixun.display")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_DISPLAYER_VERSION, 0, strtempVersion);
                    else if(strtempApkPackageName=="com.xixun.xy.conn")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_CONNECTION_VERSION, 0, strtempVersion);
                    else if(strtempApkPackageName=="com.xixun.xy.update")
                        setData(ENUM_DEVICE_PUBLISH_HEADE_UPDATE_VERSION, 0, strtempVersion);
//                    else if(strtempApkPackageName=="net.sysolution.basicapp")
//                        setData(ENUM_DEVICE_PUBLISH_HEADE_BASICAPP_VERSION, 0, strtempVersion);

                    strtempApkPackList.append(strtempApkPackageName);

                }

            }
        }
        else//失败应答，打印失败和错误信息
        {
            if(strType == "UninstallSoftware")
            {
                OnSendStatusTip(tr("UninstallSoftware")+tr("Fail")+"!",Qt::red);
            }
            else if(strType == "IsSoftwareRunning")
            {
                OnSendStatusTip(tr("IsSoftwareRunning")+tr("Fail")+"!",Qt::red);
            }
            else if(strType =="UpgradeSoftware")
            {
                emit sigUpgradeFail();
                OnCheckSoftVersions();

            }
            else if(strType =="SynchronousHardwareVersion")
            {
                emit sigUpgradeFail();
                OnCheckFpgaVersions();

            }
        }

    }
}
