//
// Created by 张雪明 <zhangxueming@uniontech.com> on 2024/11/20.
//
#include "ImmuRestoreWidget.h"
#include "utils/Utils.h"
#include <DFontSizeManager>
#include <QHeaderView>
#include <DDialog>
#include <QStorageInfo>

const static int IMMU_SYS_BACKUP_BUTTON_ID = 0;
const static int IMMU_DATA_BACKUP_BUTTON_ID = 1;
const static int IMMU_SYS_CLONE_BUTTON_ID = 2;

const int TABLE_COL_NO = 0;             //table表：序号
const int TABLE_COL_NAME = 1;           //table表：备份文件名
const int TABLE_COL_TIME = 2;           //table表：时间
const int TABLE_COL_BACKUP_FILE = 3;    //table表：备份文件
const int TABLE_COL_USER = 4;           //table表：用户
const int TABLE_COL_STATE = 5;         //table表：备份文件状态
const int TABLE_COL_REMARK = 6;          //table表：备注
const int TABLE_COL_ACTION = 7;         //table表：操作
const int TABLE_COL_OPT_ID = 8;         //table表：操作ID

bool ImmuActionWidget::m_isRemoving = false;

static void deleteBackupInfo(BackupInfoList &backupList, const QString &operateId)
{
    if (backupList.isEmpty()) {
        return;
    }

    backupList.erase(std::remove_if(backupList.begin(), backupList.end(),
                                    [&] (const BackupInfo &b) -> bool {
                                        return b.operateID == operateId;
                                    }),
                     backupList.end());
}

void ImmuActionWidget::onThemeChange(Dtk::Gui::DGuiApplicationHelper::ColorType themeType)
{
    if (nullptr != m_deleteBtn) {
        if (Dtk::Gui::DGuiApplicationHelper::ColorType::DarkType == themeType) {
            m_deleteBtn->setIcon(QIcon::fromTheme(":/resources/icons/delete_dark.svg"));
        } else {
            m_deleteBtn->setIcon(QIcon::fromTheme(":/resources/icons/delete.svg"));
        }
    }
}

ImmuActionWidget::ImmuActionWidget(QWidget *parent)
        : QWidget(parent)
{
    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &ImmuActionWidget::onThemeChange);
    QHBoxLayout *layout = new QHBoxLayout;
    layout->setContentsMargins(0, 0, 0, 0);
    layout->setAlignment(Qt::AlignLeft);
    setLayout(layout);
    m_restoreBtn = new DPushButton;
    m_restoreBtn->setStyleSheet("QPushButton {"
                               "color: #0081FF;"
                               "border: none;"
                               "background-color: transparent;"
                               "image:url(:/resources/icons/other_restore.svg);"
                               "}");
    m_restoreBtn->setToolTip(tr("Restore"));
    m_deleteBtn = new DPushButton;
    m_deleteBtn->setToolTip(tr("Delete"));
    // 设置按钮背景透明
    QPalette palette = m_deleteBtn->palette();
    palette.setBrush(QPalette::Button, Qt::transparent);
    m_deleteBtn->setPalette(palette);
    m_deleteBtn->setAutoFillBackground(false);
    // 设置按钮无边框
    m_deleteBtn->setFlat(true);
    m_deleteBtn->setIconSize(QSize(16, 16));
    onThemeChange(m_guiHelper->themeType());
    layout->addWidget(m_restoreBtn);
    layout->addSpacing(5);
    layout->addWidget(m_deleteBtn);
    m_spinner = new DSpinner;
    m_spinner->setFixedSize(24, 24);
    m_spinner->setVisible(false);
    layout->addWidget(m_spinner);
    connect(m_restoreBtn, &QPushButton::clicked, this, &ImmuActionWidget::onRestore);
    connect(m_deleteBtn, &QPushButton::clicked, this, &ImmuActionWidget::onDelete);
}

void ImmuActionWidget::setBackupFileActionType(ImmuBackupFileActionType actionType)
{
    m_actionType = actionType;
}

int ImmuActionWidget::getBackupInfoOperateType()
{
    return m_backupInfo.operateType;
}

void ImmuActionWidget::setBackupInfo(const BackupInfo &backupInfo)
{
    m_backupInfo = backupInfo;
}

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

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

    m_commonAuthUtils->checkCommonUserAuthentication(type);
}

