/*
   Copyright (c) 2003-2007 Clarence Dang <dang@kde.org>
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.

   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
   IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
   IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
   THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "widgets/toolbars/kpAiDrawingBar.h"
#include <QLinearGradient>
#include <QBrush>
#include <QPalette>
#include <QTextEdit>
#include <QPainter>
#include <QFont>
#include <QMovie>
#include <KLocalizedString>
#include <QDBusInterface>

static int configVersion = 2; //AI作图基础版本和高级版本的分别

kpAIDrawingBar::kpAIDrawingBar(QWidget *parent)
    : QDockWidget (parent)
{
    setTitleBarWidget(new QWidget());
    setFeatures(QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
    setAcceptDrops (false);

    AiSettings = nullptr;
    //取消登录界面绘画
    /*
    if(!getConfigStatus())
        loginConfigurationPage();
    else
    */

    m_AiMode = new AIModeDataThread();
    if(m_AiMode->setSessionStatus())
    {
        mSession = m_AiMode->getVisionSession();
    }

    initUI();

    setFixedWidth(250);
}

kpAIDrawingBar::~kpAIDrawingBar()
{
    if (AiSettings)
        delete AiSettings;
    if (m_AiMode)
        delete m_AiMode;
}

/**
 * @brief kpAIDrawingBar::getConfigStatus
 * 获取AI画图秘钥是否配置
 * @return 是否配置
 */
bool kpAIDrawingBar::getConfigStatus()
{
    bool res = false;
    if (QGSettings::isSchemaInstalled(AI_GSETTINGS)){
        AiSettings = new QGSettings(AI_GSETTINGS);
        connect(AiSettings, &QGSettings::changed, this, &kpAIDrawingBar::onConfigSettingsChange);
        res = AiSettings->get(AI_KEY).toBool();
    }

    return res;
}

/**
 * @brief kpAIDrawingBar::onConfigSettingsChange
 * 配置反馈回调函数
 * @param key
 */
void kpAIDrawingBar::onConfigSettingsChange(const QString &key)
{
    qDebug()<<"key == "<<key;
    if (key.compare("isVisionSetup") == 0){
        if(AiSettings->get("isVisionSetup").toBool()){
            if (configWidget) {
                delete configWidget;
                initUI();
            }
        }
    }
}

/**
 * @brief kpAIDrawingBar::loginConfigurationPage
 * 登录配置界面函数
 */
void kpAIDrawingBar::loginConfigurationPage()
{
    configWidget = new QWidget(this);
    QVBoxLayout* layout = new QVBoxLayout(configWidget);

    QLabel* label_logo = new QLabel(this);
    label_logo->setPixmap(QPixmap(DRAWING_IMAGE));
    label_logo->setScaledContents(true);
    label_logo->setFixedSize(54,52);

    QLabel* label_slogo = new QLabel(this);
    label_slogo->setPixmap(QPixmap(SLOGO_IMAGE));
    label_slogo->setScaledContents(true);
    label_slogo->setFixedSize(168,24);

    QLabel* label_config = new QLabel(this);
    label_config->setText(i18n("Please configure the AI model account before you can use the mapping function."));
    label_config->setFixedSize(218,52);
    label_config->setAlignment(Qt::AlignCenter);
    label_config->setWordWrap(true);
    label_config->setStyleSheet("color: #B8B8B8;");

    QPushButton* button_config = new QPushButton(i18n("Configure now"),this);
    button_config->setFixedSize(112,36);
    button_config->setStyleSheet("QPushButton"
                                 "{ background-color: #3790FA; "
                                 "color: white; "
                                 "border: none;"
                                 "border-radius: 5px; }");

    QLabel* label_bg = new QLabel(this);
    label_bg->setFixedSize(250, 160);
    label_bg->setPixmap(QPixmap(BG_IMAGE));
    label_bg->setScaledContents(true);

    layout->addStretch(25);
    layout->addWidget(label_logo, 0, Qt::AlignCenter);
    layout->addStretch(1);
    layout->addWidget(label_slogo, 1, Qt::AlignCenter);
    layout->addStretch(1);
    layout->addWidget(label_config, 2, Qt::AlignCenter);
    layout->addStretch(1);
    layout->addSpacing(15);
    layout->addWidget(button_config, 3, Qt::AlignCenter);
    layout->addStretch(25);
    layout->addWidget(label_bg, 4);

    connect(button_config, &QPushButton::clicked, this, &kpAIDrawingBar::onConfigButtonClicked);
    configWidget->setLayout(layout);
    setWidget(configWidget);

}

/**
 * @brief kpAIDrawingBar::onConfigButtonClicked
 * 登录配置按钮回调函数，调用秘钥配置界面
 */
void kpAIDrawingBar::onConfigButtonClicked()
{
    QDBusInterface *m_dbusInterface = new QDBusInterface(KYLIN_AI_DBUS,
                                                         KYLIN_AI_PATH,
                                                         KYLIN_AI_DBUS,
                                                         QDBusConnection::sessionBus(),
                                                         this);
    if(m_dbusInterface->isValid()){
        m_dbusInterface->call("setModel");
    }
    delete m_dbusInterface;
}


