//
// Created by 张雪明 <zhangxueming@uniontech.com> on 2024/11/19.
//
#include "ImmuRestoreModule.h"
#include "utils/Utils.h"
#include "utils/Process.h"
#include "common/CommonFunc.h"

ImmuRestoreModule::ImmuRestoreModule(FrameProxyInterface *frame, ComDeepinDaemonUosrecoveryInterface *interface,
        QObject *parent)
        : QObject(parent)
        , ModuleInterface(frame, interface)
{}

ImmuRestoreModule::~ImmuRestoreModule()
{}

void ImmuRestoreModule::initialize()
{
    if (m_restoreWidget == nullptr) {
        m_restoreWidget = new ImmuRestoreWidget;
    }

    if (m_emptyRestoreWidget == nullptr) {
        m_emptyRestoreWidget = new DefaultEmptyRestoreWidget;
    }

    QSize iconSize(149,149);
    QString sysRestoreIconPath = ":/resources/icons/v25/system_restore.png";
    m_sysRestoreIcon = Utils::hidpiPixmap(sysRestoreIconPath, iconSize);

    m_totalBackupSize = 0;
    this->showDataBackupFiles();
    this->showSystemCloneBackupFiles();
    this->showSystemBackupFiles();

    connect(m_restoreWidget, &ImmuRestoreWidget::notifyImmuSystemRestoreClicked,
            this, &ImmuRestoreModule::onStartSystemRestore);
    connect(m_restoreWidget, &ImmuRestoreWidget::notifyImmuDataRestoreClicked,
            this, &ImmuRestoreModule::onStartUserDataRestore);
    connect(m_restoreWidget, &ImmuRestoreWidget::notifyDeleteBackupInfo,
            this, &ImmuRestoreModule::onDeleteBackupFiles);
    connect(m_restoreWidget, &ImmuRestoreWidget::notifyShowBackupPage, [this] {
        Q_EMIT notifyShowBackupPage();
    });
    connect(m_emptyRestoreWidget, &DefaultEmptyRestoreWidget::notifyShowBackupPage, [this] {
        Q_EMIT notifyShowBackupPage();
    });

    connect(m_recoveryInterface, &ComDeepinDaemonUosrecoveryInterface::Success, this, &ImmuRestoreModule::onSuccess);
    connect(m_recoveryInterface, &ComDeepinDaemonUosrecoveryInterface::Error, this, &ImmuRestoreModule::onError);
    connect(m_recoveryInterface, &ComDeepinDaemonUosrecoveryInterface::ReportProgress,
            this, &ImmuRestoreModule::updateProgress);
}

QString ImmuRestoreModule::name() const
{
    return "ImmuRestoreModule";
}

QString ImmuRestoreModule::icons() const
{
    return QString(":/resources/icons/v25/restore_selected.svg");
}

QString ImmuRestoreModule::text() const
{
    return QString(tr("Restore"));
}

void ImmuRestoreModule::active()
{
    m_frameProxy->popAllWidget();
    if (m_totalBackupSize <= 0) {
        m_frameProxy->setCurrentWidget(this, m_emptyRestoreWidget);
    } else {
        m_frameProxy->setCurrentWidget(this, m_restoreWidget);
        m_restoreWidget->showFirstItem();
    }
}

void ImmuRestoreModule::updateData()
{
    m_totalBackupSize = 0;
    this->showDataBackupFiles();
    this->showSystemCloneBackupFiles();
    this->showSystemBackupFiles();
}