void ImmuActionWidget::doAdminAuthorityTask(bool result, int type)
{
    if (result) {
        AuthorityType authType = static_cast<AuthorityType>(type);
        if (AuthorityType::ImmuSystemRestore == authType) {
            DDialog dialog(this);
            dialog.setTitle(tr("Restore"));
            dialog.setMessage(tr("Your current system will be restored, and your data may be affected. Are you sure you want to restore your system?"));
            dialog.setIcon(QIcon::fromTheme("uos-recovery"));
            dialog.addButton(tr("Cancel", "button"));
            dialog.moveToCenter();

            int result = dialog.addButton(tr("Restore", "button"), true, DDialog::ButtonWarning);
            if (dialog.exec() != result) {
                return;
            }

            Q_EMIT immuSystemRestoreClicked(m_backupInfo);
            return;
        }

        if (AuthorityType::DeleteImmutableSystemBackup == authType || AuthorityType::DeleteSystemBackup == authType) {
            m_isRemoving = true;

            // 先修改状态，后发送信号，避免删除失败导致状态无法更正
            m_restoreBtn->setVisible(false);
            m_deleteBtn->setVisible(false);
            m_spinner->setVisible(true);
            m_spinner->start();

            Q_EMIT deleteBackupInfo(m_backupInfo);
            return;
        }
    }
}

void ImmuActionWidget::doCommonAuthorityTask(bool result, int type)
{
    if (result) {
        AuthorityType authType = static_cast<AuthorityType>(type);
        if (AuthorityType::DeleteDataBackup == authType) {
            m_isRemoving = true;

            // 先修改状态，后发送信号，避免删除失败导致状态无法更正
            m_deleteBtn->setVisible(false);
            m_spinner->setVisible(true);
            m_spinner->start();

            Q_EMIT deleteBackupInfo(m_backupInfo);
        } else if (AuthorityType::DataRestore == authType) {
            QString path = "/home";
            QStorageInfo storageInfo(path);
            qint64 availableSize = storageInfo.bytesAvailable();
            if ((m_backupInfo.size == 0 && availableSize <= 1 * GiB) || (m_backupInfo.size > 0 && availableSize < m_backupInfo.size)) {
                DDialog dialog(this);
                dialog.setTitle(tr("Data Restore"));
                QString tips = tr("Insufficient disk space on the device");
                QString device = storageInfo.device();
                QString errInfo = QString("%1 : %2").arg(tips).arg(device);
                dialog.setMessage(errInfo);
                dialog.setIcon(QIcon::fromTheme("dialog-warning"));
                dialog.moveToCenter();
                dialog.exec();
                return;
            }
            Q_EMIT immuDataRestoreClicked(m_backupInfo);
        }
    }
}

void ImmuActionWidget::onRestore()
{
    if (m_isRemoving) {
        return;
    }

    OperateType opType = static_cast<OperateType>(m_backupInfo.operateType);
    if (opType == OperateType::ImmutableSystemBackup) {
        return this->checkAdminAuthority(AuthorityType::ImmuSystemRestore);
    } else if (opType == OperateType::UserDataBackup) {
        return this->checkCommonAuthority(AuthorityType::DataRestore);
    }
}

void ImmuActionWidget::onDelete()
{
    if (m_isRemoving) {
        return;
    }

    DDialog dialog(this);
    QString msg = tr("Confirm deletion of backup files? This operation cannot be undone. Please proceed with caution. ");
    dialog.setMessage(msg);
    dialog.setIcon(QIcon::fromTheme("uos-recovery"));
    dialog.addButton(tr("Cancel", "button"));
    dialog.setFixedWidth(500);
    dialog.moveToCenter();

    int result = dialog.addButton(tr("OK", "button"), true, DDialog::ButtonWarning);
    if (dialog.exec() != result) {
        return;
    }

    OperateType opType = static_cast<OperateType>(m_backupInfo.operateType);
    if (opType == OperateType::SystemBackup) {
        return this->checkAdminAuthority(AuthorityType::DeleteSystemBackup);
    } else if (opType == OperateType::ImmutableSystemBackup) {
        return this->checkAdminAuthority(AuthorityType::DeleteImmutableSystemBackup);
    } else if (opType == OperateType::UserDataBackup) {
        return this->checkCommonAuthority(AuthorityType::DeleteDataBackup);
    } else if (opType == OperateType::GhostBackup) {
        m_isRemoving = true;

        // 先修改状态，后发送信号，避免删除失败导致状态无法更正
        m_deleteBtn->setVisible(false);
        m_spinner->setVisible(true);
        m_spinner->start();

        Q_EMIT deleteBackupInfo(m_backupInfo);
    }
}