/**
 * @brief kpAIDrawingBar::getconfigVersionData
 * 获取AI作图调用的模型是基础版本还是高级版本
 */
void kpAIDrawingBar::getconfigVersionData()
{
    QString jsonFilePath = QDir::homePath() + "/.config/model_manager.json";

    qDebug()<<jsonFilePath;

    QFile file(jsonFilePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;
    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData);
    if (jsonDoc.isNull()) {
        qDebug() << "Failed to parse JSON file:" << jsonFilePath;
        return;
    }
    // 获取JSON对象
    QJsonObject jsonObject = jsonDoc.object();
    // 访问第一个键（即"0"）
    if (jsonObject.contains("0")) {
        QJsonObject innerObject = jsonObject.value("0").toObject();

        // 访问第二个键（即"1"）
        if (innerObject.contains("1")) {
            QJsonObject versionObject = innerObject.value("1").toObject();

            // 检查是否存在"version"键
            if (versionObject.contains("version")) {
                // 获取"version"的值
                configVersion = versionObject.value("version").toInt();
                qDebug() << "Version:" << configVersion;
            }
        }
    }
}

/**
 * @brief kpAIDrawingBar::initUI
 * 初始化画图界面
 */
void kpAIDrawingBar::initUI()
{
    ImageStyle = EXPLORE_INFINITY;
    selectedIconLabel = nullptr;
    selectedTextLabel = nullptr;

    scrollArea = new QScrollArea(this);
    scrollArea->setWidgetResizable(true);
    auto *centralWidget = new QWidget(scrollArea);

    textBox = QString("A cute cat pilot wearing goggles is soaring through the blue sky, cartoon style, HD");

    colorfulButtonStyle = "QPushButton "
                          "{ background: qlineargradient("
                          "x1: 0, y1: 0, x2: 1, y2: 0,"
                          "stop: 0 #3790FA, "
                          "stop: 1 #E85CFF);"
                          "color: white; "
                          "border: none;"
                          "border-radius: 5px; }";

    colorGrayButtonStyle = "QPushButton"
                           "{ background-color: #E6E6E6; "
                           "color: #2626268C; "
                           "border: none;"
                           "border-radius: 5px; }";
    // 获取基础版本/高级版本
//    getconfigVersionData();

//    if (configVersion == 2)
    AIImageSize = QSize(512, 512);
//    else if (configVersion == 1)
//        AIImageSize = QSize(1536, 1024);

    /* 图像描述布局 */
    auto *label = new QLabel(i18n("Image description"));
    label->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    label->setFixedSize(224,30);

    QTextEdit *inputBox = new QTextEdit();
    inputBox->setPlaceholderText(i18n(textBox.toLocal8Bit().data()));
    inputBox->setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
    inputBox->setFixedSize(224,136);

    /* 图像风格布局 */
    auto *styleLabel = new QLabel(i18n("Image style"));
    styleLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    styleLabel->setFixedSize(180, 30);

    styleGrid = new QGridLayout();
    addStyleWidget();

    /* 图像分辨率 */
    auto *resolutionLabel = new QLabel(i18n("Image resolution"));
    resolutionLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    resolutionLabel->setFixedSize(180, 30);

    resolutionComboBox = new QComboBox(this);
    addResolutionComboBox();

    /* 生成数量布局 */
    QLabel *quantityLabel = new QLabel(i18n("Generated quantity"));
    quantityLabel->setAlignment(Qt::AlignLeft | Qt::AlignTop);
    quantityLabel->setFixedSize(180, 30);

    quantityComboBox = new QComboBox(this);
    addQuantityComboBox();

    /* 立即生成按钮 */
    buildButton = new QPushButton(i18n("Generate now"), this);
    buildButton->setFixedSize(224,36);
    buildButton->setStyleSheet(colorGrayButtonStyle);
    buildButton->setEnabled(false);
    buildButtonFlag = false;

    /* 分页功能 */
    stackedWidget = new QStackedWidget(centralWidget);

    /* 生成结果布局 */
    resultGrid = new QHBoxLayout(this);
    resultLabel = new QLabel(i18n("result"));
    QPushButton *previousButton = new QPushButton(this);
    pageLabel = new QLabel(tr("1"));
    QPushButton *nextButton = new QPushButton(this);
    deleteButton = new QPushButton(this);
    resultLabel->setFixedSize(80,30);

    previousButton->setIcon(QIcon::fromTheme("ukui-start-symbolic"));
    previousButton->setFixedSize(20,20);
    previousButton->setStyleSheet("QPushButton { background-color: transparent; }");

    pageLabel->setFixedSize(50,30);
    pageLabel->setAlignment(Qt::AlignCenter);

    nextButton->setFixedSize(20,20);
    nextButton->setIcon(QIcon::fromTheme("ukui-end-symbolic"));
    nextButton->setStyleSheet("QPushButton { background-color: transparent; }");

    deleteButton->setIcon(QIcon::fromTheme("edit-delete-symbolic"));
    deleteButton->setFixedSize(24,24);
    deleteButton->setStyleSheet("QPushButton { background-color: transparent; }");

    resultGrid->addWidget(resultLabel);
    resultGrid->addStretch();
    resultGrid->addWidget(previousButton);
    resultGrid->addWidget(pageLabel);
    resultGrid->addWidget(nextButton);
    resultGrid->addWidget(deleteButton);
    resultGrid->setAlignment(pageLabel, Qt::AlignRight);

    /* 设置整体布局 */
    vbox = new QBoxLayout(QBoxLayout::TopToBottom, centralWidget);
    vbox->setMargin (2);
    vbox->setSpacing (5);
    vbox->setAlignment(Qt::AlignTop);

    vbox->addWidget(label);
    vbox->addWidget(inputBox);
    vbox->addSpacing(15);
    vbox->addWidget(styleLabel);
    vbox->addLayout(styleGrid);
    vbox->addSpacing(15);
    vbox->addWidget(resolutionLabel);
    vbox->addWidget(resolutionComboBox);
    vbox->addSpacing(15);
    vbox->addWidget(quantityLabel);
    vbox->addWidget(quantityComboBox);
    vbox->addSpacing(15);
    vbox->addWidget(buildButton);
    vbox->addSpacing(15);
    vbox->addLayout(resultGrid);
    vbox->addWidget(stackedWidget);

    vbox->setContentsMargins(5,5,15,5);
    // 隐藏resultGrid中的所有子控件
    for (int i = 0; i < resultGrid->count(); ++i)
    {
        QLayoutItem *item = resultGrid->itemAt(i);
        if (item && item->widget())
            item->widget()->setVisible(false);
    }

    connect(buildButton, &QPushButton::clicked, this, &kpAIDrawingBar::onGenerateButtonClicked);
    connect(inputBox,&QTextEdit::textChanged, this, &kpAIDrawingBar::handleInputTextChanged);
    connect(previousButton, &QPushButton::clicked, this, &kpAIDrawingBar::showPreviousPage);
    connect(nextButton, &QPushButton::clicked, this, &kpAIDrawingBar::showNextPage);
    connect(deleteButton, &QPushButton::clicked, this, &kpAIDrawingBar::deleteCurrentPage);
    connect(m_AiMode, &AIModeDataThread::finishedSignal, this, &kpAIDrawingBar::onThreadFinished);

    centralWidget->setFixedWidth(240);

    scrollArea->setWidget(centralWidget);
    scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    setWidget(scrollArea);
}

