/*
 * 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 "introductionview.h"
#include <QPainterPath>
#include <ukuiwindowhelper/ukuiwindowhelper.h>


IntroductionView::IntroductionView(QWidget * parent)
    :QDialog(parent)
{
#ifdef UKUI_WINDOWHELPER_SUPPORT
    UkuiWindowHelper *ukuiWindowHelper = new UkuiWindowHelper(this);
    ukuiWindowHelper->removeTitleBar();
#else
    kdk::UkuiStyleHelper::self()->removeHeader(this);
#endif
    m_content = new IntroductionContent(this);
    m_content->setAccessibleName("kylin-aiassistant_IntroductionContent_m_content");
    setFixedSize(376,340);
}

void IntroductionView::showView()
{
    IntroductionView * father = reinterpret_cast<IntroductionView *>(parent());
    int posX = father->x() + (father->width() - this->width()) / 2;
    int posY = father->y() + (father->height() - this->height()) / 2;
    move(posX,posY);
    if(isWayland){
        kdk::WindowManager::setGeometry(this->windowHandle(), QRect(posX, posY, this->width(), this->height()));
    }
    this->exec();
}

void IntroductionView::hideView()
{
    hide();
}

void IntroductionView::closeView()
{
    m_isClosed = true;
    close();
}

bool IntroductionView::isClosed() const
{
    return m_isClosed;
}

IntroductionContent::IntroductionContent(QWidget * parent)
    :QWidget(parent)
{
    initChild();
    initLayout();
    initConnection();
    showAgreement();
}

void IntroductionContent::initChild()
{
    m_closeBtn =  new QPushButton;
    m_closeBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_closeBtn");
    m_icon = new QLabel(this);
    m_icon->setAccessibleName("kylin-aiassistant_QLabel_m_icon");
    m_shortcut = new QLabel(tr("Beginner's Guide - Shortcut Keys"),this);
    m_shortcut->setAccessibleName("kylin-aiassistant_QLabel_m_shortcut");
    m_addModel = new QLabel(tr("Beginner's Guide - Model Addition"),this);
    m_addModel->setAccessibleName("kylin-aiassistant_QLabel_m_addModel");


    m_winAltCWid = new InnerWidget(this);
    m_winAltCWid->setAccessibleName("kylin-aiassistant_InnerWidget_m_winAltCWid");
    m_winCWid = new InnerWidget(this);
    m_winCWid->setAccessibleName("kylin-aiassistant_InnerWidget_m_winCWid");
    setPageWid = new InnerWidget(this);
    setPageWid->setAccessibleName("kylin-aiassistant_InnerWidget_setPageWid");
    m_nextBtn = new QPushButton(tr("Next"), this);
    m_nextBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_nextBtn");
    m_previousBtn = new QPushButton(tr("Previous"));
    m_previousBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_previousBtn");
    m_acceptBtn = new QPushButton(tr("Configure"));
    m_acceptBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_acceptBtn");
    m_agreementPageWid = new QWidget(this);
    m_agreementPageWid->setAccessibleName("kylin-aiassistant_QWidget_m_agreementPageWid");
    m_agreementTitle = new QLabel(tr("Beginner's Guide - User Agreement"), this);
    m_agreementTitle->setAccessibleName("kylin-aiassistant_QLabel_m_agreementTitle");
    m_agreementInnerWid = new InnerWidget(this);
    m_agreementInnerWid->setAccessibleName("kylin-aiassistant_InnerWidget_m_agreementInnerWid");
    m_agreementContent = new QTextBrowser(this);
    m_agreementContent->setAccessibleName("kylin-aiassistant_QTextBrowser_m_agreementContent");
    m_agreementContent->setReadOnly(true);
    m_agreementContent->setSource(QUrl("qrc:/html/html/openKylin操作系统AI功能使用协议250228-0318.html"));
    m_agreementScroll = new QScrollArea(this);
    m_agreementScroll->setAccessibleName("kylin-aiassistant_QScrollArea_agreementScroll");
    m_disagreeBtn = new QPushButton(tr("disagree"), this);
    m_disagreeBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_disagreeBtn");
    m_agreeBtn = new QPushButton(tr("agree and continue"), this);
    m_agreeBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_agreeBtn");
}



void IntroductionContent::initLayout()
{
    QFont font;
    font.setPixelSize(int(globals::fontSize + 6));
    font.setBold(true);
    m_shortcut->setFont(font);
    m_addModel->setFont(font);
    m_agreementTitle->setFont(font);

    m_shortcut->setFixedWidth(312);
    m_shortcut->setWordWrap(true);
    m_addModel->setFixedWidth(312);
    m_addModel->setWordWrap(true);
    m_agreementTitle->setFixedWidth(312);
    m_agreementTitle->setWordWrap(true);

    //协议页白框
    m_agreementInnerWid->setFixedSize(328,124);
    m_agreementInnerWid->setAutoFillBackground(true);
    {
        QPalette pal = m_agreementInnerWid->palette();
        pal.setColor(QPalette::Base, Qt::white);
        m_agreementInnerWid->setPalette(pal);
    }


    //协议页滚轮
    m_agreementScroll->setWidgetResizable(true);
    m_agreementScroll->setWidget(m_agreementContent);
    m_agreementScroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_agreementScroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_agreementScroll->setFrameShape(QFrame::NoFrame);
    m_agreementScroll->setFixedSize(m_agreementInnerWid->size());

    QVBoxLayout *innerLayout = new QVBoxLayout;
    innerLayout->setContentsMargins(0, 0, 0, 0);
    innerLayout->addWidget(m_agreementScroll);
    m_agreementInnerWid->setLayout(innerLayout);


    //设置总体的用户协议页面布局
    QVBoxLayout *agreementLayout = new QVBoxLayout;
    agreementLayout->setContentsMargins(0, 4, 16, 16);
    agreementLayout->setSpacing(0);
    agreementLayout->addWidget(m_agreementTitle);      // 标题单独放在上方
    // 在标题和白色框之间添加一些间隔
    QSpacerItem* spacer = new QSpacerItem(0, 12, QSizePolicy::Minimum, QSizePolicy::Fixed);
    agreementLayout->addItem(spacer);
    // 添加白色框区域（滚动区域）
    agreementLayout->addWidget(m_agreementInnerWid); // 白色滚动区域放在下方
    m_agreementPageWid->setLayout(agreementLayout); // 设置布局到用户协议容器

    //关闭按钮
    m_closeBtn = new QPushButton;
    m_closeBtn->setAccessibleName("kylin-aiassistant_QPushButton_m_closeBtn");
    m_closeBtn->setFlat(true);
    m_closeBtn->setFixedSize(32, 32);
    m_closeBtn->setProperty("isWindowButton", 0x2);
    m_closeBtn->setProperty("useIconHighlightEffect", 0x8);
    m_closeBtn->setIcon(QIcon::fromTheme("window-close-symbolic"));
    m_closeBtn->setToolTip(tr("Close"));
    //标题栏
    QHBoxLayout * headerLayout = new QHBoxLayout;
    headerLayout->setContentsMargins(8,1,8,5);
    headerLayout->addStretch();
    headerLayout->addWidget(m_closeBtn);

    // 应用图标
    QPixmap pixmap(":/icon/icon/guide.svg");
    QPixmap scaledPixmap = pixmap.scaled(32, 32, Qt::KeepAspectRatio);
    m_icon->setFixedSize(32,32);
    m_icon->setPixmap(scaledPixmap);
    m_icon->setAlignment(Qt::AlignCenter); // 图片居中显示

    //winc快捷键介绍
    QLabel *introduceWinC = new QLabel(tr("1. Quickly activate/hide AI assistant view"));
    introduceWinC->setAccessibleName("kylin-aiassistant_QLabel_introduceWinC");
    introduceWinC->setFixedWidth(220);
    introduceWinC->setWordWrap(true);
    QLabel *winC = new QLabel("    Win + C");
    winC->setAccessibleName("kylin-aiassistant_QLabel_winC");
    winC->setFixedHeight(20);

    QVBoxLayout *winCIntroLayout = new QVBoxLayout;
    winCIntroLayout->setSpacing(0);
    winCIntroLayout->addWidget(introduceWinC);
    winCIntroLayout->addWidget(winC);

    //winc快捷键图片
    QPixmap pic(":/image/icon/Win_C.svg");
    QLabel * winCImage = new QLabel;
    winCImage->setAccessibleName("kylin-aiassistant_QLabel_winCImage");

    winCImage->setFixedSize(94, 40);
    winCImage->setPixmap(pic);
    winCImage->setAlignment(Qt::AlignCenter);

    QHBoxLayout * winCLayout = new QHBoxLayout;
    winCLayout->addLayout(winCIntroLayout);
    winCLayout->addWidget(winCImage);

    m_winCWid->setFixedWidth(328);
    m_winCWid->setLayout(winCLayout);

    //winaltc快捷键介绍
    QHBoxLayout * winAltCLayout = new QHBoxLayout;
    QLabel *introduceWinAltC = new QLabel(tr("2. After selecting the text, wake/hide the floating bar"));
    introduceWinAltC->setAccessibleName("kylin-aiassistant_QLabel_introduceWinAltC");
    introduceWinAltC->setFixedWidth(220);
    introduceWinAltC->setWordWrap(true);
    QLabel *winAltC = new QLabel("    Win + Alt + C");
    winAltC->setAccessibleName("kylin-aiassistant_QLabel_winAltC");
    winAltC->setFixedHeight(20);

    QVBoxLayout *winAltCIntroLayout = new QVBoxLayout;
    winAltCIntroLayout->setSpacing(0);
    winAltCIntroLayout->addWidget(introduceWinAltC);
    winAltCIntroLayout->addWidget(winAltC);
    winAltCLayout->addLayout(winAltCIntroLayout);

    //winaltc快捷键图片
    QPixmap pic2(":/image/icon/Win_Alt_C.svg");
    QLabel * winAltCImage = new QLabel;
    winAltCImage->setAccessibleName("kylin-aiassistant_QLabel_winAltCImage");
    winAltCImage->setFixedSize(94, 40);
    winAltCImage->setPixmap(pic2);
    winAltCImage->setAlignment(Qt::AlignCenter);
    winAltCLayout->addWidget(winAltCImage);

    m_winAltCWid->setFixedWidth(328);
    m_winAltCWid->setLayout(winAltCLayout);

    //设置蓝色文字
    QPalette palette;
    palette.setColor(QPalette::WindowText, QColor(55,144,250,255));  // 设置字体颜色为蓝色
    QFont f;
    f.setBold(true);
    winC->setFont(f);
    winAltC->setFont(f);
    winC->setPalette(palette);
    winAltC->setPalette(palette);


    //添加模型提示文字
    setPageWid->setFixedSize(328,124);

    QString messageText;
    if (hasLocalModel() == true) {
        messageText = tr("Select a model configuration for optimal performance (local models may run poorly on low-end devices). Click 'Configure Now'.");
    } else {
        messageText = tr("Select a model configuration for optimal performance. Click 'Configure Now'.");
    }

    QLabel *setPageText = new QLabel(messageText);
    setPageText->setAccessibleName("kylin-aiassistant_QLabel_setPageText");
    setPageText->setWordWrap(true);
    QVBoxLayout *setPageLayout = new QVBoxLayout;
    setPageLayout->setContentsMargins(16,16,16,16);
    setPageLayout->addWidget(setPageText);
    setPageLayout->addStretch();
    setPageWid->setLayout(setPageLayout);

    //下一页
    m_nextBtn->setProperty("isImportant", true);
    m_nextBtn->setFixedSize(88,38);

    //上一页
    m_previousBtn->setFixedSize(88,38);

    //立即配置
    m_acceptBtn->setProperty("isImportant", true);
    m_acceptBtn->setFixedSize(88,38);

    m_disagreeBtn->setFixedSize(88,38);

    m_agreeBtn->setProperty("isImportant", true);
    m_agreeBtn->setFixedSize(88,38);

    //底部按钮区
    QHBoxLayout * footLayout = new QHBoxLayout;
    footLayout->setContentsMargins(20, 6, 20, 20);
    footLayout->addStretch();
    footLayout->addWidget(m_previousBtn);
    footLayout->addWidget(m_nextBtn);
    footLayout->addWidget(m_acceptBtn);
    QWidget * footWid = new QWidget;
    footWid->setAccessibleName("kylin-aiassistant_QWidget_footWid");
    footWid->setLayout(footLayout);

    //内容布局
    QVBoxLayout * contentLayout = new QVBoxLayout;
    contentLayout->setContentsMargins(20, 0, 20, 0);
    contentLayout->setSpacing(8);
    contentLayout->addWidget(m_icon);

    //快捷键文字
    contentLayout->addWidget(m_shortcut);
    contentLayout->addWidget(m_winCWid);
    contentLayout->addWidget(m_winAltCWid);
    //添加模型文字
    contentLayout->addWidget(m_addModel);
    contentLayout->addWidget(setPageWid);
    contentLayout->addStretch();
    contentLayout->setAlignment(Qt::AlignTop);

    showFirst();

    contentLayout->addWidget(m_agreementPageWid,0,Qt::AlignLeft);
    m_agreementPageWid->setVisible(false);

    //内容窗口
    contentWid = new QWidget;
    footWid->setAccessibleName("kylin-aiassistant_QWidget_contentWid");
    contentWid->setFixedWidth(376);
    contentWid->setLayout(contentLayout);

    //滚动区域
    QScrollArea * scroll = new QScrollArea;
    scroll->setAccessibleName("kylin-aiassistant_QScrollArea_scroll");
    scroll->setFixedSize(376,220);
    scroll->setWidgetResizable(true);
    scroll->setWidget(contentWid);

    // 设置滚动条策略
    scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  // 隐藏水平滚动条
    scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);    // 垂直滚动条只在需要时显示

    //设置背景透明
    QPalette pa = scroll->palette();
    pa.setBrush(QPalette::Window, Qt::transparent);
    scroll->setPalette(pa);
    scroll->setFrameShape(QFrame::NoFrame);
    //设置滑动条透明
    scroll->verticalScrollBar()->setProperty("drawScrollBarGroove", false);

    //主要布局
    QVBoxLayout *agreementTextLayout = new QVBoxLayout;
     agreementTextLayout->setContentsMargins(16,4,16,16);
     agreementTextLayout->setSpacing(8);
     agreementTextLayout->addWidget(m_agreementContent);
     agreementTextLayout->setSpacing(8);
     m_agreementInnerWid->setLayout(agreementTextLayout);

    QVBoxLayout * mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(4, 4, 4, 4);
    mainLayout->setSpacing(4);
    mainLayout->addLayout(headerLayout);
    mainLayout->addWidget(scroll);
    mainLayout->addWidget(footWid);

    // 将用户协议页加入整体的 contentLayout 中，并初始时设为隐藏
    contentLayout->addWidget(m_agreementPageWid);
    m_agreementPageWid->setVisible(false);

    // 同时将用户协议页的按钮添加到底部按钮区域（footLayout）
    footLayout->addWidget(m_disagreeBtn);
    footLayout->addWidget(m_agreeBtn);
    // 初始先设为隐藏
    m_disagreeBtn->setVisible(false);
    m_agreeBtn->setVisible(false);

}



void IntroductionContent::initConnection()
{
    connect(m_closeBtn, &QPushButton::clicked, [this](){
        if(m_agreementPageWid->isVisible()){
            g_configManager->updateConfig("is-first-install", true);
            exit(0);
        } else {
            IntroductionView *father = reinterpret_cast<IntroductionView *>(parent());
            father->closeView();
        }
    });

    connect(m_nextBtn, &QPushButton::clicked, this, &IntroductionContent::showSecond);
    connect(m_previousBtn, &QPushButton::clicked, this, &IntroductionContent::showFirst);
    connect(m_acceptBtn, &QPushButton::clicked, [&](){
        IntroductionView * father = reinterpret_cast<IntroductionView *>(parent());
        father->closeView();
        //Q_EMIT father->showSettingPage();
        Q_EMIT father->openUKUIControlCenterView();
    });

    connect(m_disagreeBtn, &QPushButton::clicked, this, &IntroductionContent::onDisagreeClicked);
    connect(m_agreeBtn, &QPushButton::clicked, this, &IntroductionContent::onAgreeClicked);



}




void IntroductionContent::showFirst()
{
    m_agreementPageWid->setVisible(false);
    m_disagreeBtn->setVisible(false);
    m_agreeBtn->setVisible(false);
    m_shortcut->setVisible(true);
    m_winCWid->setVisible(true);
    m_winAltCWid->setVisible(true);
    m_addModel->setVisible(false);
    setPageWid->setVisible(false);
    m_nextBtn->setVisible(true);
    m_previousBtn->setVisible(false);
    m_acceptBtn->setVisible(false);
}

void IntroductionContent::showSecond()
{
    m_agreementPageWid->setVisible(false);
    m_disagreeBtn->setVisible(false);
    m_agreeBtn->setVisible(false);
    m_shortcut->setVisible(false);
    m_winCWid->setVisible(false);
    m_winAltCWid->setVisible(false);
    m_addModel->setVisible(true);
    setPageWid->setVisible(true);
    m_nextBtn->setVisible(false);
    m_previousBtn->setVisible(true);
    m_acceptBtn->setVisible(true);
}

void IntroductionContent::showAgreement()
{
    // 隐藏其他页面控件
    m_shortcut->setVisible(false);
    m_winCWid->setVisible(false);
    m_winAltCWid->setVisible(false);
    m_addModel->setVisible(false);
    setPageWid->setVisible(false);
    m_nextBtn->setVisible(false);
    m_previousBtn->setVisible(false);
    m_acceptBtn->setVisible(false);

    // 显示用户协议页面和按钮
    m_agreementPageWid->setVisible(true);
    m_disagreeBtn->setVisible(true);
    m_agreeBtn->setVisible(true);
}

void IntroductionContent::onDisagreeClicked()
{
    g_configManager->updateConfig("is-first-install", true);
    // 用户选择不同意，则关闭向导
    QCoreApplication::quit();
    QTimer::singleShot(0,QCoreApplication::quit);
}

void IntroductionContent::onAgreeClicked()
{
    // 用户同意后，显示原先的第一页（快捷键介绍）
    showFirst();
}


void IntroductionContent::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    // 创建一个线性渐变：从上到下
    QLinearGradient gradient(QPointF(width()/2, 0), QPointF(width()/2,height()));
    gradient.setColorAt(0, QColor(7, 144, 250, 0.25 * 255));   // 渐变的起始颜色
    gradient.setColorAt(1, QColor(7, 144, 250, 0.));  // 渐变的结束颜色

    // 设置渐变作为画刷
    painter.setBrush(gradient);
    painter.setPen(Qt::NoPen);  // 不使用边框

    // 绘制整个背景
    painter.drawRect(0, 0, width(), height());
}

bool IntroductionContent::hasLocalModel()
{
    ModelConfig mc;
    const auto models = mc.getExtendedModels(DeployType::Ondevice);
    KyInfo() << "Determine whether the local model is available through getExtendedModels，get local models size:" << models.size();
    if (models.size() == 0) {
        return false;
    } else {
        return true;
    }
}


InnerWidget::InnerWidget(QWidget *parent)
{
}

void InnerWidget::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    QPainterPath path;
    path.addRoundedRect(rect(), 12, 12);
    // 将路径转换为多边形，并设置为控件的 mask
    setMask(QRegion(path.toFillPolygon().toPolygon()));
    QWidget::resizeEvent(event);

}
void InnerWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    // 将圆角半径由 12 改为 8
    QPainterPath path;
    path.addRoundedRect(rect(), 12, 12);

    painter.setClipPath(path);
    QColor bgColor = this->palette().color(QPalette::Base);
    painter.fillPath(path, bgColor);
}