void ImmuActionWidget::setDeleteBtnVisible(bool visible)
{
    if (m_deleteBtn != nullptr) {
        m_deleteBtn->setVisible(visible);
    }
}

void ImmuActionWidget::setRestoreBtnVisible(bool visible)
{
    if (m_restoreBtn != nullptr) {
        m_restoreBtn->setVisible(visible);
    }
}

void ImmuActionWidget::stopSpinner()
{
    if (m_spinner != nullptr) {
        m_spinner->stop();
    }
}

void ImmuActionWidget::setSpinnerVisible(bool visible)
{
    if (m_spinner != nullptr) {
        m_spinner->setVisible(visible);
    }
}

ImmuBackupFileDelegate::ImmuBackupFileDelegate(QObject *parent)
        : BaseItemDelegate(parent)
{

}

QWidget * ImmuBackupFileDelegate::createEditor(QWidget *widget,
                                           const QStyleOptionViewItem &styleOptionViewItem,
                                           const QModelIndex &index) const
{
    //todo 支持编辑备注
//    if (index.column() == TABLE_COL_REMARK) {
//        return new DLineEdit(widget);
//    }
    return nullptr;
}

void ImmuBackupFileDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    //todo 支持编辑备注
}

void ImmuBackupFileDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    //todo 支持编辑备注
}

DefaultEmptyRestoreWidget::DefaultEmptyRestoreWidget(DWidget *parent) : DWidget(parent)
{
    this->setAccessibleName("DefaultEmptyRestoreWidget");
    m_isCommunity = Utils::isCommunity();
    this->initUI();
    this->initLayout();
    updateTheme();
}

void DefaultEmptyRestoreWidget::initUI()
{
    m_backupFilesMgrLabel = new DLabel(this);
    m_backupFilesMgrLabel->setText(tr("Backup files"));
    m_backupFilesMgrLabel->setAccessibleName("DefaultEmptyRestoreWidget_BackupFiles");
    m_backupFilesMgrLabel->setFixedHeight(35);
    DFontSizeManager::instance()->bind(m_backupFilesMgrLabel, DFontSizeManager::T4);
    QFont font = m_backupFilesMgrLabel->font();
    font.setWeight(QFont::Bold);
    m_backupFilesMgrLabel->setFont(font);
    m_backupFilesMgrLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.85)));
    m_backupFilesMgrLabel->setPalette(titlePalette);

    m_newBackupBtn = new DPushButton(this);
    m_newBackupBtn->setAccessibleName("uos_DefaultEmptyRestoreWidget_newBackupButton");
    m_newBackupBtn->setText(tr("Create Backup"));
    m_newBackupBtn->setFixedWidth(200);
    DFontSizeManager::instance()->bind(m_newBackupBtn, DFontSizeManager::T6);
    QFont newBackupFont = m_newBackupBtn->font();
    newBackupFont.setWeight(QFont::Normal);
    m_newBackupBtn->setFont(newBackupFont);

    m_icon = new DLabel(this);
    m_lightIconPixmap = Utils::hidpiPixmap(":/resources/icons/v25/default_no_backup_files.png", QSize(174, 164));
    m_darkIconPixmap = Utils::hidpiPixmap(":/resources/icons/v25/default_no_backup_files_dark.png", QSize(174, 164));
    m_icon->setAccessibleName("DefaultEmptyRestoreWidget_NoBackupFilesIcon");

    m_text = new DLabel(this);
    m_text->setText(tr("No available backup files to restore"));
    m_text->setAlignment(Qt::AlignHCenter);
    m_text->setAccessibleName("DefaultEmptyRestoreWidget_NoBackupFilesToRestore");
    DFontSizeManager::instance()->bind(m_text, DFontSizeManager::T6);
    m_text->setForegroundRole(DPalette::PlaceholderText);


    connect(m_newBackupBtn, &DPushButton::clicked, this, &DefaultEmptyRestoreWidget::showBackupPage);
    connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged,
            this, [this]() {
                updateTheme();
            });
}