/**
 * @brief kpAIDrawingBar::addStyleGrid
 * 添加风格布局
 * @param widget
 * @param line
 */
void kpAIDrawingBar::addStyleGrid(QWidget *widget, int line)
{
    styleGrid->addWidget(widget, line / 3, line % 3);
}

/**
 * @brief kpAIDrawingBar::addStyleWidget
 * 添加风格窗口
 */
void kpAIDrawingBar::addStyleWidget()
{
    QString path = "/usr/share/kolourpaint/pics/style/%1";
    QStringList styleList = {"style-ancient", "style-anime",
                             "style-realistic","style-ukiyoe"};

    QStringList styleMoreList ={ "style-futurism", "style-pixel", "style-conceptual", "style-cyberpunk",
                                 "style-baroque", "style-surrealism", "style-watercolour", //头部删除"style-lolita"
                                 "style-vaporwave", "style-oil-painting","style-cartoon"};



    moreButton = new QPushButton();
    moreButton->setText(i18n("more"));
    moreButton->setFixedSize(72, 40);
    moreButton->setFont(QFont("Arial", 8));
    moreButton->setProperty("useButtonPalette", true);

    QWidget *widget_all = addAllStyleLabel(path.arg("style-all@2x.png"), "style-all", 0);
    widget_low_poly = addStyleLabel(path.arg("style-low-poly@2x.png"), "style-low-poly", 5);

    styleGrid->addWidget(widget_all, 0, 0, Qt::AlignTop);
    for (int i = 0; i < styleList.size(); ++i)
    {
        QString iconPath = path.arg(styleList[i]) + "@2x.png";
        QString labelText = styleList[i];
        QWidget *widget = addStyleLabel(iconPath, labelText, i+1);
        addStyleGrid(widget, i+1);
    }
    styleGrid->addWidget(moreButton, 1, 2,Qt::AlignTop);
    for (int i = 0; i < styleMoreList.size(); ++i)
    {
        QString iconPath = path.arg(styleMoreList[i]) + "@2x.png";
        QString labelText = styleMoreList[i];
        QWidget *widget = addStyleLabel(iconPath, labelText, i + 6);
        addStyleGrid(widget, i + 6);
    }

    for (int i = 6; i < styleGrid->count(); ++i)
    {
        styleGrid->itemAt(i)->widget()->setVisible(false);
    }

    styleFlag = true;

    connect(moreButton,&QPushButton::clicked, this, &kpAIDrawingBar::onStyleMoreButtonClick);

}

/**
 * @brief kpAIDrawingBar::onStyleMoreButtonClick
 * 风格点击回调事件
 */
