#include "upgrade.h"
#include "ui_upgrade.h"

#include "CAppInfo.h"
#include <QFile>
#include "logproc.h"
#include "popMsgBox.h"
#include "CCommonTools.h"
#include "CSqlite3DBProc.h"

upgrade::upgrade(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::upgrade)
{
    ui->setupUi(this);

    setStyleSheet(g_appInfoPtr->m_sQssStr);

    initUI();

    qRegisterMetaType<CDownLoadFileInfo>("CDownLoadFileInfo");
    connect(g_httpBllPtr.get(), SIGNAL(sgnDownLoadFile(CDownLoadFileInfo)), this, SLOT(onDownLoadFile(CDownLoadFileInfo)));
}

upgrade::~upgrade()
{    
    disconnect(g_httpBllPtr.get(), SIGNAL(sgnDownLoadFile(CDownLoadFileInfo)), this, SLOT(onDownLoadFile(CDownLoadFileInfo)));

    delete ui;
}

void upgrade::initUI()
{
    setGeometry(0, 0, g_appInfoPtr->m_fRate*(600 - 24), g_appInfoPtr->m_fRate*340);
    ui->label_upgradeTitle->adjustSize();
    ui->label_upgradeTitle->setGeometry(g_appInfoPtr->m_fRate*80, g_appInfoPtr->m_fRate*86, ui->label_upgradeTitle->width(), ui->label_upgradeTitle->height());
    ui->label_upgradePregress->adjustSize();
    ui->label_upgradePregress->setGeometry(ui->label_upgradeTitle->x(), g_appInfoPtr->m_fRate*184, g_appInfoPtr->m_fRate*200, ui->label_upgradePregress->height());
    ui->pgb_upgrade->setGeometry(ui->label_upgradeTitle->x(), ui->label_upgradePregress->y() + ui->label_upgradePregress->height() + g_appInfoPtr->m_fRate*16,
                                 g_appInfoPtr->m_fRate*440, g_appInfoPtr->m_fRate*8);
    ui->label_upgradeHint->adjustSize();
    ui->label_upgradeHint->setGeometry(ui->label_upgradeTitle->x(), ui->pgb_upgrade->y() + ui->pgb_upgrade->height() + g_appInfoPtr->m_fRate*10,
                                       g_appInfoPtr->m_fRate*500, ui->label_upgradeHint->height());
}

void upgrade::startUpgrade(QList<UpdateInfo> sList)
{       
    m_sList = sList;
    if(m_sList.count() > 0)
    {
        m_curInfo = m_sList[0];
        m_sList.pop_front();


        if(m_curInfo.nType == 2)
        {
            ui->label_upgradeHint->setText(QString::fromLocal8Bit("正在获取升级信息…"));
            QApplication::processEvents();

            QString sFileName = m_curInfo.sUrl.right(m_curInfo.sUrl.length() - m_curInfo.sUrl.lastIndexOf("/") - 1);
                sFileName = g_appInfoPtr->m_sCacheFileDir + "uptemp/" + sFileName;
            CHttpRequestPackage hrp;
            hrp.sUri = m_curInfo.sUrl;
            hrp.sCommonStr = sFileName;
            hrp.nRequestType = RequestType::rtDownLoadFile;

            g_httpBllPtr->downLoad(hrp);
        }
    }
}

void upgrade::retry()
{
    QString sFileName = m_curInfo.sUrl.right(m_curInfo.sUrl.length() - m_curInfo.sUrl.lastIndexOf("/") - 1);
        sFileName = g_appInfoPtr->m_sCacheFileDir + "uptemp/" + sFileName;
    CHttpRequestPackage hrp;
    hrp.sUri = m_curInfo.sUrl;
    hrp.sCommonStr = sFileName;
    hrp.nRequestType = RequestType::rtDownLoadFile;

    g_httpBllPtr->downLoad(hrp);
}