void ImmuRestoreModule::showSystemBackupFiles()
{
    QString curUserName = Utils::getUserName();
    bool isAdmin = Utils::isAdminUser(curUserName);
    if (isAdmin) {
        auto systemBackupReply = m_recoveryInterface->ListSystemBackup();
        systemBackupReply.waitForFinished();
        if (!systemBackupReply.isValid()) {
            qCritical() <<systemBackupReply.error();
            return;
        }

        BackupInfoList sysBackupList;
        QJsonObject jsonRoot = Utils::QStringToJson(systemBackupReply.value());
        QJsonArray jsonBackupInfo = jsonRoot.value("backup").toArray();
        // 读取记录备份ID和用户名映射文件
        QJsonDocument backupIDUserNameDoc;
        if (!Utils::readJsonFile(BACKUP_USER_INFO, backupIDUserNameDoc)) {
            backupIDUserNameDoc = QJsonDocument::fromJson("{}");
        }
        QJsonObject backupIDUserNameObject = backupIDUserNameDoc.object();
        for (auto jsonObject : jsonBackupInfo) {
            BackupInfo info;
            info.unmarshal(jsonObject.toObject());

            if (backupIDUserNameObject.keys().contains(info.operateID)) {
                // 根据 info.operateID 查询用户名
                info.username = backupIDUserNameObject.value(info.operateID).toObject().value("username").toString();
            } else {
                // 初始化备份，用户名使用”管理员“
                info.username = tr("Administrator");
            }

            if (info.recoveryType == static_cast<int>(RecoveryType::OSTree)) {
                if (info.submissionType == CommitType::SystemCommit) {
                    info.remark = tr("Automatical backup before system updates");
                } else if (info.submissionType == CommitType::InstallerCommit) {
                    info.remark = tr("Initial backup during system installation");
                    info.systemVersion = tr("Initial backup");
                }
            } else if (info.operateType == static_cast<int> (OperateType::ImmutableSystemBackup)) {
                if ((info.submissionType == CommitType::InstallerCommit) &&
                    (info.recoveryType == static_cast<int> (RecoveryType::ImmutableMode))) {
                    info.remark = tr("Initial backup during system installation");
                    info.systemVersion = tr("Initial backup");
                    continue;
                }
            }
            sysBackupList.append(info);
            ++m_totalBackupSize;
        }
        m_restoreWidget->setSystemBackupInfoData(sysBackupList);
        m_restoreWidget->setData(sysBackupList);
    } else {
        BackupInfoList emptyBackupList;
        m_restoreWidget->setData(emptyBackupList);
    }
}

void ImmuRestoreModule::showDataBackupFiles()
{
    QString curUserName = Utils::getUserName();
    auto userDataReply = m_recoveryInterface->ListUserDataBackup(curUserName);
    userDataReply.waitForFinished();
    if (!userDataReply.isValid()) {
        qCritical() << userDataReply.error();
        return;
    }

    BackupInfoList backupInfoList;
    QJsonObject jsonRoot = Utils::QStringToJson(userDataReply.value());
    QJsonArray jsonBackupInfo = jsonRoot.value("backup").toArray();
    for (auto jsonObject : jsonBackupInfo) {
        BackupInfo info;
        info.unmarshal(jsonObject.toObject());
        backupInfoList.append(info);
        ++m_totalBackupSize;
    }
    m_restoreWidget->setDataBackupInfoData(backupInfoList);
    m_restoreWidget->setData(backupInfoList);
}

void ImmuRestoreModule::showSystemCloneBackupFiles()
{
    QString curUserName = Utils::getUserName();
    GhostLogQuery ghostQuery;
    ghostQuery.mask = 0;
    ghostQuery.userName = curUserName;
    ghostQuery.orderByTimeDesc = true; // 日志默认按照时间排序显示
    //QJsonObject request = ghostQuery.marshal();
    auto logReply = m_recoveryInterface->QueryUImgBackup(ghostQuery);
    logReply.waitForFinished();
    if (!logReply.isValid()) {
        qCritical() << "QueryUImgBackup err: "<<logReply.error();
        return;
    }

    BackupInfoList ghostLogList;
    QJsonObject jsonGhostRoot = Utils::QStringToJson(logReply.value());
    QJsonArray logsObject = jsonGhostRoot.value("logs").toArray();
    for (auto jsonObject : logsObject) {
        GhostLog ghostLog;
        ghostLog.unmarshal(jsonObject.toObject());
        BackupInfo ghostInfo;
        ghostInfo.operateID = ghostLog.operateID;
        ghostInfo.username = ghostLog.userName;
        ghostInfo.operateType = static_cast<int> (ghostLog.operateType);
        ghostInfo.status = ghostLog.status;
        ghostInfo.backupDevUUID = ghostLog.deviceUUID;
        ghostInfo.backupDeviceRemovable = ghostLog.isRemoveable;
        ghostInfo.backupPath = ghostLog.path;
        ghostInfo.startTime = ghostLog.time;
        ghostInfo.systemVersion = ghostLog.path;
        ghostInfo.remark = ghostLog.deviceUUID;
        ghostLogList.append(ghostInfo);
        ++m_totalBackupSize;
    }
    m_restoreWidget->setGhostInfoData(ghostLogList);
}