void kpAIDrawingBar::onStyleMoreButtonClick()
{
    if (styleFlag) {
        for (int i = 0; i < styleGrid->count(); ++i)
        {
            styleGrid->itemAt(i)->widget()->setVisible(styleFlag);
        }

        moreButton->setText(i18n("Pack up"));

        styleGrid->removeWidget(moreButton);

        addStyleGrid(widget_low_poly, 5);
        styleGrid->addWidget(moreButton, 5, 1,Qt::AlignTop);
    } else {
        for (int i = 5; i < styleGrid->count()-1; ++i)
        {
            styleGrid->itemAt(i)->widget()->setVisible(styleFlag);
        }

        moreButton->setText(i18n("more"));

        styleGrid->removeWidget(moreButton);
        styleGrid->removeWidget(widget_low_poly);

        addStyleGrid(widget_low_poly, 16);
        styleGrid->addWidget(moreButton, 1, 2, Qt::AlignTop);
    }

    styleFlag = !styleFlag;
}

/**
 * @brief kpAIDrawingBar::addAllStyleLabel
 * 添加探索无限风格函数
 * @param iconPath
 * @param labelText
 * @param line
 * @return
 */
QWidget *kpAIDrawingBar::addAllStyleLabel(QString iconPath, QString labelText, int line)
{
    QWidget *widget = new QWidget();
    QVBoxLayout *styleVBox = new QVBoxLayout(widget);

    QLabel *iconLabel = new QLabel(this);
    iconLabel->setObjectName("iconLabel");
    iconLabel->setFixedSize(72,42);
    iconLabel->setPixmap(QPixmap(iconPath).scaled(112,64, Qt::KeepAspectRatio,Qt::SmoothTransformation));
    iconLabel->setScaledContents(true);
    iconLabel->setAlignment(Qt::AlignCenter);

    QLabel *textLabel = new QLabel(i18n(labelText.toLocal8Bit().data()), this);
    textLabel->setObjectName("textLabel");
    textLabel->setFixedSize(72,16);
    textLabel->setFont(QFont("Arial", 8));
    textLabel->setAlignment(Qt::AlignCenter);
    textLabel->setProperty("labelStyle", line);

    iconLabel->setStyleSheet("border: 2px solid #3790FA; border-radius: 5px;");
    textLabel->setStyleSheet("color: #3790FA;");
    selectedIconLabel = iconLabel;
    selectedTextLabel = textLabel;

    styleVBox->setMargin (0);
    styleVBox->setSpacing (2);
    styleVBox->addWidget(iconLabel);
    styleVBox->addWidget(textLabel);

    widget->setFixedSize(72,58);

    widget->installEventFilter(this);

    return widget;
}

/**
 * @brief kpAIDrawingBar::addStyleLabel
 * 添加风格布局函数
 * @param iconPath
 * @param labelText
 * @param line
 * @return
 */
QWidget *kpAIDrawingBar::addStyleLabel(QString iconPath, QString labelText, int line)
{
    QWidget *widget = new QWidget();
    QVBoxLayout *styleVBox = new QVBoxLayout(widget);

    QLabel *iconLabel = new QLabel(this);
    iconLabel->setObjectName("iconLabel");
    iconLabel->setFixedSize(72,42);
    iconLabel->setPixmap(QPixmap(iconPath).scaled(112,64, Qt::KeepAspectRatio,Qt::SmoothTransformation));
    iconLabel->setScaledContents(true);
    iconLabel->setAlignment(Qt::AlignCenter);

    QLabel *textLabel = new QLabel(i18n(labelText.toLocal8Bit().data()), this);
    textLabel->setObjectName("textLabel");
    textLabel->setFixedSize(72,16);
    textLabel->setFont(QFont("Arial", 8));
    textLabel->setAlignment(Qt::AlignCenter);
    textLabel->setProperty("labelStyle", line);

    styleVBox->setMargin (0);
    styleVBox->setSpacing (2);
    styleVBox->addWidget(iconLabel);
    styleVBox->addWidget(textLabel);
    widget->setFixedSize(72,58);

    widget->installEventFilter(this);

    return widget;
}

/**
 * @brief kpAIDrawingBar::eventFilter
 * 事件重载回调函数
 * @param obj
 * @param event
 * @return
 */
bool kpAIDrawingBar::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress)
    {
        handleLabelClicked(obj);
        return true;
    }
    return QObject::eventFilter(obj, event);
}

/**
 * @brief kpAIDrawingBar::handleLabelClicked
 * 新增的槽函数，处理风格部分的点击事件
 * @param clickedObject
 */
void kpAIDrawingBar::handleLabelClicked(QObject *clickedObject)
{
    QWidget *clickedWidget = qobject_cast<QWidget*>(clickedObject);

    if (!clickedWidget){
        qDebug()<<"clickedWidget   is  null";
        return;
    }

    QLabel *iconLabel = clickedWidget->findChild<QLabel*>("iconLabel");
    QLabel *textLabel = clickedWidget->findChild<QLabel*>("textLabel");

    if (!iconLabel || !textLabel){
        qDebug()<<"clickedLable   is  null";
        return;
    }

    if(!selectedIconLabel || !selectedTextLabel){
        qDebug()<<"selectedIconLabel/selectedTextLabel is null";
        return;
    }

    if (selectedIconLabel != iconLabel) {
        selectedIconLabel->setStyleSheet("");
        selectedTextLabel->setStyleSheet("");
        selectedIconLabel = nullptr;
        selectedTextLabel = nullptr;
    }
    iconLabel->setStyleSheet("border: 2px solid #3790FA; border-radius: 5px;");
    textLabel->setStyleSheet("color: #3790FA;");
    selectedIconLabel = iconLabel;
    selectedTextLabel = textLabel;
    int identifier = textLabel->property("labelStyle").toInt();
    if (identifier > 9){
        identifier += 1;
    }
    ImageStyle = (VisionImageStyle)identifier;
}

