/*
 * Copyright (C) 2020, KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
#include "settingdialog.h"

#include <knavigationbar.h>
#include <QResizeEvent>
#include <QVBoxLayout>
#include <QStackedWidget>
#include <kmessagebox.h>
#include <QPushButton>
#include <QModelIndex>

#include "windowhelper.h"

SettingDialog* SettingDialog::sharedInstance = nullptr;

class SettingDialog::Private
{
public:
    QModelIndex m_commandTemplateIndex;  // "Prompt Template"的索引
    bool isCancelOperation = false;
    QPushButton *m_btnBack = nullptr;
    KNavigationBar *navigationBar = nullptr;
    QStackedWidget *stackedWidget = nullptr;
    CommandPage *commandPage = nullptr;
    ScribeWordPage *scribeWordPage = nullptr;
    GeneralPage *generalPage = nullptr;

};

SettingDialog::SettingDialog(QWidget *parent):
    KWidget(parent),
    d_ptr(std::make_shared<Private>())
{
    // fix bug #301003 【需求33947】【AI助手】设置窗口支持拖拽调整大小，双击后窗口最大化
    // 问题描述：由于sdk KWidget嵌套KWidget的实现机制问题，直接通过构造函数setFixedSize会失效
    // 解决方案：为避免此问题，采用规避方案：1. 不在构造函数中调用setFixedSize，改为在对象创建后设置固定大小 2. 在构造函数中首先调用resize，否则获取宽高时会出现问题
    resize(744, 460);
    initLayout();
    initConnect();
    //setAttribute(Qt::WA_TranslucentBackground);
    setWindowModality(Qt::WindowModal);
//    setWindowModality(Qt::ApplicationModal);
}

SettingDialog::~SettingDialog()
{
}

void SettingDialog::initLayout()
{
    setWindowFlag(Qt::Dialog);
    setLayoutType(HorizontalType);
    setIcon(QIcon::fromTheme("kylin-ai-assistant"));
    setWidgetName(tr("Setting"));

    d_ptr->m_btnBack = new QPushButton(this);
    d_ptr->m_btnBack->setAccessibleName("kylin-aiassistant_QPushButton_d_ptr->m_btnBack");
    d_ptr->m_btnBack->setFixedSize(32, 32);
    d_ptr->m_btnBack->setIcon(QIcon(QString(":/icon/icon/back.svg")));
    d_ptr->m_btnBack->setIconSize(QSize(16, 16));
    d_ptr->m_btnBack->setProperty("useIconHighlightEffect", true);
    d_ptr->m_btnBack->setProperty("iconHighlightEffectMode", 1);
    d_ptr->m_btnBack->setFlat(true);
    d_ptr->m_btnBack->setVisible(false);
    d_ptr->m_btnBack->setToolTip(tr("back"));

    KWindowButtonBar *button_bar = windowButtonBar();
    button_bar->minimumButton()->hide();
    button_bar->maximumButton()->hide();
    ((QHBoxLayout *)button_bar->layout())->insertWidget(0, d_ptr->m_btnBack);

    initSideBar();
    initBaseBar();

    //windowButtonBar()->setBackgroundRole(QPalette::Window);
    //baseBar()->setBackgroundRole(QPalette::Window);

}

void SettingDialog::initSideBar()
{
    QVBoxLayout *layout_left = new QVBoxLayout(sideBar());
    d_ptr->navigationBar = new KNavigationBar(nullptr);
    d_ptr->navigationBar->setAccessibleName("kylin-aiassistant_KNavigationBar_d_ptr->navigationBar");
    QStandardItem *itemCommand = new QStandardItem(QIcon(":/icon/icon/setting/prompt.svg"),tr("Prompt Template"));
    QStandardItem *itemFloatingBar = new QStandardItem(QIcon(":/icon/icon/setting/floatingbar.svg"),tr("Word Selection Floating Bar"));
    QStandardItem *itemGeneral = new QStandardItem(QIcon(":/icon/icon/setting/convention.svg"),tr("General"));
    d_ptr->navigationBar->addItem(itemGeneral);
    d_ptr->navigationBar->addItem(itemCommand);
    d_ptr->navigationBar->addItem(itemFloatingBar);
    d_ptr->navigationBar->listview()->setCurrentIndex(d_ptr->navigationBar->listview()->model()->index(0, 0));
    layout_left->addWidget(d_ptr->navigationBar);

    sideBar()->show();
}

void SettingDialog::initBaseBar()
{
    QVBoxLayout *vlay = new QVBoxLayout(baseBar());

    d_ptr->stackedWidget = new QStackedWidget;
    d_ptr->stackedWidget->setAccessibleName("kylin-aiassistant_QStackedWidget_d_ptr->stackedWidget");
    vlay->addWidget(d_ptr->stackedWidget);
    {

        d_ptr->generalPage = new GeneralPage(this);
        d_ptr->generalPage->setAccessibleName("kylin-aiassistant_GeneralPage_d_ptr->generalPage");
        d_ptr->stackedWidget->addWidget(d_ptr->generalPage);

        d_ptr->commandPage = new CommandPage(this);
        d_ptr->commandPage->setAccessibleName("kylin-aiassistant_CommandPage_d_ptr->commandPage");
        d_ptr->stackedWidget->addWidget(d_ptr->commandPage);

        d_ptr->scribeWordPage = new ScribeWordPage(this);
        d_ptr->scribeWordPage->setAccessibleName("kylin-aiassistant_ScribeWordPage_d_ptr->scribeWordPage");
        d_ptr->stackedWidget->addWidget(d_ptr->scribeWordPage);
    }

    d_ptr->stackedWidget->setCurrentIndex(0);
}

void SettingDialog::initConnect()
{
    connect(d_ptr->navigationBar->listview(), &QListView::clicked, this, &SettingDialog::slotNaviClicked);
    // connect(d_ptr->generalPage, &GeneralPage::sigMinimizeToTrayChanged, [this](bool isMinimizeToTray){
    //     // 这里可以连接到主程序的相关槽函数
    //     emit sigMinimizeToTraySettingChanged(isMinimizeToTray);
    // });
    connect(d_ptr->scribeWordPage, &ScribeWordPage::sigEnableScribeWordsSwitch, [this](){
        Q_EMIT this->sigEnableScribeWords();
    });
    connect(d_ptr->scribeWordPage, &ScribeWordPage::sigDisableScribeWordsSwitch, [this](){
        Q_EMIT this->sigDisableScribeWords();
    });
    connect(d_ptr->m_btnBack, &QPushButton::clicked, [this](){
        d_ptr->m_btnBack->setVisible(false);
        d_ptr->stackedWidget->setCurrentIndex(0);
    });
}

void SettingDialog::resetIndex()
{
    QListView *listView = d_ptr->navigationBar->listview();
    QModelIndex index = listView->model()->index(0,0);
    listView->setCurrentIndex(index);
    d_ptr->stackedWidget->setCurrentIndex(0);
}

void SettingDialog::onSetSelectCloudModel(AiCapability capability, QString modelName)
{
    emit sigSetCloudModel(capability, modelName);
}

void SettingDialog::slUpdateCloseMode(bool isHideToTray)
{
    if(d_ptr->generalPage)
    {
        d_ptr->generalPage->updateCloseMode(isHideToTray);
    }
}

void SettingDialog::slotNaviClicked(const QModelIndex &index)
{
   QString data = index.data().toString();
   if(data == tr("General")) {
       d_ptr->m_btnBack->setVisible(false);
       d_ptr->stackedWidget->setCurrentIndex(0);
   } else if(data == tr("Prompt Template")) {
       d_ptr->m_commandTemplateIndex = index;
       d_ptr->m_btnBack->setVisible(false);
       d_ptr->stackedWidget->setCurrentIndex(1);
       CommandTemplateList::getInstance()->updateAllData();
   } else if(data == tr("Word Selection Floating Bar")){
       d_ptr->m_btnBack->setVisible(false);
       d_ptr->stackedWidget->setCurrentIndex(2);
   }

   return;
}

void SettingDialog::showSaveMsgBox()
{
    ConfirmSaveDialog confirmSaveDialog(this);
    confirmSaveDialog.exec();
}

void SettingDialog::closeEvent(QCloseEvent *event)
{
    event->ignore();

    hide();
    isSettingOpen = false;
}

void SettingDialog::paintEvent(QPaintEvent *event)
{
    QPalette pale;
    pale.setColor(QPalette::Base, QColor("#F5F5F5"));
    pale.setColor(QPalette::Window, QColor("#F5F5F5"));
    baseBar()->setPalette(pale);
    baseBar()->setAutoFillBackground(true);

    windowButtonBar()->setPalette(pale);
    windowButtonBar()->setAutoFillBackground(true);

    // 首先调用父类的paintEvent，确保其他绘制正常进行
    QWidget::paintEvent(event);

    return;
}


void SettingDialog::scribeWordsDisabled()
{
    if(d_ptr->scribeWordPage)
    {
        d_ptr->scribeWordPage->disableScribeWords();
    }
}


void SettingDialog::onThemeChanged()
{
    Q_EMIT sigChangeTheme();
}

void SettingDialog::onCancelOperation()
{
    d_ptr->isCancelOperation = true;
}

ConfirmSaveDialog::ConfirmSaveDialog(QWidget *parent)
    : QDialog(parent)
{
    initLayout();
    initConnect();
}


ConfirmSaveDialog::~ConfirmSaveDialog()
{

}

void ConfirmSaveDialog::initLayout()
{
    setWindowIcon(QIcon::fromTheme("kylin-ai-assistant"));
    setWindowTitle(tr("kylin-aiassistant"));
    setFixedSize(420, 172);
    this->setContentsMargins(0, 0, 0, 0);

#ifdef UKUI_WINDOWHELPER_SUPPORT
    UkuiWindowHelper *ukuiWindowHelper = new UkuiWindowHelper(this);
    ukuiWindowHelper->removeTitleBar();
#else
    kdk::UkuiStyleHelper::self()->removeHeader(this);
#endif

    this->setAttribute(Qt::WA_AlwaysShowToolTips);

    m_closeButton = new QPushButton;
    m_closeButton->setAccessibleName("kylin-aiassistant_QPushButton_m_closeButton");

    m_closeButton->setFlat(true);
    m_closeButton->setFixedSize(32, 32);
    m_closeButton->setProperty("isWindowButton", 0x2);
    m_closeButton->setProperty("useIconHighlightEffect", 0x8);
    m_closeButton->setIcon(QIcon::fromTheme("window-close-symbolic"));
    m_closeButton->setToolTip(tr("Close"));

    m_titleWidget = new QWidget();
    m_titleWidget->setAccessibleName("kylin-aiassistant_QWidget_m_titleWidget");
    m_titleWidget->setFixedSize(420, 40);
    QHBoxLayout *titleHLayout = new QHBoxLayout(m_titleWidget);
    titleHLayout->setContentsMargins(8, 4, 4, 4);
    titleHLayout->addStretch();
    titleHLayout->addWidget(m_closeButton);

    m_iconLabel = new QLabel;
    m_iconLabel->setAccessibleName("kylin-aiassistant_QLabel_m_iconLabel");
    m_iconLabel->setFixedSize(22,22);
    QPixmap pixmap(":/icon/icon/tips.svg");
    pixmap.scaled(m_iconLabel->size(), Qt::KeepAspectRatio,Qt::SmoothTransformation);
    m_iconLabel->setScaledContents(true);
    m_iconLabel->setPixmap(pixmap);//设置图标

    m_textLabel = new QLabel(tr("Your changes have not been saved yet. Do you want to save these changes?"));
    m_textLabel->setAccessibleName("kylin-aiassistant_QLabel_m_textLabel");
    m_textLabel->setWordWrap(true);

    m_contentWidget = new QWidget();
    m_contentWidget->setAccessibleName("kylin-aiassistant_QWidget_m_contentWidget");
    m_contentWidget->setContentsMargins(24, 8, 24, 0);
    QHBoxLayout *contentHLayout = new QHBoxLayout(m_contentWidget);
    contentHLayout->setContentsMargins(0, 0, 0, 0);
    contentHLayout->setSpacing(8);
    contentHLayout->addWidget(m_iconLabel);
    contentHLayout->addWidget(m_textLabel);

    m_cancelButton = new QPushButton(tr("Cancel"), this);
    m_cancelButton->setAccessibleName("kylin-aiassistant_QPushButton_m_cancelButton");
    m_cancelButton->setFixedSize(94, 36);

    m_saveButton = new QPushButton(tr("Save"), this);
    m_saveButton->setAccessibleName("kylin-aiassistant_QPushButton_m_saveButton");
    m_saveButton->setProperty("isImportant", true);
    m_saveButton->setFixedSize(94, 36);

    m_buttonWidget = new QWidget();
    m_buttonWidget->setAccessibleName("kylin-aiassistant_QWidget_m_buttonWidget");
    m_buttonWidget->setContentsMargins(24, 0, 24, 24);
    QHBoxLayout *buttonHLayout = new QHBoxLayout(m_buttonWidget);
    buttonHLayout->setContentsMargins(0, 0, 0, 0);
    buttonHLayout->setSpacing(16);
    buttonHLayout->addStretch();
    buttonHLayout->addWidget(m_cancelButton);
    buttonHLayout->addWidget(m_saveButton);

    QVBoxLayout *vLayout = new QVBoxLayout(this);
    vLayout->setContentsMargins(0, 0, 0, 0);
    vLayout->addWidget(m_titleWidget);
    vLayout->addWidget(m_contentWidget);
    vLayout->addStretch();
    vLayout->addWidget(m_buttonWidget);

    this->setLayout(vLayout);
}

void ConfirmSaveDialog::initConnect()
{
    connect(m_closeButton, &QPushButton::clicked, this, &ConfirmSaveDialog::onCloseBtnClicked);
    connect(m_cancelButton, &QPushButton::clicked, this, &ConfirmSaveDialog::onCancelBtnClicked);
    connect(m_saveButton, &QPushButton::clicked, this, &ConfirmSaveDialog::onSaveBtnClicked);

}

void ConfirmSaveDialog::onCloseBtnClicked()
{
    emit sigCloseBtnClicked();
    reject();
}

void ConfirmSaveDialog::onCancelBtnClicked()
{
    emit sigCancelBtnClicked();
    reject();
}

void ConfirmSaveDialog::onSaveBtnClicked()
{
    emit sigSaveBtnClicked();
    accept();
}
