//
// Created by 张雪明 <zhangxueming@uniontech.com> on 2024/11/19.
//
#include "ImmuBackupWidget.h"
#include "common/ItemFrame.h"
#include "ImmuBackupFrame.h"
#include "utils/Utils.h"
#include "utils/Device.h"
#include <QVBoxLayout>
#include <QScrollBar>
#include <DDialog>

enum OptBackupType {
    SystemBackup = 0, //系统备份
    UserDataBackup,    //数据备份
    SystemClone
};

const int ITEM_FRAME_HEIGHT = 218;
const int ITEM_FRAME_WIDTH = 218;
const int ITEM_FRAME_HEIGHT_VERTICAL_LAYOUT = 85;
const int ITEM_FRAME_WIDTH_VERTICAL_LAYOUT = 600;

ImmuBackupWidget::ImmuBackupWidget(DWidget *parent) : DWidget(parent)
{
    this->setAccessibleName("immuBackupWidget");

    // 主题变换
    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &ImmuBackupWidget::onThemeChange);
    //m_isCommunity = Utils::isCommunity();
    // 初始化UI
    initUI();
}

void ImmuBackupWidget::initUI()
{
    int uiLayout = UI::UI_LAYOUT_BACKUP_HORIZONTAL;
    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->setContentsMargins(0, 8, 0, 10);

    m_title = new DLabel(this);
    m_title->setText(tr("Choose a backup way"));
    m_title->setAccessibleName("uosBackup_ChooseBackupWay");
    m_title->setAlignment(Qt::AlignLeft);
    m_title->setFixedHeight(35);
    DFontSizeManager::instance()->bind(m_title, DFontSizeManager::T4);
    QFont font = m_title->font();
    font.setWeight(QFont::Bold);
    m_title->setFont(font);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.85)));
    m_title->setPalette(titlePalette);

    auto titleLayout = new QHBoxLayout;
    titleLayout->setContentsMargins(12, 0, 0, 0);
   // titleLayout->addSpacing(10);
    titleLayout->addWidget(m_title);
    verticalLayout->addLayout(titleLayout);
    //verticalLayout->addWidget(m_title, 0, Qt::AlignLeft);

    m_backupView = new DListView(this);
    m_model = new QStandardItemModel(m_backupView);
    m_backupView->setModel(m_model);
    m_backupView->setAccessibleName("uosBackup_BackupListView");

    verticalLayout->addSpacing(90);
    m_backupView->setFixedSize(815, 600);
    m_backupView->setContentsMargins(0, 0, 0, 0);
    //verticalLayout->addWidget(m_backupView, 0, Qt::AlignLeft);

    auto viewLayout = new QHBoxLayout;
    viewLayout->setContentsMargins(-90, 0, 0, 0);
    viewLayout->addWidget(m_backupView);
    verticalLayout->addLayout(viewLayout);

    m_backupView->setFrameShape(QFrame::Shape::NoFrame);
    // 不能编辑触发
    m_backupView->setEditTriggers(QListView::NoEditTriggers);
    // 不可以拖拽
    m_backupView->setDragEnabled(false);
    m_backupView->clearSelection();
    m_backupView->clearFocus();
    m_backupView->clearMask();
    m_backupView->setSelectionMode(QAbstractItemView::NoSelection);

    verticalLayout->addStretch();
    m_nextBtn = new DPushButton;
    m_nextBtn->setText(tr("Next"));
    m_nextBtn->setAccessibleName("uosBackup_Next");
    m_nextBtn->setFixedSize(200, 36);
    m_nextBtn->setEnabled(false);

    QHBoxLayout *hBoxLayout = new QHBoxLayout;
    this->uiHorizontalLayout();
    hBoxLayout->setContentsMargins(13, 0, 13, 0);
    hBoxLayout->addWidget(m_nextBtn, Qt::AlignHCenter);

    verticalLayout->addLayout(hBoxLayout);

    // 按钮  中间标题
    QStringList titles = {
            tr("System Backup"),
            tr("Data Backup")
    };
    m_iconList << ":/resources/icons/v25/system_backup.png"
        << ":/resources/icons/v25/user_data_backup.png";

    QStringList description = {
            tr("Back up the partitions and directories that store system files, to resist system breakdown"),
            tr("Specify files and directories to back up, so as to avoid data loss or damage")
    };

    if (!m_isCommunity) {
        titles.append(tr("System Clone"));
        m_iconList << ":/resources/icons/v25/system_clone.png";
        description << tr("One click clone the system and data, and can be installed to other device");
    }

    Q_ASSERT(titles.size() == m_iconList.size());

    for (int i = 0; i < titles.size(); i++) {
        auto *item = new QStandardItem;
        if (titles.at(i) == tr("System Backup")) {
            item->setAccessibleText("uos_SystemBackup");
        } else if (titles.at(i) == tr("Data Backup")) {
            item->setAccessibleText("uos_DataBackup");
        }
        m_model->appendRow(item);
        ImmuBackupFrame *itemFrame = new ImmuBackupFrame(titles.at(i), description.at(i), m_iconList.at(i), m_backupView);
        itemFrame->showDescription(true);
        itemFrame->setLayoutStype(uiLayout);
        itemFrame->setBackgroundRole(DPalette::NoType);
        // itemFrame->setFrameShape(QFrame::StyledPanel);
        itemFrame->setLineWidth(0);
        if (UI::UI_LAYOUT_BACKUP_HORIZONTAL == uiLayout) {
            itemFrame->setFixedSize(ITEM_FRAME_WIDTH, ITEM_FRAME_HEIGHT);
            itemFrame->setIconPixmap(m_iconList.at(i), QSize(122, 122));
        } else if (UI::UI_LAYOUT_BACKUP_VERTICAL == uiLayout) {
            itemFrame->setFixedSize(ITEM_FRAME_WIDTH_VERTICAL_LAYOUT, ITEM_FRAME_HEIGHT_VERTICAL_LAYOUT);
            itemFrame->setIconPixmap(m_iconList.at(i), QSize(56, 56));
        }
        itemFrame->initLayout();
        m_backupView->setIndexWidget(m_model->index(i, 0), itemFrame);
        connect(itemFrame, &ImmuBackupFrame::clicked, this, &ImmuBackupWidget::onItemChanged);
    }

    connect(m_nextBtn, &QPushButton::clicked, [=] {
        auto index = m_backupView->currentIndex();
        if (!index.isValid()) {
            return;
        }
        switch (static_cast<OptBackupType>(index.row())) {
            case SystemBackup:
                Q_EMIT notifySystemBackup();
                break;
            case UserDataBackup: {
                if (-1 == m_userDataSyncType) {
                    QString msg = tr("Data backup is not supported in the current environment.");
                    this->showNotSupportDlg(msg);
                    return;
                }
                Q_EMIT notifyDataBackup();
                break;
            }
            case SystemClone: {
                this->systemCloneItemClicked();
                break;
            }
            default:
                break;
        }
    });
}