QJsonArray kpAIDrawingBar::readResolutionsFromJson(QString key)
{
    if (!mSession)
        return QJsonArray();

    QString jsonString = QString(vision_get_prompt2image_supported_params(mSession));

    qDebug()<<"jsonString === "<<jsonString;

    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());

    if (!doc.isObject())
        return QJsonArray();

    QJsonObject obj = doc.object();
    if (!obj.contains(key.toLatin1().data()))
        return QJsonArray();

    return obj[key.toLatin1().data()].toArray();
}

int kpAIDrawingBar::readNumFromJson(QString key)
{
    if(!mSession)
        return 1;

    QString jsonString = QString(vision_get_prompt2image_supported_params(mSession));

    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8());

    if (!doc.isObject())
        return 1;

    QJsonObject obj = doc.object();
    if (!obj.contains(key.toLatin1().data()))
        return 1;

    return obj[key.toLatin1().data()].toInt();
}

void kpAIDrawingBar::addResolutionComboBox()
{
    QString resoKey = "resolution-ratio";
    QJsonArray resolutions = readResolutionsFromJson(resoKey);
    if (resolutions.isEmpty())
    {
        resolutionComboBox->addItem("512x512");
        return;
    }

    for (const QJsonValue &value : resolutions) {
        QString resolution = value.toString();
        resolutionComboBox->addItem(resolution);
    }

    connect(resolutionComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            [=](int index) {
                QString selectedResolution = resolutionComboBox->currentText();
                // 解析为QSize（这里假设分辨率总是"WxH"格式）
                int widthPos = selectedResolution.indexOf('x');
                qDebug()<<"index = "<<index<<selectedResolution<<widthPos;
                if (widthPos != -1) {
                    int width = selectedResolution.left(widthPos).toInt();
                    int height = selectedResolution.mid(widthPos + 1).toInt();
                    QSize size(width, height);
                    AIImageSize = size;
                }
                qDebug()<<"AIImageSize === "<<AIImageSize;
            });
}

void kpAIDrawingBar::addQuantityComboBox()
{
    QString numKey = "image-number";
    int num = readNumFromJson(numKey);
    if (num == 1){
        quantityComboBox->addItem("1张");
    }
    else if (num == 6){
        quantityComboBox->addItem("1张");
        quantityComboBox->addItem("2张");
        quantityComboBox->addItem("6张");
    }
    else if (num == 8){
        for (int i = 1; i <= num; i *= 2) {
            quantityComboBox->addItem(QString("%1张").arg(i));
        }
    }
    else {
        quantityComboBox->addItem("1张");
        qDebug()<<"读取生成数量不是常用数量, num = "<<num;
    }

    // 连接信号以处理分辨率变化
    connect(quantityComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            [=](int index) {
                QString selectedResolution = quantityComboBox->currentText();
                QString numberString = selectedResolution.remove(QRegExp("[^\\d]"));
                quantityNum = numberString.toInt();
                qDebug()<<"生成数量quantityNum = "<<quantityNum;
    });


}

/**
 * @brief kpAIDrawingBar::onGenerateButtonClicked
 * 立即生成按钮回调函数
 */
void kpAIDrawingBar::onGenerateButtonClicked()
{
    QString resultText = static_cast<QTextEdit *>(findChild<QTextEdit *>())->toPlainText();
    if(!resultText.isEmpty())
        textBox = resultText;

    qDebug() << "输入文字为：" << textBox;

    buildButton->setEnabled(false);
    buildButton->setText(i18n("In formation..."));
    buildButton->setStyleSheet(colorGrayButtonStyle);
    buildButtonFlag = true;
    if(!deleteButton->isEnabled())
        deleteButton->setEnabled(true);

    // 更新结果显示
    updateResultGrid();

    // 更新图像
    updateImageGrid();
}

/**
 * @brief kpAIDrawingBar::handleInputTextChanged
 * 文字输入回调函数
 */
void kpAIDrawingBar::handleInputTextChanged()
{
    //考虑添加生成中判断
    QString userText = static_cast<QTextEdit *>(findChild<QTextEdit *>())->toPlainText().trimmed();
    bool enableButton = !userText.isEmpty();
    if (enableButton && !buildButton->isEnabled() && !buildButtonFlag) {
        qDebug()<<"buildButton  set  true";
        buildButton->setEnabled(enableButton);
        buildButton->setStyleSheet(colorfulButtonStyle);
    }
    else if (!enableButton && buildButton->isEnabled()) {
        buildButton->setEnabled(enableButton);
        buildButton->setStyleSheet(colorGrayButtonStyle);
    }
}

