//
// Created by uos on 2022/4/28.
//

#include "UserDataRestoreWidget.h"
#include "common/BaseItemDelegate.h"
#include <QVBoxLayout>
#include <DFontSizeManager>
#include <QHeaderView>
#include <QDateTime>
#include <DRadioButton>
#include <QScrollBar>
#include <QDebug>
#include "utils/Utils.h"

const int TABLEVIEW_ROW_HEIGHT = 40;    //tableview 每列高度
const int TABLE_COL_CHOOSE = 0;         //table表 第0列：选择
const int TABLE_COL_TIME = 1;           //table表 第1列：时间
const int TABLE_COL_TYPE = 2;           //table表 第2列：类型
const int TABLE_COL_USER = 3;           //table表 第3列：用户
const int TABLE_COL_REMARK = 4;         //table表 第4列：备注
const int TABLE_COL_OPT_ID = 5;         //table表 第5列：操作id

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

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

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

    DLabel *title = new DLabel;
    title->setText(tr("Data Restore"));
    title->setAccessibleName("uosDataRestore_DataRestoreTitle");
    title->setAlignment(Qt::AlignCenter);
    DFontSizeManager::instance()->bind(title, DFontSizeManager::T3);
    QFont font = title->font();
    font.setWeight(QFont::DemiBold);
    title->setFont(font);
    QPalette titlePalette;
    titlePalette.setColor(QPalette::BrightText, QColor(qRgb(0,26,46)));
    title->setPalette(titlePalette);
    verticalLayout->addWidget(title);

    verticalLayout->addSpacing(4);
    auto subTitle = new DLabel;
    subTitle->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    subTitle->setText(tr("Select a backup file and restore your data from it."));
    subTitle->setAccessibleName("uosDataRestore_DataRestoreSubTitle");
    QFont subTitleFont = subTitle->font();
    subTitleFont.setPixelSize(14);
    subTitleFont.setWeight(QFont::DemiBold);
    subTitle->setFont(subTitleFont);
    DFontSizeManager::instance()->bind(subTitle, DFontSizeManager::T6);
    QPalette subTitlePalette;
    subTitlePalette.setColor(QPalette::BrightText, QColor(qRgba(0,0,0,0.85)));
    subTitle->setPalette(subTitlePalette);
    verticalLayout->addWidget(subTitle);
    verticalLayout->addSpacing(10);

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

    m_tips = new DLabel;
    m_tips->setAlignment(Qt::AlignHCenter);
    m_tips->setWordWrap(true);
    m_tips->hide();
    m_tips->setAccessibleName("uosDataRestore_tipsLabel");
    verticalLayout->addWidget(m_tips);
    verticalLayout->addSpacing(10);

    auto warning = new DLabel;
    warning->setText(tr("Attention: The existing data will be overwritten. Please proceed carefully!"));
    warning->setAccessibleName("uosDataRestore_WarningLabel");
    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("uosDataRestore_Cancel");
    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("uosDataRestore_Restore");
    m_okBtn->setFixedSize(140, 36);
    hLayout->addWidget(m_okBtn);
    verticalLayout->addLayout(hLayout);

    connect(m_tableView, &QTreeView::pressed, this, &UserDataRestoreWidget::onBackupFileChanged);
    connect(m_cancelBtn, &DPushButton::clicked, this, &UserDataRestoreWidget::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 UserDataRestoreWidget::initTableView()
{
    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->setAccessibleText("HeaderChooseItem");

    // 时间
    auto timeItem = new QStandardItem(tr("Time"));
    timeItem->setTextAlignment(Qt::AlignVCenter);
    timeItem->setAccessibleText("HeaderTime");
    // 类型
    auto typeItem = new QStandardItem(tr("Type"));
    typeItem->setTextAlignment(Qt::AlignVCenter);
    typeItem->setAccessibleText("HeaderType");
    // 用户
    auto userItem = new QStandardItem(tr("User"));
    userItem->setTextAlignment(Qt::AlignVCenter);
    userItem->setAccessibleText("HeaderUser");
    // 备注
    auto remarkItem = new QStandardItem(tr("Note"));
    remarkItem->setTextAlignment(Qt::AlignVCenter);
    remarkItem->setAccessibleText("HeaderNote");

    //操作id
    auto optIdItem = new QStandardItem();
    optIdItem->setAccessibleText("HeaderOptIdItem");

    m_model->setHorizontalHeaderItem(TABLE_COL_CHOOSE, chooseItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_TIME, timeItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_TYPE, typeItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_USER, userItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_REMARK, remarkItem);
    m_model->setHorizontalHeaderItem(TABLE_COL_OPT_ID, optIdItem);

    m_tableView->setFixedHeight(DEFAULT_ROW_HEIGHT * 8);
    m_tableView->header()->setSortIndicatorShown(false);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_CHOOSE, QHeaderView::ResizeToContents);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_TIME, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_TYPE, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_USER, QHeaderView::Stretch);