void ImmuRestoreModule::setSystemSyncType(int type)
{
    m_systemSyncType = type;
}

void ImmuRestoreModule::setUserDataSyncType(int type)
{
    m_userDataSyncType = type;
}

void ImmuRestoreModule::setSelinuxEnable(bool enable)
{
    m_isSelinuxEnabled = enable;
}

void ImmuRestoreModule::setLVM(bool isLVM)
{
    m_isLVMOnly = isLVM;
}

void ImmuRestoreModule::setEncrypted(bool isEncrypted)
{
    m_isEncrypted = isEncrypted;
}

void ImmuRestoreModule::setDevice(bool isDevice)
{
    m_isDevice = isDevice;
}

void ImmuRestoreModule::setFileMgrEncrypted(bool encrypt)
{
    m_isFileMgrEncrypted = encrypt;
}

void ImmuRestoreModule::setMajorVersion(int version)
{
    m_osMajorVer = version;
}

void ImmuRestoreModule::setMinorVersion(int version)
{
    m_osMinorVer = version;
}

void ImmuRestoreModule::onSystemRestore()
{}

void ImmuRestoreModule::onStartSystemRestore(const BackupInfo &backupInfo)
{
    m_frameProxy->setMenuDisabled(true);
    m_frameProxy->setQuitMenuDisabled(true);
    m_frameProxy->setWindowFuncClose(false);
//    m_systemRestoreWidget->setTips(tr("Preparing for system restore..."));
    // m_systemRestoreWidget->setTipsStyleSheet("QLabel {"
    //                                             "color: #000000;"
    //                                             "}");
//    m_systemRestoreWidget->startSpinner();

    SystemRestoreRequest request;
    request.username = Utils::getUserName();
    request.operateID = QUuid::createUuid().toString();
    request.backupInfo = backupInfo;
    m_curSysOpID = request.operateID;
    auto requestObject = request.marshal();
    QString reqStr = Utils::JsonToQString(requestObject);
    auto reply = m_recoveryInterface->SystemRestore(request);
    reply.waitForFinished();
    if (!reply.isValid()) {
        m_curSysOpID.clear();
        m_frameProxy->setMenuDisabled(false);
        m_frameProxy->setQuitMenuDisabled(false);
        m_frameProxy->setWindowFuncClose(true);
 //       m_systemRestoreWidget->setTips(tr("DBus error, please try again"));
//        m_systemRestoreWidget->stopSpinner();
        qCritical() << reply.error();
        return;
    }

    if (backupInfo.recoveryType != static_cast<int>(RecoveryType::OSTree)) { // OSTree 是异步去处理的
        m_frameProxy->setMenuDisabled(false);
        m_frameProxy->setQuitMenuDisabled(false);
        m_frameProxy->setWindowFuncClose(true);
  //      m_systemRestoreWidget->setTips("");
 //       m_systemRestoreWidget->stopSpinner();
        if ((m_osMajorVer >= OS_VERSION_MAJOR_V25) && Utils::isImmutableSystem()) {
            onShowProgress(OperateType::ImmutableSystemRestore,
                           tr("Restoring..."),
                           tr("Time remaining:") + " ",
                           tr("To avoid data loss, please do not use your computer during the process."));
        } else {
            this->reboot();
        }
    }
}