/**
 * @brief kpAIDrawingBar::addPageAndStoreImages
 * 添加AI生成后的图片及页
 */
void kpAIDrawingBar::addPageAndStoreImages()
{
    // Create a new page
    QWidget *newPage = new QWidget();

    // Get the current set of images
    QVector<QPixmap> currentImages = imagesVector.last();

    QGridLayout *pageLayout = new QGridLayout(newPage);
    pageLayout->setMargin (2);
    pageLayout->setSpacing (5);
    if(show_quantityNum == 1){
        pageLayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    }
    else {
        pageLayout->setAlignment(Qt::AlignTop | Qt::AlignCenter);
    }

    for (int i = 0; i < currentImages.size(); ++i) {
        QPixmap pixmap = currentImages[i];
        setAiPixmap(pixmap, i, pageLayout);
    }
    stackedWidget->addWidget(newPage);
    stackedWidget->setCurrentIndex(stackedWidget->count() - 1);
    updatePageLabel();
}

/**
 * @brief kpAIDrawingBar::createPixmapWithText
 * 生成图片报错处理
 * @param text
 * @return
 */
QPixmap kpAIDrawingBar::createPixmapWithText(const QString &text)
{
    QSize size;
    size = getImageLabelSize();

    QPixmap pixmap(size);
    pixmap.fill(QColor("#E6E6E6"));

    QColor color("#B8B8B8");
    QPainter painter(&pixmap);

    // 设置字体和字体大小，这里假设使用默认字体，根据实际需求可自定义
    QFont font = painter.font();
    font.setPointSize(12);
    // 若需要调整字体大小以适应换行，请在此处设置，例如：font.setPointSize(10);

    QRect textRect = pixmap.rect().adjusted(8, 8, -8, -8);
    // 计算文本在给定宽度下的自动换行字符串
    QString wrappedText = fontMetrics().elidedText(i18n(text.toLocal8Bit().data()), Qt::ElideNone, textRect.width(), Qt::TextWordWrap);

    painter.setFont(font);
    painter.setPen(color);
    painter.drawText(textRect, Qt::AlignCenter | Qt::TextWordWrap, wrappedText);
    painter.end();

    qDebug()<<"Error message:"<<i18n(text.toLocal8Bit().data())<<"size = "<<size;
    return pixmap;
}

/**
 * @brief kpAIDrawingBar::AIGeneratesErrorHandling
 * 生成图片报错处理
 * @param errorCode
 * @return
 */
QPixmap kpAIDrawingBar::AIGeneratesErrorHandling(int errorCode)
{
    VisionResult visionError = (VisionResult)errorCode;
    QPixmap map;

    switch (visionError) {
    case VISION_SESSION_ERROR:
    case VISION_GENERATE_IMAGE_FAILED:
        map = createPixmapWithText("Generation error");
        break;
    case VISION_GENERATE_IMAGE_BLOCKED:
        map = createPixmapWithText("Text or style errors");
        break;
    case VISION_NET_ERROR:
        map = createPixmapWithText("Network error");
        break;
    case VISION_SERVER_ERROR:
        map = createPixmapWithText("Service error");
        break;
    case VISION_UNAUTHORIZED:
        map = createPixmapWithText("Unconfigured model");
        break;
    case VISION_REQUEST_FAILED:
        map = createPixmapWithText("Request failed");
        break;
    case VISION_TASK_TIMEOUT:
        map = createPixmapWithText("Task timeout");
        break;
    case VISION_INPUT_TEXT_LENGTH_INVAILD:
    case VISION_PARAM_ERROR:
        map = createPixmapWithText("Text length exceeds the limit");
        break;
//    case VISION_PARAM_ERROR:
//        map = createPixmapWithText("Parameter error");
//        break;
    default:
        map = createPixmapWithText("Generation error");
        break;
    }
    return map;

}

/**
 * @brief kpAIDrawingBar::onThreadFinished
 * AI生成后，线程的回调函数
 * @param flag
 * @param pixmap
 * @param imageIndex
 * @param imageSum
 * @param errorCode
 */
void kpAIDrawingBar::onThreadFinished(bool flag, QPixmap pixmap, int imageIndex, int imageSum, int errorCode)
{
    // 可以调用主进程的函数等
    QPixmap map;
    if(!flag){
        deleteImageGridWidget();
        deleteButtonFlag = true;
        deleteButton->setEnabled(true);
        return;
    }
    if (imageIndex == 0){
        imagesVector.append(QVector<QPixmap>());
    }
    if (errorCode != 0)
        map = AIGeneratesErrorHandling(errorCode);
    else
        map = pixmap;

    if (imagesVector.size() > 0 ){
        imagesVector.last().append(map);
    }
    qDebug()<<"onThreadFinished: imageIndex = "<<imageIndex<<"imageSum = "<<imageSum<<"errorCode = "<<errorCode;
    if (imageIndex + 1 == imageSum || imageSum == 0){
        buildButton->setEnabled(true);
        buildButton->setText(i18n("Generate now"));
        buildButton->setStyleSheet(colorfulButtonStyle);//设置立即生成按钮为立即生成
        buildButtonFlag = false;
        addPageAndStoreImages();
    }
}