void DefaultEmptyRestoreWidget::initLayout()
{
    m_vMainLayout = new QVBoxLayout(this);
    m_vMainLayout->setContentsMargins(0, 4, 0, 0);
    auto titleLayout = new QHBoxLayout;
    titleLayout->addSpacing(12);
    titleLayout->addWidget(m_backupFilesMgrLabel, 0, Qt::AlignLeft);
    m_vMainLayout->addLayout(titleLayout);
    m_vMainLayout->addSpacing(110);
    m_vMainLayout->addWidget(m_icon);
    m_vMainLayout->setAlignment(m_icon, Qt::AlignHCenter);
    m_vMainLayout->addWidget(m_text);
    m_vMainLayout->setAlignment(m_text, Qt::AlignHCenter);
    m_vMainLayout->addSpacing(24);
    m_vMainLayout->addWidget(m_newBackupBtn, 0, Qt::AlignHCenter);
    //m_vMainLayout->addSpacing(184);
    m_vMainLayout->addStretch();
}

void DefaultEmptyRestoreWidget::updateTheme()
{
    if (DGuiApplicationHelper::instance()->themeType() == DGuiApplicationHelper::DarkType) {
        if (m_icon != nullptr) {
            m_icon->setPixmap(m_darkIconPixmap);
        }
    } else {
        if (m_icon != nullptr) {
            m_icon->setPixmap(m_lightIconPixmap);
        }
    }
}

void DefaultEmptyRestoreWidget::showBackupPage()
{
    Q_EMIT notifyShowBackupPage();
}

ImmuRestoreWidget::ImmuRestoreWidget(DWidget *parent) : DWidget(parent)
{
    m_isCommunity = Utils::isCommunity();
    this->initUI();
    this->initTableView();
    this->initLayout();
}

void ImmuRestoreWidget::initUI()
{
    m_backupFilesMgrLabel = new DLabel(this);
    m_backupFilesMgrLabel->setText(tr("Backup files"));
    m_backupFilesMgrLabel->setAccessibleName("BackupFileMgrDlg_BackupFiles");
    m_backupFilesMgrLabel->setFixedHeight(35);
    DFontSizeManager::instance()->bind(m_backupFilesMgrLabel, DFontSizeManager::T4);
    QFont font = m_backupFilesMgrLabel->font();
    font.setWeight(QFont::Bold);
    m_backupFilesMgrLabel->setFont(font);
    m_backupFilesMgrLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.85)));
    m_backupFilesMgrLabel->setPalette(titlePalette);

    m_newBackupBtn = new DPushButton(this);
    m_newBackupBtn->setIcon(QIcon::fromTheme(":/resources/icons/v25/add_backup.svg"));
    m_newBackupBtn->setAccessibleName("uos_ImmuRestoreWidget_newBackupButton");
    m_newBackupBtn->setText(tr("Create Backup"));
    m_newBackupBtn->setFixedSize(98, 34);

    m_buttonBox = new DButtonBox(this);
    m_systemBackupBtn = new DButtonBoxButton(tr("System Backup"));
    m_dataBackupBtn = new DButtonBoxButton(tr("Data Backup"));
    m_systemCloneBtn = new DButtonBoxButton(tr("System Clone"));
    m_systemBackupBtn->setAccessibleName("uos-recovery-gui-SystemBackup");
    m_dataBackupBtn->setAccessibleName("uos-recovery-gui-DataBackup");
    m_systemCloneBtn->setAccessibleName("uos-recovery-gui-SystemClone");
    m_buttonBox->setAccessibleName("uos-recovery-gui-FBRA-Box");
//    if (m_isCommunity) {
//        m_buttonBox->setButtonList({m_systemBackupBtn, m_dataBackupBtn}, true);
//    } else {
//        m_buttonBox->setButtonList({m_systemBackupBtn, m_dataBackupBtn, m_systemCloneBtn}, true);
//    }
    m_buttonBox->setButtonList({m_systemBackupBtn, m_dataBackupBtn, m_systemCloneBtn}, true);

    m_buttonBox->setId(m_systemBackupBtn, IMMU_SYS_BACKUP_BUTTON_ID);
    m_buttonBox->setId(m_dataBackupBtn, IMMU_DATA_BACKUP_BUTTON_ID);
  //  if (!m_isCommunity) {
        m_buttonBox->setId(m_systemCloneBtn, IMMU_SYS_CLONE_BUTTON_ID);
    //}

    m_tableView = new ImmuBaseTableView;
    m_tableView->setAccessibleName("BackupFileMgrDlg_tableView");
    m_model = new QStandardItemModel;
    m_tableView->setModel(m_model);
    auto itemDelegate = new ImmuBackupFileDelegate(this);
    m_tableView->setItemDelegate(itemDelegate);

    connect(m_newBackupBtn, &DPushButton::clicked, this, &ImmuRestoreWidget::showBackupPage);
    connect(m_buttonBox, &DButtonBox::buttonPressed, this, &ImmuRestoreWidget::onBackupFileBtnChange);
    m_buttonBox->button(IMMU_SYS_BACKUP_BUTTON_ID)->setChecked(true);

    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &ImmuRestoreWidget::onThemeChange);
}