//    m_tableView->header()->setSectionResizeMode(TABLE_COL_REMARK, QHeaderView::Stretch);

    m_tableView->setColumnWidth(TABLE_COL_CHOOSE, 3);
    m_tableView->setColumnWidth(TABLE_COL_TIME, 170);
    m_tableView->setColumnWidth(TABLE_COL_TYPE, 130);
    m_tableView->setColumnWidth(TABLE_COL_USER, 180);
    m_tableView->setColumnWidth(TABLE_COL_REMARK, 140);
    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 UserDataRestoreWidget::setData(BackupInfoList &backupInfo)
{
    m_model->removeRows(0, m_model->rowCount());
    m_allBackupInfo.clear();
    m_okBtn->setEnabled(false);
    std::sort(backupInfo.begin(), backupInfo.end());
    auto iter = backupInfo.rbegin();
    for (; iter != backupInfo.rend(); ++iter) {
        m_allBackupInfo[iter->operateID] = *iter;
        int currentRow = m_model->rowCount();
        auto chooseItem = new QStandardItem();
        QString currentRowStr = QString("%1").arg(currentRow);
        chooseItem->setAccessibleText( iter->operateID + "_chooseItem");
        chooseItem->setAccessibleDescription(currentRowStr);
        m_model->setItem(currentRow, TABLE_COL_CHOOSE, chooseItem);

        auto time = QDateTime::fromSecsSinceEpoch(iter->startTime);
        QString startTime = time.toString("yyyy-MM-dd HH:mm:ss");
        auto timeItem = new QStandardItem(startTime);
        timeItem->setAccessibleText( iter->operateID + "_timeItem");
        m_model->setItem(currentRow, TABLE_COL_TIME, timeItem);

        auto typeItem = new QStandardItem();
        typeItem->setText(iter->operateType == static_cast<int> (OperateType::UserDataBackup) ? tr("Data backup") : "");
        typeItem->setAccessibleText( iter->operateID + "_typeItem");
        m_model->setItem(currentRow, TABLE_COL_TYPE, typeItem);

        auto userItem = new QStandardItem(QString("%1").arg(iter->username));
        userItem->setAccessibleText( iter->operateID + "_userItem");
        m_model->setItem(currentRow, TABLE_COL_USER, userItem);

        auto remarkItem = new QStandardItem(QString("%1").arg(iter->remark));
        remarkItem->setAccessibleText( iter->operateID + "_remarkItem");
        m_model->setItem(currentRow, TABLE_COL_REMARK, remarkItem);

        //操作id
        auto optIdItem = new QStandardItem(iter->operateID);
        optIdItem->setSelectable(false);
        optIdItem->setAccessibleText(iter->operateID + "_optIdItem");
        m_model->setItem(currentRow, TABLE_COL_OPT_ID, optIdItem);

        //第0列
        DRadioButton *widget0 = new DRadioButton(m_tableView);
        widget0->setAccessibleName(iter->operateID + "_RadioButton");
        widget0->setFocusPolicy(Qt::NoFocus);
        m_tableView->setIndexWidget(m_model->index(currentRow, TABLE_COL_CHOOSE), widget0);
        connect(widget0, &DRadioButton::clicked, this, &UserDataRestoreWidget::onRadioClicked);

    }
}

void UserDataRestoreWidget::onThemeChange()
{

}

void UserDataRestoreWidget::onBackupFileChanged(const QModelIndex &index)
{
    if (!index.isValid()) {
        return;
    }
    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 UserDataRestoreWidget::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 UserDataRestoreWidget::setTips(const QString &tips, bool normalStyle)
{
    if (nullptr != m_tips) {
        m_tips->setText(tips);
        if (normalStyle) {
            QLabel styleLabel;
            m_tips->setStyleSheet(styleLabel.styleSheet());
        } else {
            m_tips->setStyleSheet("QLabel {"
                                  "font-family: SourceHanSansSC, SourceHanSansSC-Medium;"
                                  "font-size: 14px;"
                                  "font-weight: 500;"
                                  "color: #ff5736;"
                                  "}");
        }

        if (tips.isEmpty()) {
            m_tips->hide();
        } else {
            m_tips->show();
        }
    }
}

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

DefaultDataRestoreWidget::DefaultDataRestoreWidget(DWidget *parent) : DWidget(parent)
{
    this->setAccessibleName("DefaultDataRestoreWidget");
    this->initUI();
    this->initLayout();
}

void DefaultDataRestoreWidget::initUI()
{
    m_icon = new DLabel(this);
    m_icon->setPixmap(Utils::hidpiPixmap(":/resources/icons/no-dataBackup-134.png", QSize(134, 134)));
    m_icon->setAccessibleName("uosDataRestore_NoDataBackupIcon");

    m_text = new DLabel(this);
    m_text->setText(tr("No available data backup to restore"));
    m_text->setAlignment(Qt::AlignHCenter);
    m_text->setAccessibleName("uosDataRestore_NoDataBackupToRestore");
    DFontSizeManager::instance()->bind(m_text, DFontSizeManager::T5);
    QFont font = m_text->font();
    font.setWeight(QFont::DemiBold);
    m_text->setFont(font);
    m_text->setForegroundRole(DPalette::PlaceholderText);
    m_text->setWordWrap(true);

    m_button = new DPushButton(this);
    m_button->setText(tr("Return", "button"));
    m_button->setAccessibleName("uosDataRestore_Return");
    m_button->setFixedWidth(200);
    DFontSizeManager::instance()->bind(m_button, DFontSizeManager::T6);

    connect(m_button, &QPushButton::clicked, this, &DefaultDataRestoreWidget::cancel);
}

void DefaultDataRestoreWidget::initLayout()
{
    m_vMainLayout = new QVBoxLayout(this);
    m_vMainLayout->setContentsMargins(0, 0, 0, 0);
    m_vMainLayout->addStretch();
    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(40);
    m_vMainLayout->addStretch();
    m_vMainLayout->addWidget(m_button);
    m_vMainLayout->setAlignment(m_button, Qt::AlignHCenter);
}