AIModeDataThread::AIModeDataThread()
{

}

AIModeDataThread::~AIModeDataThread()
{
    vision_destory_session(session);
}

bool AIModeDataThread::setSessionStatus()
{
    if (m_sessionFlag)
        return true;

    session = nullptr;
    VisionResult ret = vision_create_session(&session);
    if (ret != VISION_SUCCESS) {
        qDebug()<<"创建失败VisionResult="<<ret
                <<"ErrorMessage:"<<vision_get_last_error_message();
        sendErrorSignal(ret);
        m_sessionFlag = false;
        return false;
    }

    VisionResult initRet = vision_init_session(session);
    if (initRet != VISION_SUCCESS) {
        qDebug()<<"初始化失败 VisionResult="<<initRet
                <<"ErrorMessage:"<<vision_get_last_error_message();
        sendErrorSignal(initRet);
        m_sessionFlag = false;
        return false;
    }
    m_sessionFlag = true;
    return true;
}

/**
 * @brief AIModeDataThread::generateImageCallback
 * AI生成后回调函数
 * @param imageData
 * @param userData
 */
void AIModeDataThread::generateImageCallback(VisionImageData imageData, void* userData){

    qDebug()<<"AI生成回调函数: length:"<<imageData.data_size
            <<"imageIndex："<<imageData.index
            <<"imageSum"<<imageData.total
            <<"imageError="<<imageData.error_code
            <<"Image format:"<< imageData.format;

    AIModeDataThread *AIMode = (AIModeDataThread *)userData;
    QPixmap map;
    map.loadFromData(imageData.data, imageData.data_size);
    qDebug()<<"textBox ===== "<<AIMode->textBox;
    if(imageData.index == 0)
        emit AIMode->finishedSignal(false, map, imageData.index, imageData.total, imageData.error_code);
    emit AIMode->finishedSignal(true, map, imageData.index, imageData.total, imageData.error_code);
}

/**
 * @brief AIModeDataThread::someFunctionInThread
 * AI服务调用函数
 * @return
 */
bool AIModeDataThread::someFunctionInThread()
{
    int width = AIImageSize.width();
    int height = AIImageSize.height();

    vision_set_prompt2image_number(session, quantityNum);
    vision_set_prompt2image_size(session, width, height);
    vision_set_prompt2image_callback(session, generateImageCallback, this);
    vision_set_prompt2image_style(session, ImageStyle);

    VisionResult imageRet = vision_prompt2image_async(session, textBox.toLocal8Bit().data());

    qDebug()<<"ImageStyle == "<<ImageStyle;
    if (imageRet != VISION_SUCCESS) {
        qDebug()<<"文字输入失败,VisionResult="<<imageRet
                <<"ErrorMessage:"<<vision_get_last_error_message();
        sendErrorSignal(imageRet);
        return false;
    }
    return true;
}

/**
 * @brief kpAIDrawingBar::getImageLabelSize
 * 获取显示图片区域QLabel的大小
 * @return
 */
QSize kpAIDrawingBar::getImageLabelSize()
{
    imageColumn = 2;
    QSize labelSize = QSize(108,108);
    double ratio = static_cast<double>(showAIImageSize.width()) / static_cast<double>(108);
    int height = showAIImageSize.height() / ratio;

    if (height != 0)
        labelSize = QSize(108, height);

    qDebug()<<"getImageLabelSize   labelSize = "<<labelSize;
    return labelSize;
}

/**
 * @brief kpAIDrawingBar::setAiPixmap
 * 将AI生成的图片更新到QLabel中，并加入回调可以传输图片到画图中
 * @param pixmap
 * @param imageIndex
 * @param pageLayout
 */
