#include "wprogrampublishitem.h"
#include "loapptools.h"
#include "LoUIClass/x_uimsgboxok.h"
//#include "LoUIClass/louimsgboxokcancel.h"
#include <QMessageBox>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonDocument>
#include <QProgressBar>
#include <wDevicesManager/inputpassworddialog.h>
#include <globaldefine.h>
#include <QSizePolicy>
wProgramPublishItem::wProgramPublishItem(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();

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

void wProgramPublishItem::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(120);
    //启动心跳，监测设备在线和下线，3次超时表示下线

}


void wProgramPublishItem::refreshLable()
{

}
void wProgramPublishItem::onVerifyLockPassword()
{
    InputPasswordDialog *pDlg=new InputPasswordDialog(m_parent,1);
    connect(pDlg, SIGNAL(sigAcceptData(QString)), this, SLOT(onInputPasswordPro(QString)));
    pDlg->setWindowModality(Qt::WindowModal);
    pDlg->exec();
}
void wProgramPublishItem::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 wProgramPublishItem::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 wProgramPublishItem::onPublish()
{
//HttpPostByTypeWord("GetScreenSize");
//    HttpPostByTypeWordAndParma("VerifyPassword","pwd","123");
    if(m_pLedCard->bPassword)
    {
        if(m_pLedCard->m_bLockStatus)
        {
            OnSendStatusTip(tr("This screen is encrypted"));
            return;
        }
    }

    //QString strFilePathName=m_strProgramPath+"/"+m_strProgramName+"_tmp/"+"program.json";
    QString strFilePathName=m_strProgramPath+"/"+m_strProgramName+"_tmp/"+"program";

   /*老的接口，使用post命令发送节目任务数据到cardsystem，再有cardsystem序列号类给xixunplayer
    *  QFile file(strFilePathName);
    if(file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        QByteArray t = file.readAll();
        QString strCommandContent=QString(t);
        QJsonObject login_json;
        login_json.insert("_id", getRandomString(10));
        login_json.insert("_type", TaskCommand);
        login_json.insert("command", strCommandContent);


        HttpPostByTypeJsonObject(login_json);
        file.close();
    }
    */
    if(m_iSendingFlag==1)
    {
        //OnSendStatusTip(tr("already send,please wait!"));
        return;
    }
    OnSendStatusTip("");
    /* 发送连接请求 */
    ThreadSendPro *m_pThreadSendPro=nullptr;
    m_pThreadSendPro = new ThreadSendPro(strFilePathName,m_pLedCard->m_strCardIp,3333);

    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(sigSetProgressMax(int)),m_pProgress,SLOT(setMaximum(int)));
    connect(m_pThreadSendPro,SIGNAL(finished()),this,SLOT(OnThreadFinished()));
    m_iSendingFlag=1;
    m_pProgress->setValue(0);
    m_pThreadSendPro->start();
    this->moveToThread(m_pThreadSendPro);
 }
void wProgramPublishItem::OnSendStatusTip(QString strTip)
{
    QCoreApplication::processEvents();

    setData(ENUM_DEVICE_PUBLISH_HEADE_REMARKS, 0, strTip);
    if(!strTip.isEmpty())
      m_iSendingFlag=0;
//    m_pProgress->setStyleSheet("margin-top:12px; margin-bottom:12px");
//    m_pProgress->setStyleSheet("color:#ff0000");
    this->setTextColor(ENUM_DEVICE_PUBLISH_HEADE_REMARKS,Qt::green);
//    this->setBackgroundColor(ENUM_DEVICE_PUBLISH_HEADE_PROGRESS,Qt::red);
}
void wProgramPublishItem::onAttrChanged()
{

}
void wProgramPublishItem::OnThreadFinished()
{
    m_iSendingFlag=0;
    qDebug()<<"OnThreadFinished";
   // ui->sendBtn->setEnabled(true);
//    delete m_pThreadSendPro;
//    m_pThreadSendPro=nullptr;
}



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



void wProgramPublishItem::SetItemParam(LedCard *p)
{

    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_ID, 0, p->m_strCardId);
    setData(ENUM_DEVICE_PUBLISH_HEADE_REMARK_NAME, 0, p->m_strCardRemarkName);
    setData(ENUM_DEVICE_PUBLISH_HEADE_SCREEN_IP, 0, p->m_strCardIp);
    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);

//    //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 wProgramPublishItem::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 wProgramPublishItem::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//失败应答，打印失败和错误信息
        {
        }

    }
}