void ImmuRestoreWidget::showFirstItem()
{
    m_buttonBox->button(IMMU_SYS_BACKUP_BUTTON_ID)->setChecked(true);
}

bool ImmuRestoreWidget::showRebootDialog(const QString &title, const QString &msg, const QString &iconName,
                       const QString &btnText)
{
    DDialog dialog(this);
    dialog.setTitle(title);
    dialog.setMessage(msg);
    dialog.setIcon(QIcon::fromTheme(iconName));
    dialog.moveToCenter();
    dialog.setCloseButtonVisible(false);

    int result = dialog.addButton(btnText, true, DDialog::ButtonWarning);
    if (dialog.exec() != result) {
        return false;
    }

    return true;
}

void ImmuRestoreWidget::initTableView()
{
    m_tableView->setFixedHeight(466); // 470
    //m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_tableView->setSortingEnabled(false);
    m_tableView->setFocusPolicy(Qt::NoFocus);
    m_tableView->setRowBackgroundDelta(10);

    //序号
    auto noItem = new QStandardItem(tr("No."));
    noItem->setTextAlignment(Qt::AlignVCenter);
    //备份文件名
    auto nameItem = new QStandardItem(tr("Name"));
    nameItem->setTextAlignment(Qt::AlignVCenter);

    // 备份文件
    auto backupFileItem = new QStandardItem(tr("Backup File"));
    backupFileItem->setTextAlignment(Qt::AlignVCenter);

    // 时间
    auto timeItem = new QStandardItem(tr("Time"));
    timeItem->setTextAlignment(Qt::AlignVCenter);

    // 用户
    auto userItem = new QStandardItem(tr("User"));
    userItem->setTextAlignment(Qt::AlignVCenter);
    //备份状态
    auto stateItem = new QStandardItem(tr("State"));
    stateItem->setTextAlignment(Qt::AlignVCenter);
    //备注
    auto remarkItem = new QStandardItem(tr("Note"));
    remarkItem->setTextAlignment(Qt::AlignVCenter);
    // 操作
    auto actionItem = new QStandardItem(tr("Action"));
    actionItem->setTextAlignment(Qt::AlignVCenter);
    //操作id
    auto optIdItem = new QStandardItem();
    optIdItem->setTextAlignment(Qt::AlignVCenter);

    m_model->setHorizontalHeaderItem(TABLE_COL_NO, noItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_NAME, nameItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_TIME, timeItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_BACKUP_FILE, backupFileItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_USER, userItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_STATE, stateItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_REMARK, remarkItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_ACTION, actionItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_OPT_ID, optIdItem);

    //m_tableView->header()->setSectionResizeMode(QHeaderView::ResizeToContents);
    m_tableView->setColumnWidth(TABLE_COL_NO, 20);
    m_tableView->setColumnWidth(TABLE_COL_OPT_ID, 5);
    m_tableView->setColumnWidth(TABLE_COL_TIME, 150);
    m_tableView->setColumnWidth(TABLE_COL_BACKUP_FILE, 180);
    m_tableView->setColumnWidth(TABLE_COL_USER, 130);
    m_tableView->setColumnWidth(TABLE_COL_REMARK, 160);
    m_tableView->setColumnWidth(TABLE_COL_ACTION, 30);

    //隐藏列
    m_tableView->hideColumn(TABLE_COL_NAME);
    m_tableView->hideColumn(TABLE_COL_STATE);
    m_tableView->hideColumn(TABLE_COL_OPT_ID);

    // 禁止拖动列宽
    QHeaderView * headerView = m_tableView->header();
    headerView->setSectionResizeMode(TABLE_COL_NO, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_NAME, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_TIME, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_BACKUP_FILE, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_USER, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_STATE, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_REMARK, QHeaderView::ResizeMode::Fixed);
    headerView->setSectionResizeMode(TABLE_COL_ACTION, QHeaderView::ResizeMode::Fixed);
}