void upgrade::onDownLoadFile(CDownLoadFileInfo downLoadFileInfo)
{
    QString sFileName = m_curInfo.sUrl.right(m_curInfo.sUrl.length() - m_curInfo.sUrl.lastIndexOf("/") - 1);
    sFileName = g_appInfoPtr->m_sCacheFileDir + "uptemp/" + sFileName;
    if (downLoadFileInfo.sFileName == sFileName)
    {
        if (downLoadFileInfo.nCode == 200)
        {
            if(m_curInfo.nType == 2)
            {
                //解析升级文件
                QString sUrlPrefix = m_curInfo.sUrl.left(m_curInfo.sUrl.lastIndexOf("/")+1);
                QString sFileName = m_curInfo.sUrl.right(m_curInfo.sUrl.length() - m_curInfo.sUrl.lastIndexOf("/") - 1);
                sFileName = g_appInfoPtr->m_sCacheFileDir + "uptemp/" + sFileName;
                QFile sFile(sFileName);
                if(!sFile.open(QIODevice::ReadOnly))
                {
                    popMsg(QString::fromLocal8Bit("加载升级文件失败！"), QString::fromLocal8Bit("系统提示"), this);
                    myDebug()<<QString::fromLocal8Bit("加载升级文件失败！");
                    return;
                }
                QString upStr = sFile.readAll();
                Json::Reader reader;
                Json::Value rootJson = Json::Value::null;
                if(!reader.parse(upStr.toStdString(), rootJson))
                {
                    popMsg(QString::fromLocal8Bit("解析升级文件失败！"), QString::fromLocal8Bit("系统提示"), this);
                    myDebug()<<QString::fromLocal8Bit("解析升级文件失败！");
                    return;
                }

                __int64 versionValue = rootJson["versionValue"].asInt64();
                if(versionValue != g_appInfoPtr->m_nVersionId)
                {
                    popMsg(QString::fromLocal8Bit("升级文件版本不一致！"), QString::fromLocal8Bit("系统提示"), this);
                    myDebug()<<QString::fromLocal8Bit("升级文件版本不一致！");
                    return;
                }

                int nCount = 0;
                int nSize = rootJson["files"].size();
                ui->pgb_upgrade->setValue(0);
                ui->pgb_upgrade->setMaximum(nSize*2);
                ui->label_upgradePregress->setText(ui->pgb_upgrade->text());
                QApplication::processEvents();

                QApplication::processEvents();
                for(int i = 0; i < nSize; i++)
                {
                    QString sName = rootJson["files"][i]["name"].asString().c_str();
                    QString sMd5 = rootJson["files"][i]["md5"].asString().c_str();
                    QString sFileMd5 = CCommonTools::fileMd5(sName);
                    if(sFileMd5 != sMd5)
                    {
                        UpdateInfo upInfo;
                        upInfo.nType = 3;
                        upInfo.sUrl = sUrlPrefix + rootJson["files"][i]["url"].asString().c_str();
                        upInfo.sMd5 = sMd5;
                        upInfo.sDestFileName = sName;
                        m_sList.push_back(upInfo);
                        myDebug()<<sName;
                        nCount++;
                    }
                    if(ui->pgb_upgrade->value() < ui->pgb_upgrade->maximum())
                    {
                        ui->pgb_upgrade->setValue(ui->pgb_upgrade->value()+1);
                        ui->label_upgradePregress->setText(ui->pgb_upgrade->text());
                    }
                    QApplication::processEvents();
                }

                ui->pgb_upgrade->setMaximum(2*nCount);
                ui->pgb_upgrade->setValue(nCount);
                ui->label_upgradeHint->setText(QString::fromLocal8Bit("正在配置升级项…"));
                QApplication::processEvents();

                QFile::remove(sFileName);
            }

            if(m_curInfo.nType == 3)
            {
                QString sFileName = m_curInfo.sUrl.right(m_curInfo.sUrl.length() - m_curInfo.sUrl.lastIndexOf("/") - 1);
                QString sName = sFileName;
                sFileName = g_appInfoPtr->m_sCacheFileDir + "uptemp/" + sFileName;
                QFile file(sFileName);
                if(!file.exists())
                {
                    popMsg(QString::fromLocal8Bit("下载文件不存在"), QString::fromLocal8Bit("系统提示"), this);
                    myDebug()<<QString::fromLocal8Bit("下载文件不存在");
                    return;
                }

                QString sFileMd5 = CCommonTools::fileMd5(sFileName);
                if(sFileMd5 != m_curInfo.sMd5)
                {
                    popMsg(QString::fromLocal8Bit("下载文件MD5校验不通过"), QString::fromLocal8Bit("系统提示"), this);
                    myDebug()<<QString::fromLocal8Bit("下载文件MD5校验不通过");
                    return;
                }

                if(sName != "launcher.exe")
                {
                    QFile::remove(m_curInfo.sDestFileName);
                    CCommonTools::createDir(m_curInfo.sDestFileName);
                    if(!file.copy(m_curInfo.sDestFileName))
                    {
                        popMsg(QString::fromLocal8Bit("拷贝升级文件失败！"), QString::fromLocal8Bit("系统提示"), this);
                        myDebug()<<QString::fromLocal8Bit("拷贝升级文件失败！")<<m_curInfo.sDestFileName;
                        return;
                    }
                    QFile::remove(sFileName);
                }
                else
                {
                    m_bUpdateOeLauncher = true;
                }

                if(ui->pgb_upgrade->value() < ui->pgb_upgrade->maximum())
                {
                    ui->pgb_upgrade->setValue(ui->pgb_upgrade->value()+1);
                    ui->label_upgradePregress->setText(ui->pgb_upgrade->text());
                }
                QApplication::processEvents();
            }

            if(m_sList.count() > 0)
            {
                m_curInfo = m_sList[0];
                m_sList.pop_front();


                QString sFileName = m_curInfo.sUrl.right(m_curInfo.sUrl.length() - m_curInfo.sUrl.lastIndexOf("/") - 1);
                    sFileName = g_appInfoPtr->m_sCacheFileDir + "uptemp/" + sFileName;
                CHttpRequestPackage hrp;
                hrp.sUri = m_curInfo.sUrl;
                hrp.sCommonStr = sFileName;
                hrp.nRequestType = RequestType::rtDownLoadFile;
                g_httpBllPtr->downLoad(hrp);
            }
            else
            {

//                    if(m_curInfo.nType == 3)
                    {
                        QString sql = QString("update t_sysinfo set version_id='%1',version_code='%2'")
                                .arg(g_appInfoPtr->m_nVersionId).arg(g_appInfoPtr->m_sVersionCode);

                        if(!g_sysDBProcPtr->ExcuteSql(sql.toStdString()))
                        {
                            popMsg(QString::fromLocal8Bit("更新版本信息失败！"), QString::fromLocal8Bit("系统提示"), this);
                            myDebug()<<QString::fromLocal8Bit("更新版本信息失败！");
                            return;
                        }
                    }

                    emit updateSucceed(m_bUpdateOeLauncher);
            }
        }
        else
        {
//            if(downLoadFileInfo.sMessage.isEmpty())
            {
                int nRet = popMsg(QString::fromLocal8Bit("下载失败,是否重试？"), QString::fromLocal8Bit("系统提示"), this);
                if(nRet == QDialog::Accepted)
                {
                    retry();
                }
                else
                {
                    emit exitUpgrade();
                }
            }
//            else
//            {
//                popMsg(downLoadFileInfo.sMessage, QString::fromLocal8Bit("系统提示"), this);
//            }
        }
    }
}
