//
// Created by uos on 2022/4/1.
//
#include "SystemRestoreWidget.h"
#include "common/BaseItemDelegate.h"
#include <QVBoxLayout>
#include <DFontSizeManager>
#include <QJsonValue>
#include <DRadioButton>
#include <QSizePolicy>
#include <QDateTime>
#include <QHeaderView>
#include <QScrollBar>
#include <QDebug>

const int TABLEVIEW_ROW_HEIGHT = 40;    //tableview 每列高度
const int TABLE_COL_CHOOSE = 0;         //table表 第0列：选择
const int TABLE_COL_NO = 1;             // table表 第1列：序号
const int TABLE_COL_BACKUP_FILE = 2;    // table表 第2列：备份文件
const int TABLE_COL_TIME = 3;           // table表 第3列：时间
const int TABLE_COL_TYPE = 4;           // table表 第4列：类别
const int TABLE_COL_NOTE = 5;           // table表 第5列：备注
const int TABLE_COL_OPT_ID = 6;         // table表 第6列：操作id

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

    // 主题变换
    m_guiHelper = Dtk::Gui::DGuiApplicationHelper::instance();
    connect(m_guiHelper, &Dtk::Gui::DGuiApplicationHelper::themeTypeChanged, this, &SystemRestoreWidget::onThemeChange);
    // 初始化UI
    initUI();
    onThemeChange();
    connect(m_tableView, &DTableView::pressed, this, &SystemRestoreWidget::onBackupFileChanged);
}

void SystemRestoreWidget::initUI()
{
    QVBoxLayout *verticalLayout = new QVBoxLayout(this);
    verticalLayout->setContentsMargins(10, 20, 10, 10);
    verticalLayout->setAlignment(Qt::AlignHCenter);

    DLabel *title = new DLabel;
    title->setText(tr("System Restore"));
    title->setAccessibleName("uosRestore_SystemRestoreTitle");
    title->setAlignment(Qt::AlignCenter);
    DFontSizeManager::instance()->bind(title, DFontSizeManager::T4);
    QFont font = title->font();
    font.setWeight(QFont::Bold);
    title->setFont(font);
    verticalLayout->addWidget(title);

    verticalLayout->addSpacing(4);
    auto subTitle = new DLabel;
    subTitle->setAlignment(Qt::AlignCenter);
    subTitle->setText(tr("Select a backup file and restore your system from it."));
    subTitle->setAccessibleName("uosRestore_SystemRestoreSubTitle");
    verticalLayout->addWidget(subTitle);

    m_tableView = new BaseTableView;
    m_tableView->setAccessibleName("uosRestore_SystemRestoreTableView");
    m_model = new QStandardItemModel;
    m_tableView->setModel(m_model);
    auto itemDelegate = new BaseItemDelegate(this);
    m_tableView->setItemDelegate(itemDelegate);
    initTableView();
    verticalLayout->addWidget(m_tableView);
    verticalLayout->addStretch();

    QHBoxLayout *loadingHboxLayout = new QHBoxLayout;
    m_spinner = new DSpinner(this);
    m_spinner->setAccessibleName("uos_SystemRestoreWidget_DSpinner");
    m_spinner->setFocusPolicy(Qt::NoFocus);
    m_spinner->setFixedSize(16,16);
    m_spinner->hide();

    loadingHboxLayout->addStretch();
    loadingHboxLayout->addWidget(m_spinner);
    loadingHboxLayout->addSpacing(10);

    m_tips= new DLabel;
    m_tips->setAccessibleName("uos_SystemRestoreWidget_Tips");
    m_tips->setAlignment(Qt::AlignCenter);
    m_tips->setFocusPolicy(Qt::NoFocus);
    // m_tips->setStyleSheet("QLabel {"
    //                       "color: #000000;"
    //                       "}");
    loadingHboxLayout->addWidget(m_tips);
    loadingHboxLayout->addStretch();

    verticalLayout->addLayout(loadingHboxLayout);
    verticalLayout->addSpacing(10);

    auto warning = new DLabel;
    warning->setText(tr("Attention: Your current system will be restored, which may affect your data. Please proceed carefully!"));
    warning->setAccessibleName("uosRestore_SystemRestoreWarningLabel");
    warning->setAlignment(Qt::AlignHCenter);
    warning->setWordWrap(true);
    warning->setStyleSheet("QLabel {"
                             "font-family: SourceHanSansSC, SourceHanSansSC-Medium;"
                             "font-size: 14px;"
                             "font-weight: 500;"
                             "color: #ff5736;"
                             "}");
    verticalLayout->addWidget(warning);
    verticalLayout->addSpacing(10);

    auto hLayout = new QHBoxLayout;
    hLayout->setAlignment(Qt::AlignHCenter);
    m_cancelBtn = new DPushButton;
    m_cancelBtn->setText(tr("Cancel", "button"));
    m_cancelBtn->setAccessibleName("uosRestore_SystemRestoreCancel");
    m_cancelBtn->setFixedSize(140, 36);
    hLayout->addWidget(m_cancelBtn);
    hLayout->addSpacing(10);

    m_okBtn = new DSuggestButton;
    m_okBtn->setEnabled(false);
    m_okBtn->setText(tr("Start Restore"));
    m_okBtn->setAccessibleName("uosRestore_SystemRestoreRestore");
    m_okBtn->setFixedSize(140, 36);
    hLayout->addWidget(m_okBtn);
    verticalLayout->addLayout(hLayout);

    connect(m_cancelBtn, &DPushButton::clicked, this, &SystemRestoreWidget::cancel);
    connect(m_okBtn, &DPushButton::clicked, [this] {
        auto itFind = m_allBackupInfo.find(m_backupFileOptUUID);
        if (itFind != m_allBackupInfo.end()) {
            Q_EMIT start(itFind.value());
        }
    });
}