void ImmuRestoreModule::onDataRestore()
{}

void ImmuRestoreModule::onStartUserDataRestore(const BackupInfo &backupInfo)
{
    if (m_recoveryInterface->IsRunning()) {
        QString operateID;
        QString userName;
        int opType;
        int progress;
        m_recoveryInterface->GetContext(operateID, userName, opType, progress);
        QString opTypeDes = Common::GetOperateTypeDes(opType);
        QString tips = tr("Task conflict, user %1's task %2 has not been completed").arg(userName).arg(opTypeDes);
        m_restoreWidget->showErrorDlg(tips);
        qWarning()<<"onStartUserDataRestore, another task is running, operateID = "<<operateID
                  <<", opType = "<<opType<<", progress = "<<progress;
        return;
    }

    m_frameProxy->setMenuDisabled(true);
    m_frameProxy->setQuitMenuDisabled(true);
    m_frameProxy->setWindowFuncClose(false);

    UserDataRestoreRequest request;
    request.username = Utils::getUserName();
    request.operateID = QUuid::createUuid().toString();
    request.backupInfo = backupInfo;
    m_curUserOpID = request.operateID;
    // 调整一下结构中的rootUUID
    if (request.backupInfo.rootUUID.compare(m_frameProxy->rootUUID())) {
        request.backupInfo.rootUUID = m_frameProxy->rootUUID();
    }
    // auto requestObject = request.marshal();
    auto reply = m_recoveryInterface->UserDataRestore(request);
    reply.waitForFinished();
    if (!reply.isValid()) {
        m_curUserOpID.clear();
        qCritical() << reply.error();
        onShowResult(false, static_cast<int>(OperateType::UserDataRestore), tr("DBus error, please try again"));
        return;
    }

    int retVal = reply.value();
    if (reply.value() != ErrorCode::OK) {
        m_curUserOpID.clear();
        qCritical() <<"data restore error: "<<reply.value();
        onShowProgress(OperateType::UserDataRestore,
                   tr("Restoring..."),
                   tr("Time remaining:") + " ",
                   tr("To avoid data loss, please do not use your computer during the process."));
        if (retVal == static_cast<int>(ErrorCode::PartitionNotMount)) {
            this->showDataBackupFiles();
        }
        onShowResult(false, static_cast<int>(OperateType::UserDataRestore));
        return;
    }

    onShowProgress(OperateType::UserDataRestore,
                   tr("Restoring..."),
                   tr("Time remaining:") + " ",
                   tr("To avoid data loss, please do not use your computer during the process."));
}

void ImmuRestoreModule::onDeleteBackupFiles(const BackupInfo &backupInfo)
{
    if (m_recoveryInterface->IsRunning()) {
        QString operateID;
        QString userName;
        int opType;
        int progress;
        m_recoveryInterface->GetContext(operateID, userName, opType, progress);
        QString opTypeDes = Common::GetOperateTypeDes(opType);
        QString tips = tr("Task conflict, user %1's task %2 has not been completed").arg(userName).arg(opTypeDes);
        m_restoreWidget->setDeleteWidgetStatus(true, false, backupInfo.operateID);
        m_restoreWidget->showErrorDlg(tips);
        return;
    }
    RemoveUserDataBackupRequest removeUserDataBackupRequest;
    removeUserDataBackupRequest.username = Utils::getUserName();
    removeUserDataBackupRequest.backupInfo = backupInfo;
    removeUserDataBackupRequest.operateID = QUuid::createUuid().toString();
    m_curSysOpID = removeUserDataBackupRequest.operateID;

    //QJsonObject request = removeUserDataBackupRequest.marshal();
    auto removeReply = m_recoveryInterface->RemoveBackupInfo(removeUserDataBackupRequest);
    removeReply.waitForFinished();
    if (!removeReply.isValid()) {
        qCritical() << "RemoveBackupInfo removeReply isInvalid, error: " << removeReply.error();
        m_restoreWidget->setDeleteWidgetStatus(true, false, backupInfo.operateID);
        return ;
    }

    int retCode = removeReply.value();
    if (retCode != ErrorCode::OK) {
        qCritical()<<"RemoveBackupInfo failed, retCode = "<<retCode;
        m_restoreWidget->setDeleteWidgetStatus(true, false, backupInfo.operateID);
        return;
    }
}