void kpAIDrawingBar::setAiPixmap(QPixmap pixmap, int imageIndex, QGridLayout *pageLayout)
{

    QSize labelSize = getImageLabelSize();
    QPixmap scalePix =  pixmap.scaled(labelSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    imageClickableLabel *imageLabel = new imageClickableLabel(pixmap, this);

    imageLabel->setPixmap(scalePix);

    imageLabel->setFixedSize(labelSize);
    pageLayout->addWidget(imageLabel, imageIndex / imageColumn, imageIndex % imageColumn);
    connect(imageLabel, &imageClickableLabel::labelClicked, this, &kpAIDrawingBar::handleLabelClick);
}

/**
 * @brief kpAIDrawingBar::deleteImageGridWidget
 * 清空上一次生成的图像函数，主要是等待转圈参数
 */
void kpAIDrawingBar::deleteImageGridWidget()
{
    // 清空之前的图像
    if(stackedWidget->count() > 0 ){
        QWidget *w = stackedWidget->widget(stackedWidget->count() - 1);
        stackedWidget->removeWidget(w);
        w->deleteLater();
    }
    updatePageLabel();
}

/**
 * @brief kpAIDrawingBar::updatePageLabel
 * 更新换页页码函数
 */
void kpAIDrawingBar::updatePageLabel()
{
    currentPageIndx = stackedWidget->currentIndex();
    pageLabel->setText(QString("%1/%2").arg(currentPageIndx + 1).arg(stackedWidget->count()));
}

/**
 * @brief kpAIDrawingBar::showPreviousPage
 * 上一页回调函数
 */
void kpAIDrawingBar::showPreviousPage()
{
    if (stackedWidget->count() > 1 && currentPageIndx > 0) {
        currentPageIndx--;
        stackedWidget->setCurrentIndex(currentPageIndx);
        updatePageLabel();
    }
    else if (stackedWidget->count() > 1 && currentPageIndx == 0) {
        currentPageIndx = stackedWidget->count() - 1;
        stackedWidget->setCurrentIndex(currentPageIndx);
        updatePageLabel();
    }
    setEnabledDeleteButton();
    qDebug()<<"stackedWidget->count() = "<<stackedWidget->count()<<"currentPageIndx="<<currentPageIndx;
}

/**
 * @brief kpAIDrawingBar::showNextPage
 * 下一页回调函数
 */
void kpAIDrawingBar::showNextPage()
{
    if (stackedWidget->count() > 1 && currentPageIndx < stackedWidget->count() - 1) {
        currentPageIndx++;
        stackedWidget->setCurrentIndex(currentPageIndx);
        updatePageLabel();
    }
    else if (stackedWidget->count() > 1 && currentPageIndx == stackedWidget->count() - 1) {
        currentPageIndx = 0;
        stackedWidget->setCurrentIndex(currentPageIndx);
        updatePageLabel();
    }
    setEnabledDeleteButton();
    qDebug()<<"stackedWidget->count() = "<<stackedWidget->count()<<"currentPageIndx="<<currentPageIndx;
}

void kpAIDrawingBar::deleteCurrentPage()
{
    stackedWidget->removeWidget(stackedWidget->currentWidget());
    updatePageLabel();
    if(stackedWidget->count() <= 1){
        updateResultGrid();
        if (currentPageIndx == -1)
            deleteButton->setEnabled(false);
        else
            setEnabledDeleteButton();
    }
    else {
        setEnabledDeleteButton();
    }
}

void kpAIDrawingBar::setEnabledDeleteButton()
{
    qDebug()<<"currentPageIndx == "<<currentPageIndx;
    if(!deleteButtonFlag && currentPageIndx == stackedWidget->count() - 1){
        deleteButton->setEnabled(false);
    }
    else {
        deleteButton->setEnabled(true);
    }
}
void kpAIDrawingBar::updateResultGrid()
{
    qDebug()<<"updateResultGrid: stackedWidget->count() === "<<stackedWidget->count();
    // 显示resultGrid中的所有子控件
    for (int i = 0; i < resultGrid->count(); ++i)
    {
        QLayoutItem *item = resultGrid->itemAt(i);;
        if (stackedWidget->count() < 1 && (i == 2 || i == 3 || i ==4)){
            if (item && item->widget()){
                item->widget()->setVisible(false);
            }
            continue;
        }
        if (item && item->widget()){
            item->widget()->setVisible(true);
        }
    }
}

/**
 * @brief kpAIDrawingBar::updateImageGrid
 * 更新、等待QLabel相关界面，并开启线程运行
 */
void kpAIDrawingBar::updateImageGrid()
{
    show_quantityNum = quantityNum;
    showAIImageSize = AIImageSize;

    QSize labelSize = getImageLabelSize();

    QWidget *newWidget = new QWidget();
    QGridLayout *pageLayout = new QGridLayout(newWidget);

    pageLayout->setMargin (2);
    pageLayout->setSpacing (5);
    if(show_quantityNum == 1){
        pageLayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    }
    else {
        pageLayout->setAlignment(Qt::AlignTop | Qt::AlignCenter);
    }

    for(int i = 0; i < quantityNum; i++){
        QLabel *label = new QLabel();
        movie = new QMovie(LOADING_IMAGE);
        if (quantityNum == 1)
            movie->setScaledSize(QSize(50,50));
        else
            movie->setScaledSize(QSize(30,30));
        label->setMovie(movie);
        movie->start();
        label->setStyleSheet("QLabel {"
                             "background-color: #E6E6E6;"
                             "border-radius: 5px;}");

        label->setFixedSize(labelSize);
        label->setAlignment(Qt::AlignCenter);
        pageLayout->addWidget(label, i / imageColumn, i % imageColumn, Qt::AlignTop);
    }

    stackedWidget->addWidget(newWidget);
    stackedWidget->setCurrentIndex(stackedWidget->count() - 1);

    qDebug()<<"updateImageGrid : currentPageIndx = "<<currentPageIndx + 1<<stackedWidget->count();
    updatePageLabel();

    deleteButtonFlag = false;
    deleteButton->setEnabled(false);

    qDebug()<<textBox<<AIImageSize <<quantityNum<<ImageStyle;

    startThread();
}

/**
 * @brief kpAIDrawingBar::handleLabelClick
 * 图像点击回调信号，用于传输图片到画图中
 * @param pixmap
 */
void kpAIDrawingBar::handleLabelClick(const QPixmap &pixmap)
{
    // 在这里处理图像被点击的事件，可以调用XXX函数，传递图像数据
    emit imageClicked(pixmap);
}