void ImmuBackupWidget::uiHorizontalLayout()
{
    m_backupView->setResizeMode(QListView::Adjust);
    m_backupView->setViewMode(QListView::IconMode);
    m_backupView->setViewportMargins(QMargins(0, 0, 0, 0));

    m_backupView->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    m_backupView->setSpacing(40);

    // 每个对象大小
    m_backupView->setItemSize(QSize(ITEM_FRAME_WIDTH, ITEM_FRAME_HEIGHT));

    // 设置其他属性
    m_backupView->setTextElideMode(Qt::ElideRight);
    m_backupView->setBackgroundType(DStyledItemDelegate::RoundedBackground);
}

void ImmuBackupWidget::uiVerticalLayout()
{
    m_backupView->setResizeMode(QListView::Adjust);
    m_backupView->setViewMode(QListView::IconMode);
    m_backupView->setViewportMargins(QMargins(0, 0, 0, 0));

    m_backupView->verticalScrollBar()->setEnabled(false);
    m_backupView->horizontalScrollBar()->setEnabled(false);
    m_backupView->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    m_backupView->setSpacing(16);

    // 每个对象大小
    m_backupView->setItemSize(QSize(ITEM_FRAME_WIDTH_VERTICAL_LAYOUT, ITEM_FRAME_HEIGHT_VERTICAL_LAYOUT));

    // 设置其他属性
    m_backupView->setTextElideMode(Qt::ElideRight);
    m_backupView->setBackgroundType(DStyledItemDelegate::RoundedBackground);
}

void ImmuBackupWidget::onThemeChange(Dtk::Gui::DGuiApplicationHelper::ColorType themeType)
{
}

void ImmuBackupWidget::onItemChanged(bool checked)
{
    if (checked) {
        auto *itemFrame = dynamic_cast<ImmuBackupFrame *>(sender());
        int rowCount = m_model->rowCount();
        for (int i = 0; i < rowCount; ++i) {
            auto item = dynamic_cast<ImmuBackupFrame *>(m_backupView->indexWidget(m_model->index(i, 0)));
            item->setCheckState(itemFrame == item);
            item->setBackgroundRole(itemFrame == item ? DPalette::ObviousBackground : DPalette::NoType);
            item->setLineWidth(itemFrame == item ? 1 : 0);
        }
        m_nextBtn->setEnabled(checked);
    }
}

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

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

void ImmuBackupWidget::setImmutable(bool isImmutable)
{
    m_isImmutable = isImmutable;
}

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

void ImmuBackupWidget::systemCloneItemClicked()
{
    static QString osEditionType = Utils::getOSEditionType();
    QString encryptMsg = tr("Your system contains encrypted partition, system clone is not supported.");
    QString lvmMsg = tr("System clone is not supported in the current environment.");
    QString notFullInstallMsg = tr("System clone is not supported in the current environment.");

    QString fstabFile = "/etc/fstab";
    QStringList sysMountPointList;
    bool isFullInstall = false;
    if (!m_isImmutable) {
        isFullInstall = Device::isFullDiskInstall(fstabFile, sysMountPointList);
    }
    if ((-1 == m_userDataSyncType) || (!m_isImmutable && !isFullInstall)) {
        QString msg = tr("System clone is not supported in the current environment.");
        this->showNotSupportDlg(msg);
        return;
    }

    // if ("Community" == osEditionType) {
    //     this->showNotSupportDlg(lvmMsg);
    //     return;
    // }

    if (m_isEncrypted) {
        this->showNotSupportDlg(encryptMsg);
        return;
    }

    if (m_isLVMOnly) {
        this->showNotSupportDlg(lvmMsg);
        return;
    }

    Q_EMIT notifySystemClone();
}

void ImmuBackupWidget::showNotSupportDlg(const QString &msg)
{
    DDialog dlg(this);
    dlg.setMessage(msg);
    dlg.setIcon(QIcon::fromTheme("dialog-warning"));
    QRect rect = geometry();
    dlg.move(rect.center());
    dlg.moveToCenter();

    dlg.exec();
    return;
}