void ImmuRestoreModule::onBack()
{
    if (m_frameProxy) {
        m_frameProxy->back();
    }
}

void ImmuRestoreModule::onBackHome()
{
    if (nullptr != m_frameProxy) {
        m_frameProxy->backHome();
    }
}

void ImmuRestoreModule::onShowResult(bool success, int operateType, const QString &errorMsg)
{
    QString resultText = "";
    QString btnText = tr("OK", "button");

    if (operateType == static_cast<int>(OperateType::UserDataRestore) ||
        operateType == static_cast<int>(OperateType::SystemRestore) ||
        operateType == static_cast<int>(OperateType::ImmutableSystemRestore)) {
        resultText = success ? tr("Restore successful!") : tr("Sorry, restore failed!");
    } else if (operateType == static_cast<int>(OperateType::DimFileRestore)) {
        resultText = success ? tr("The backup file was parsed successfully") : tr("Failed to parse the backup file");
    } else {
        return ;
    }

    m_frameProxy->setMenuDisabled(false);
    m_frameProxy->setQuitMenuDisabled(false);
    m_frameProxy->setWindowFuncClose(true);

    if (m_progressWidget != nullptr) {
        m_frameProxy->popWidget();
    }

    if (m_resultWidget == nullptr) {
        m_resultWidget = new ResultWidgetV2(operateType, success, resultText, errorMsg, btnText, false);
        connect(m_resultWidget, &ResultWidgetV2::done, this, &ImmuRestoreModule::onBackHome);
    } else {
        m_resultWidget->set(operateType, success, resultText, errorMsg, btnText, false);
    }

    m_frameProxy->setCurrentWidget(this, m_resultWidget);
    m_frameProxy->enableBackWard(true);
    m_frameProxy->enableModule(true);

    if (operateType == static_cast<int>(OperateType::ImmutableSystemRestore)) {
        if (success) {
            this->reboot();
        }
    }
}

void ImmuRestoreModule::onShowResult(bool success, const Response &rsp)
{
    QString err = tr("Operation failed,error code: %1").arg(rsp.errCodeStr);
    int operateType = static_cast<int>(rsp.operateType);

    QString resultText = "";
    QString btnText = tr("OK", "button");

    if (operateType == static_cast<int>(OperateType::UserDataRestore) ||
        operateType == static_cast<int>(OperateType::SystemRestore)) {
        resultText = success ? tr("Restore successful!") : tr("Sorry, restore failed!");
    } else if (operateType == static_cast<int>(OperateType::DimFileRestore)) {
        resultText = success ? tr("The backup file was parsed successfully") : tr("Failed to parse the backup file");
    } else if (operateType == static_cast<int>(OperateType::ImmutableSystemRestore)) {
        resultText = err;
    } else {
        return ;
    }

    m_frameProxy->setMenuDisabled(false);
    m_frameProxy->setQuitMenuDisabled(false);
    m_frameProxy->setWindowFuncClose(true);

    if (m_progressWidget != nullptr) {
        m_frameProxy->popWidget();
    }

    if (m_resultWidget == nullptr) {
        m_resultWidget = new ResultWidgetV2(operateType, success, resultText, rsp.errMsg, btnText, false);
        connect(m_resultWidget, &ResultWidgetV2::done, this, &ImmuRestoreModule::onBackHome);
    } else {
        m_resultWidget->set(operateType, success, resultText, rsp.errMsg, btnText, false);
    }

    m_frameProxy->setCurrentWidget(this, m_resultWidget);
    m_frameProxy->enableBackWard(true);
    m_frameProxy->enableModule(true);

    if (operateType == static_cast<int>(OperateType::ImmutableSystemRestore)) {
        if (success) {
            this->reboot();
        }
    }
}