void SystemRestoreWidget::initTableView()
{
    m_tableView->setFixedHeight(304);

    //m_tableView->header()->setDefaultSectionSize(TABLEVIEW_ROW_HEIGHT);
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_tableView->setSelectionMode(QAbstractItemView::NoSelection);
    m_tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_tableView->setFrameShape(QTableView::NoFrame);
    m_tableView->setSortingEnabled(false);
    m_tableView->setFocusPolicy(Qt::NoFocus);

    //选择
    auto chooseItem = new QStandardItem();
    chooseItem->setTextAlignment(Qt::AlignVCenter);

    // 序号
    auto numItem = new QStandardItem(tr("No."));
    numItem->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 typeItem = new QStandardItem(tr("Type"));
    typeItem->setTextAlignment(Qt::AlignVCenter);

    // 备注
    auto noteItem = new QStandardItem(tr("Note"));
    noteItem->setTextAlignment(Qt::AlignVCenter);

    //操作id
    auto optIdItem = new QStandardItem();

    m_model->setHorizontalHeaderItem(TABLE_COL_CHOOSE, chooseItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_NO, numItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_BACKUP_FILE, backupFileItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_TIME, timeItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_TYPE, typeItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_NOTE, noteItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_OPT_ID, optIdItem);

    m_tableView->setFixedHeight(DEFAULT_ROW_HEIGHT * 8);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_CHOOSE, QHeaderView::ResizeToContents);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_NO, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_BACKUP_FILE, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_TIME, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_TYPE, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_NOTE, QHeaderView::Stretch);
    m_tableView->setColumnWidth(TABLE_COL_CHOOSE, 3);
    m_tableView->setColumnWidth(TABLE_COL_NO, 60);
    m_tableView->setColumnWidth(TABLE_COL_BACKUP_FILE, 180);
    m_tableView->setColumnWidth(TABLE_COL_TIME, 150);
    m_tableView->setColumnWidth(TABLE_COL_TYPE, 130);
    m_tableView->setColumnWidth(TABLE_COL_NOTE, 230);
    m_tableView->setColumnWidth(TABLE_COL_OPT_ID, 5);


    //隐藏列
    m_tableView->header()->setSectionHidden(TABLE_COL_OPT_ID, true);

    m_tableView->setRowBackgroundDelta(m_tableView->header()->sectionSize(TABLE_COL_CHOOSE));
    m_tableView->horizontalScrollBar()->setEnabled(false);
    m_tableView->setDragEnabled(false);
    m_tableView->header()->setSectionsMovable(false);
    m_tableView->header()->setSectionResizeMode(QHeaderView::ResizeMode::Fixed); //禁止标题列拖动
}