void ImmuRestoreWidget::initLayout()
{
    m_mainVLayout = new QVBoxLayout(this);
   // m_mainVLayout->setSpacing(10);
    m_mainVLayout->setContentsMargins(12, 8, 10, 70);

    QHBoxLayout *backupFileHLayout = new QHBoxLayout();
    backupFileHLayout->addWidget(m_backupFilesMgrLabel, 0, Qt::AlignLeft);
    backupFileHLayout->addWidget(m_newBackupBtn, 0, Qt::AlignRight);

    m_mainVLayout->addLayout(backupFileHLayout);
    m_mainVLayout->addSpacing(10);
    m_mainVLayout->addWidget(m_buttonBox, 0, Qt::AlignLeft);
    m_mainVLayout->addSpacing(10);
    m_mainVLayout->addWidget(m_tableView);
    m_mainVLayout->addStretch();
}

void ImmuRestoreWidget::showBackupPage()
{
    Q_EMIT notifyShowBackupPage();
}

void ImmuRestoreWidget::setSystemBackupInfoData(const BackupInfoList &backupInfos)
{
    m_allSystemBackupInfo = backupInfos;
}

void ImmuRestoreWidget::setDataBackupInfoData(const BackupInfoList &backupInfos)
{
    m_allDataBackupInfo = backupInfos;
}

void ImmuRestoreWidget::setGhostInfoData(const BackupInfoList &backupInfos)
{
    m_allGhostBackupInfo = backupInfos;
}

void ImmuRestoreWidget::onBackupFileBtnChange(QAbstractButton *button)
{
    int backupTypeIndex = m_buttonBox->id(button);
    QString curUserName = Utils::getUserName();
    bool isAdmin = Utils::isAdminUser(curUserName);

    if (IMMU_SYS_BACKUP_BUTTON_ID == backupTypeIndex) {
        if (isAdmin) {
            this->setData(m_allSystemBackupInfo);
        } else {
            BackupInfoList emptyList;
            this->setData(emptyList);
        }
    } else if (IMMU_DATA_BACKUP_BUTTON_ID == backupTypeIndex) {
        this->setData(m_allDataBackupInfo);
    } else if (IMMU_SYS_CLONE_BUTTON_ID == backupTypeIndex) {
        this->setData(m_allGhostBackupInfo);
    }
}

void ImmuRestoreWidget::onThemeChange(Dtk::Gui::DGuiApplicationHelper::ColorType themeType)
{
    if (themeType == Dtk::Gui::DGuiApplicationHelper::LightType) {
        m_newBackupBtn->setIcon(QIcon::fromTheme(":/resources/icons/v25/add_backup.svg"));
    } else {
        m_newBackupBtn->setIcon(QIcon::fromTheme(":/resources/icons/v25/add_backup_dark.svg"));
    }
}