void ImmuRestoreModule::onShowProgress(OperateType opType, const QString &mainTitle, const QString &subTitle, const QString &warning)
{
    if (m_progressWidget == nullptr) {
        m_progressWidget = new ProgressWidgetV2(mainTitle, subTitle, warning);
    } else {
        m_progressWidget->setMainTitle(mainTitle);
        m_progressWidget->setSubTitle(subTitle);
        m_progressWidget->setWarning(warning);
    }
    switch (opType) {
        case OperateType::ImmutableSystemRestore: {
            m_progressWidget->setIconPixmap(m_sysRestoreIcon);
            break;
        }
        default: // 设计师还没提供，暂时先使用一样的
            m_progressWidget->setIconPixmap(m_sysRestoreIcon);
            break;
    }
    m_progressWidget->setValue(0);
    m_frameProxy->setCurrentWidget(this, m_progressWidget);
    m_frameProxy->setMenuDisabled(true);
    m_frameProxy->setQuitMenuDisabled(true);
    m_frameProxy->setWindowFuncClose(false);
    m_frameProxy->enableBackWard(false);
    m_frameProxy->enableModule(false);
}

void ImmuRestoreModule::updateProgress(const QString &progress)
{
    QJsonObject jsonObject = Utils::QStringToJson(progress);
    int operateType = jsonObject.value("operateType").toInt();
    if ((operateType != static_cast<int>(OperateType::SystemRestore)) &&
        (operateType != static_cast<int>(OperateType::ImmutableSystemRestore)) &&
        (operateType != static_cast<int>(OperateType::UserDataRestore)) &&
        (operateType != static_cast<int>(OperateType::DimFileRestore))) {
        return;
    }

    QString curOperateID = jsonObject.value("operateID").toString();
    if ((operateType == static_cast<int>(OperateType::UserDataRestore)) && curOperateID != m_curUserOpID ||
        (operateType == static_cast<int>(OperateType::ImmutableSystemRestore)) && curOperateID != m_curSysOpID) {
        return;
    }

    auto curProgress = jsonObject.value("progress").toInt();
    if (m_progressWidget != nullptr) {
        auto remainSecond = jsonObject.value("remainSecond").toInt();
        m_progressWidget->setRemainTime(remainSecond);
        m_progressWidget->setValue(curProgress);
        if (curProgress >= 100) {
            onShowResult(true, operateType);
        }
    }
}

void ImmuRestoreModule::onError(const QString &errMsg)
{
    qCritical()<<"ImmuRestoreModule::onError, errMsg: "<<errMsg.toLocal8Bit().data();
    QJsonObject jsonObject = Utils::QStringToJson(errMsg);
    Response rsp;
    rsp.unmarshal(jsonObject);
    QString errInfo = "Unknown";
    if (jsonObject.contains("errMsg")) {
        errInfo = jsonObject.value("errMsg").toString();
    }

    int opType = -1;
    if (jsonObject.contains("operateType")) {
        opType = jsonObject.value("operateType").toInt();
    }
    QString curOperateID = jsonObject.value("operateID").toString();
    int backupInfoType = jsonObject.value("backupInfoType").toInt(-1);
    QString err = tr("Operation failed,error code: %1").arg(rsp.errCodeStr);
    // if (rsp.errCodeStr == ImmutableErrCode::OTHER_INSTANCE_RUNNING) {
    //     err = tr("Installation of apps,system updates,etc.,resulting in operation failures,please check and retry.");
    // }
    OperateType operateType = static_cast<OperateType>(opType);
    if (operateType == OperateType::UserDataRestore) {
        if (m_curUserOpID == curOperateID) {
            if (rsp.errMsg.startsWith("path not exit,")) {
                this->showDataBackupFiles();
            }
            onShowResult(false, opType, errInfo);
        }
        return;
    }

    if (m_curSysOpID != curOperateID) {
        return;
    }
    if (operateType == OperateType::ImmutableSystemRestore) {
        onShowResult(false, rsp);
    } else if (operateType == OperateType::removeBackup) {
        if (backupInfoType == static_cast<int>(OperateType::ImmutableSystemBackup)) {
            m_restoreWidget->showErrorDlg(err);
        }
    } else {
        onShowResult(false, opType, errInfo);
    }
}