void SystemRestoreWidget::setData(BackupInfoList &backupInfo)
{
    m_model->removeRows(0, m_model->rowCount());
    m_allBackupInfo.clear();
    qDeleteAll(m_backgroundLst);
    m_backgroundLst.clear();
    m_okBtn->setEnabled(false);
    m_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    std::sort(backupInfo.begin(), backupInfo.end());
    int num = 0;
    auto iter = backupInfo.rbegin();
    for (; iter != backupInfo.rend(); ++iter) {
        if (static_cast<int>(RecoveryType::OSTree) == iter->recoveryType && CommitType::InstallerCommit == iter->submissionType) {
            continue; // 初始化还原的备份文件只在初始化还原功能入口里
        }

        m_allBackupInfo[iter->operateID] = *iter;
        int currentRow = m_model->rowCount();
        auto chooseItem = new QStandardItem();
        m_model->setItem(currentRow, TABLE_COL_CHOOSE, chooseItem);

        ++num;
        auto numItem = new QStandardItem(QString("%1").arg(num));
        m_model->setItem(currentRow, TABLE_COL_NO, numItem);

        auto backupFileItem = new QStandardItem(QString("%1").arg(iter->systemVersion));
        m_model->setItem(currentRow, TABLE_COL_BACKUP_FILE, backupFileItem);

        auto time = QDateTime::fromSecsSinceEpoch(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 typeItem = new QStandardItem();
        QString opType = "";
        OperateType operateType = static_cast<OperateType> (iter->operateType);
        switch (operateType) {
            case OperateType::SystemBackup:
            case OperateType::ImmutableSystemBackup: {
                opType = tr("System backup");
                break;
            }
            case OperateType::AutoBackup: {
                opType = tr("Auto backup");
                break;
            }
            default:
                opType = tr("Unknown operation");
                break;
        }

        typeItem->setText(opType);
        m_model->setItem(currentRow, TABLE_COL_TYPE, typeItem);

        auto remarkItem = new QStandardItem(QString("%1").arg(iter->remark));
        m_model->setItem(currentRow, TABLE_COL_NOTE, remarkItem);

        //操作id
        auto optIdItem = new QStandardItem(iter->operateID);
        m_model->setItem(currentRow, TABLE_COL_OPT_ID, optIdItem);

        //第0列

        DRadioButton *widget0 = new DRadioButton(m_tableView);
        widget0->setFocusPolicy(Qt::NoFocus);
        m_tableView->setIndexWidget(chooseItem->index(), widget0);

        connect(widget0, &DRadioButton::clicked, this, &SystemRestoreWidget::onRadioClicked);
    }
}

void SystemRestoreWidget::onThemeChange()
{

}

void SystemRestoreWidget::onBackupFileChanged(const QModelIndex &index)
{
    auto currItem = m_model->itemFromIndex(index);
    if (currItem == nullptr) {
        qCritical() << "Select backup file failed, currItem is null";
        return;
    }
    m_backupFileOptUUID = m_model->itemFromIndex(index.siblingAtColumn(TABLE_COL_OPT_ID))->text();
    if (!m_backupFileOptUUID.isEmpty()) {
        m_okBtn->setEnabled(true);
    }
//    qDebug() << m_backupFileOptUUID;
    DRadioButton *widget = dynamic_cast<DRadioButton *>(m_tableView->indexWidget(m_model->index(index.row(), TABLE_COL_CHOOSE)));
    widget->setChecked(true);
}

void SystemRestoreWidget::onRadioClicked(bool checked)
{
    if (checked) {
        int count = m_model->rowCount();
        for (int i = 0; i < count; ++i) {
            DRadioButton *widget = dynamic_cast<DRadioButton *>(m_tableView->indexWidget(m_model->index(i, TABLE_COL_CHOOSE)));
            if (widget == sender()) {
                onBackupFileChanged(m_model->index(i , TABLE_COL_CHOOSE));
                break;
            }
        }
    } else {
        m_okBtn->setEnabled(false);
    }
}

void SystemRestoreWidget::startSpinner()
{
    if (m_spinner != nullptr) {
        m_spinner->show();
        m_spinner->start();
    }

    if (m_cancelBtn != nullptr) {
        m_cancelBtn->setDisabled(true);
    }

    if (m_okBtn != nullptr) {
        m_okBtn->setDisabled(true);
    }
}

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

    if (m_cancelBtn != nullptr) {
        m_cancelBtn->setDisabled(false);
    }

    if (m_okBtn != nullptr) {
        m_okBtn->setDisabled(false);
    }
}

void SystemRestoreWidget::setTips(const QString &tips)
{
    if (m_tips != nullptr) {
        m_tips->setText(tips);
    }
}

void SystemRestoreWidget::setTipsStyleSheet(const QString &styleSheet)
{
    if (m_tips != nullptr) {
        m_tips->setStyleSheet(styleSheet);
    }
}