void ImmuRestoreWidget::setData(BackupInfoList &backupInfos)
{
    m_model->removeRows(0, m_model->rowCount());
    m_allBackupInfo.clear();

    std::sort(backupInfos.begin(), backupInfos.end());
    auto iter = backupInfos.rbegin();
    int i = 1;
    for (; iter != backupInfos.rend(); ++iter, ++i) {
        m_allBackupInfo[iter->operateID] = *iter;
        int currentRow = m_model->rowCount();
        auto seqItem = new QStandardItem(QString("%1").arg(i));
        seqItem->setTextAlignment(Qt::AlignCenter);
        m_model->setItem(currentRow, TABLE_COL_NO, seqItem);
        m_model->setItem(currentRow, TABLE_COL_NAME, new QStandardItem(iter->operateID));
        QDateTime time = QDateTime::fromSecsSinceEpoch(iter->startTime); //时间戳-秒级
        if (OperateType::GhostBackup == static_cast<OperateType>(iter->operateType)) {
            time = QDateTime::fromMSecsSinceEpoch(iter->startTime);
        }
        QString startTime = time.toString("yyyy-MM-dd HH:mm:ss");
        auto timeItem = new QStandardItem(startTime);
        m_model->setItem(currentRow, TABLE_COL_TIME, timeItem);

        auto backupFileItem = new QStandardItem(iter->systemVersion);
        m_model->setItem(currentRow, TABLE_COL_BACKUP_FILE, backupFileItem);
        m_model->setItem(currentRow, TABLE_COL_USER, new QStandardItem(iter->username));
        m_model->setItem(currentRow, TABLE_COL_STATE, new QStandardItem(QString("%1").arg(iter->status)));
        m_model->setItem(currentRow, TABLE_COL_REMARK, new QStandardItem(iter->remark));

        auto actionItem = new QStandardItem();
        actionItem->setAccessibleText(iter->operateID + "_deleteWidget");
        m_model->setItem(currentRow, TABLE_COL_ACTION, actionItem);
        auto actionWidget = new ImmuActionWidget;
        actionWidget->setBackupInfo(*iter);
        if (static_cast<int>(OperateType::GhostBackup) == iter->operateType) {
            actionWidget->setRestoreBtnVisible(false);
        }
        m_tableView->setIndexWidget(m_model->index(currentRow, TABLE_COL_ACTION), actionWidget);
        connect(actionWidget, &ImmuActionWidget::immuSystemRestoreClicked,
                this, &ImmuRestoreWidget::notifyImmuSystemRestoreClicked);
        connect(actionWidget, &ImmuActionWidget::immuDataRestoreClicked,
                this, &ImmuRestoreWidget::notifyImmuDataRestoreClicked);
        connect(actionWidget, &ImmuActionWidget::deleteBackupInfo, this, &ImmuRestoreWidget::notifyDeleteBackupInfo);
        //操作id
        m_model->setItem(currentRow, TABLE_COL_OPT_ID, new QStandardItem(iter->operateID));
    }
}

void ImmuRestoreWidget::setDeleteWidgetStatus(bool deleteBtnVisible, bool spinnerVisible, const QString &operateId)
{
    auto items = m_model->findItems(operateId, Qt::MatchExactly, TABLE_COL_OPT_ID);
    for (auto &item : items) {
        int currentRow = m_model->indexFromItem(item).row();
        qInfo()<<Q_FUNC_INFO<<"currentRow = "<<currentRow<<", operateId = "<<operateId;
        QWidget *curWidget = m_tableView->indexWidget(m_model->index(currentRow, TABLE_COL_ACTION));
        ImmuActionWidget *curActionWidget = dynamic_cast<ImmuActionWidget *>(curWidget);
        if (curActionWidget != nullptr) {
            curActionWidget->stopSpinner();
            curActionWidget->setSpinnerVisible(spinnerVisible);
            curActionWidget->setDeleteBtnVisible(deleteBtnVisible);
            if (static_cast<int>(OperateType::GhostBackup) != curActionWidget->getBackupInfoOperateType()) {
                curActionWidget->setRestoreBtnVisible(deleteBtnVisible);
            }
        }
        ImmuActionWidget::m_isRemoving = false;
    }
}

void ImmuRestoreWidget::showErrorDlg(const QString &msg)
{
    DDialog dialog(this);
    dialog.setMessage(msg);
    dialog.setIcon(QIcon::fromTheme("dialog-warning"));
    dialog.setAccessibleName("ImmuRestoreWidget_ErrorDialog");
    QRect rect = geometry();
    dialog.move(rect.center());
    dialog.moveToCenter();
    dialog.exec();
}

void ImmuRestoreWidget::removeBackupInfo(const QString &operateId)
{
    m_allBackupInfo.remove(operateId);
    auto items = m_model->findItems(operateId, Qt::MatchExactly, TABLE_COL_OPT_ID);
    for (auto &item : items) {
        m_model->removeRow(m_model->indexFromItem(item).row());
        ImmuActionWidget::m_isRemoving = false;
    }

    int curIndex = m_buttonBox->checkedId();
    if (IMMU_SYS_BACKUP_BUTTON_ID == curIndex) {
        deleteBackupInfo(m_allSystemBackupInfo, operateId);
    } else if (IMMU_DATA_BACKUP_BUTTON_ID == curIndex) {
        deleteBackupInfo(m_allDataBackupInfo, operateId);
    } else if (IMMU_SYS_CLONE_BUTTON_ID == curIndex) {
        deleteBackupInfo(m_allGhostBackupInfo, operateId);
    }
}