void ImmuRestoreModule::onSpaceChanged(const QString &space)
{}

void ImmuRestoreModule::onSuccess(const QString &msg)
{
    QJsonObject jsonObject = Utils::QStringToJson(msg);
    if (jsonObject.isEmpty()) {
        return;
    }

    int operateType = jsonObject.value("operateType").toInt(-1);
    OperateType opType = static_cast<OperateType>(operateType);
    if (!(OperateType::removeBackup == opType || OperateType::ImmutableSystemRestore == opType)) {
        return;
    }

    V20Response rsp;
    rsp.unmarshal(jsonObject);
    qWarning()<<"msg: "<<msg.toLocal8Bit().data();
    if (m_curSysOpID != rsp.operateID) {
        qWarning()<<"m_curSysOpID: "<<m_curSysOpID<<", operateID: "<<rsp.operateID;
        return;
    }

    switch (opType) {
        case OperateType::removeBackup: {
            QString operateId = jsonObject.value("operateId").toString();
            m_restoreWidget->removeBackupInfo(operateId);
            break;
        }
        case OperateType::ImmutableSystemRestore: {
            onShowResult(true, operateType);
            break;
        }
        default:
            break;
    }

    m_frameProxy->enableBackWard(true);
    m_frameProxy->enableModule(true);
    m_frameProxy->setWindowFuncClose(true);
}

void ImmuRestoreModule::doAdminAuthorityTask(bool result, int type)
{
    if (result) {
        AuthorityType authType = static_cast<AuthorityType>(type);
        if (AuthorityType::SystemRestoreV20 == authType) {
            return this->onSystemRestore();
        } else if (AuthorityType::InitRestoreV20 == authType) {
            //return this->onInitializeRestore();
        }
    }
}

void ImmuRestoreModule::doCommonAuthorityTask(bool result, int type)
{
    if (result) {
        AuthorityType authType = static_cast<AuthorityType>(type);
        if (AuthorityType::DataRestore == authType) {
            return this->onDataRestore();
        }
    }
}

int ImmuRestoreModule::reboot()
{
    if (m_restoreWidget->showRebootDialog(tr("Restore"),
                         tr("The system is ready to be restored. Please restart and restore the system immediately."),
                         "uos-recovery",  tr("Reboot and Restore"))) {
        auto rebootReply = m_recoveryInterface->Reboot();
        rebootReply.waitForFinished();
        if (!rebootReply.isValid()) {
            qCritical() << Q_FUNC_INFO <<" call Reboot failed! " << rebootReply.error();
            return -1;
        }
    }

    return 0;
}

void ImmuRestoreModule::checkAdminAuthority(AuthorityType type)
{
    if (nullptr == m_adminAuthUtils) {
        m_adminAuthUtils = new AuthorityUtils();
        connect(m_adminAuthUtils, &AuthorityUtils::notifyAdminAuthority, this, &ImmuRestoreModule::doAdminAuthorityTask);
    }
    m_adminAuthUtils->authorization(type);
}

void ImmuRestoreModule::checkCommonAuthority(AuthorityType type)
{
    if (nullptr == m_commonAuthUtils) {
        m_commonAuthUtils = new AuthorityUtils();
        connect(m_commonAuthUtils, &AuthorityUtils::notifyCommonUserAuthority, this, &ImmuRestoreModule::doCommonAuthorityTask);
    }

    m_commonAuthUtils->checkCommonUserAuthentication(type);
}
