#include "cloudmodelconfigwidget.h"

#include <ukui-log4qt.h>
#include <QCoreApplication>

CloudModelConfigWidget::CloudModelConfigWidget(QWidget *parent) : QDialog(parent)
{
    // 初始化布局
    initLayout();

    // 加载已配置的模型并显示
    loadModelConfig();

    // 初始化信号槽
    initConnect();
}

CloudModelConfigWidget::~CloudModelConfigWidget()
{
    m_nlpModelMap.clear();
    m_visionModelMap.clear();
    m_speechModelMap.clear();

    // 删除ModelItem对象
    for (ModelItem* item : m_nlpModelItemMap) {
        if (item) {
            delete item;
            item = nullptr;
        }
    }
    m_nlpModelItemMap.clear();

    for (ModelItem* item : m_visionModelItemMap) {
        if (item) {
            delete item;
            item = nullptr;
        }
    }
    m_visionModelItemMap.clear();

    for (ModelItem* item : m_speechModelItemMap) {
        if (item) {
            delete item;
            item = nullptr;
        }
    }
    m_speechModelItemMap.clear();

    m_nlpModelItemList.clear();
    m_visionModelItemList.clear();
    m_speechModelItemList.clear();

    m_nlpModelGroup->removeAndDeleteAllWidget();
    m_visionModelGroup->removeAndDeleteAllWidget();
    m_speechModelGroup->removeAndDeleteAllWidget();

    m_nlpModelMapUI.clear();
    m_visionModelMapUI.clear();
    m_speechModelMapUI.clear();
}

void CloudModelConfigWidget::initLayout()
{
    this->setFixedSize(544, 610);
    this->setWindowTitle(tr("Cloud model"));

    m_mainVLayout = new QVBoxLayout();

    initModelTitleLayout();
    initModellayout();

    m_mainVLayout->setStretch(0,2);
    m_mainVLayout->setStretch(1,8);
    this->setLayout(m_mainVLayout);
}

void CloudModelConfigWidget::initModelTitleLayout()
{
    QWidget* backgroundWidget = new QWidget(this);
    backgroundWidget->setAccessibleName("kylin-ai-subsystem-modelconfig_QWidget_backgroundWidget");
    backgroundWidget->setFixedHeight(72);
    backgroundWidget->setStyleSheet("background-image: url(:/res/icon/background.svg); background-repeat: no-repeat; background-position: center;");
    m_titleHLayout = new QHBoxLayout(backgroundWidget);

    m_vLeftLayout = new QVBoxLayout();
    m_iconLabel = new QLabel(backgroundWidget);
    m_iconLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_m_iconLabel");
    QPixmap iconPixmap(":/res/icon/ukui-cloud-model-symbolic.svg");
    if(!iconPixmap.isNull())
    {   iconPixmap = iconPixmap.scaled(24, 24, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        m_iconLabel->setPixmap(iconPixmap);
    }
    m_iconLabel->setFixedSize(24, 24);
    m_iconLabel->setStyleSheet("background: transparent;");
    m_iconLabel->setAlignment(Qt::AlignCenter);
    m_iconLabel->setContentsMargins(16, 24, 0, 24);
    m_vLeftLayout->setContentsMargins(16, 0, 0, 0);
    m_vLeftLayout->addWidget(m_iconLabel);

    m_cloudHLayout = new QVBoxLayout();
    m_cloudLabel = new QLabel(backgroundWidget);
    m_cloudLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_m_cloudLabel");
    m_cloudLabel->setFixedSize(216, 24);
    m_cloudLabel->setText(tr("Cloud Model"));
    QFont cloudFont;
    cloudFont.setBold(true);
    m_cloudLabel->setFont(cloudFont);
    m_cloudLabel->setStyleSheet("color: #3790FA; background: transparent;");

    m_descripLabel = new kdk::KLabel(backgroundWidget);
    m_descripLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_m_descripLabel");
    m_descripLabel->setFixedSize(450, 20);
    m_descripLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    m_descripLabel->setWordWrap(true);
    m_descripLabel->setMinimumHeight(30); // 增加高度，防止文字被截断

    m_descripLabel->setText(tr("Deployed on the cloud server, access and use over the network"));
    QFont cloudDescripFont;
    cloudDescripFont.setPointSize(cloudFont.pointSize() - 2);
    m_descripLabel->setFont(cloudDescripFont);
    m_descripLabel->setFontColor("#3790FA");
    m_descripLabel->setStyleSheet("background: transparent;");

    m_cloudHLayout->addWidget(m_cloudLabel);
    m_cloudHLayout->addWidget(m_descripLabel);
    m_cloudHLayout->setContentsMargins(0, 4, 232, 8);


    m_titleHLayout->addLayout(m_vLeftLayout);
    m_titleHLayout->addLayout(m_cloudHLayout);

    m_mainVLayout->addWidget(backgroundWidget);
}


void CloudModelConfigWidget::initModellayout()
{
    m_baseVLayout = new QVBoxLayout;
    m_baseVLayout->setContentsMargins(0, 30, 0, 0);

    // NLP大语言模型
    m_nlpWidget = new QWidget;
    m_nlpWidget->setAccessibleName("kylin-ai-subsystem-modelconfig_QWidget_m_nlpWidget");

    m_nlpVLayout = new QVBoxLayout;
    m_nlpVLayout->setContentsMargins(0, 0, 0, 0);
    m_nlpVLayout->setSpacing(4);
    m_nlpHLayout = new QHBoxLayout;
    m_nlpHLayout->setContentsMargins(16, 0, 16, 0);

    // NLP标题
    QFont font;
    font.setBold(true); // 设置字体加粗

    // 设置QLabel的字体
    m_nlpLabel = new QLabel;
    m_nlpLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_m_nlpLabel");
    m_nlpLabel->setText(tr("NLP Model"));
    m_nlpLabel->setFont(font);

    // NLP描述
    m_nlpDescLabel = new kdk::KLabel(this);
    m_nlpDescLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_kdk::KLabel_m_nlpDescLabel");
    m_nlpDescLabel->setText(tr("Processing and generating text, such as understanding text and answering questions"));
    m_nlpDescLabel->setFixedWidth(402);
    m_nlpDescLabel->setFontColor("#808080");

    // 标题和描述放入布局
    m_nlpDescVLayout  = new QVBoxLayout();
    m_nlpDescVLayout->setSpacing(0);
    m_nlpDescVLayout->addWidget(m_nlpLabel);
    m_nlpDescVLayout->addWidget(m_nlpDescLabel);

    // 添加按钮
    m_nlpAddButton = new kdk::KBorderlessButton;
    m_nlpAddButton->setAccessibleName("kylin-ai-subsystem-modelconfig_kdk::KBorderlessButton_m_nlpAddButton");
    m_nlpAddButton->setFixedSize(60, 28);
    m_nlpAddButton->setIcon(QIcon::fromTheme("list-add-symbolic"));
    m_nlpAddButton->setIconSize(QSize(16, 16));
    m_nlpAddButton->setText(tr("Add"));

    // 已配置模型
    m_nlpModelGroup = new SettingGroup(m_nlpWidget, QFrame::NoFrame, UkccFrame::None, 4);
    m_nlpModelGroup->setAccessibleName("kylin-ai-subsystem-modelconfig_SettingGroup_m_nlpModelGroup");

    m_freeTrialModelGroup = new SettingGroup(m_nlpWidget);
    m_freeTrialModelGroup->setAccessibleName("kylin-ai-subsystem-modelconfig_SettingGroup_m_freeTrialModelGroup");

    m_nlpHLayout->addLayout(m_nlpDescVLayout);
    m_nlpHLayout->addStretch();
    m_nlpHLayout->addWidget(m_nlpAddButton);

    m_nlpVLayout->addLayout(m_nlpHLayout);
    m_nlpVLayout->addWidget(m_freeTrialModelGroup);
    m_nlpVLayout->addWidget(m_nlpModelGroup);

    m_nlpWidget->setLayout(m_nlpVLayout);

    // VISION视觉模型
    m_visionWidget = new QWidget;
    m_visionWidget->setAccessibleName("kylin-ai-subsystem-modelconfig_QWidget_m_visionWidget");

    m_visionVLayout = new QVBoxLayout;
    m_visionVLayout->setContentsMargins(0, 0, 0, 0);
    m_visionHLayout = new QHBoxLayout;
    m_visionHLayout->setContentsMargins(16, 0, 16, 0);

    // VISION标题
    m_visionLabel = new QLabel;
    m_visionLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_m_visionLabel");
    m_visionLabel->setText(tr("Visual Model"));
    m_visionLabel->setFont(font);

    // VISION描述
    m_visionDescrLabel = new kdk::KLabel(this);
    m_visionDescrLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_kdk::KLabel_m_visionDescrLabel");
    m_visionDescrLabel->setText(tr("Processing and generating images, such as recognizing objects and analyzing scenes"));
    m_visionDescrLabel->setFixedWidth(402);
    m_visionDescrLabel->setFontColor("#808080");

    // 标题和描述放入布局
    m_visionDescVLayout  = new QVBoxLayout();
    m_visionDescVLayout->setSpacing(0);
    m_visionDescVLayout->addWidget(m_visionLabel);
    m_visionDescVLayout->addWidget(m_visionDescrLabel);

    // 添加按钮
    m_visionAddButton = new kdk::KBorderlessButton;
    m_visionAddButton->setAccessibleName("kylin-ai-subsystem-modelconfig_kdk::KBorderlessButton_m_visionAddButton");
    m_visionAddButton->setFixedSize(60, 28);
    m_visionAddButton->setIcon(QIcon::fromTheme("list-add-symbolic"));
    m_visionAddButton->setIconSize(QSize(16, 16));
    m_visionAddButton->setText(tr("Add"));

    // 已配置模型
    m_visionModelGroup = new SettingGroup;
    m_visionModelGroup->setAccessibleName("kylin-ai-subsystem-modelconfig_SettingGroup_m_visionModelGroup");
    m_visionHLayout->addLayout(m_visionDescVLayout);
    m_visionHLayout->addStretch();
    m_visionHLayout->addWidget(m_visionAddButton);

    m_visionVLayout->addLayout(m_visionHLayout);
    m_visionVLayout->addWidget(m_visionModelGroup);

    m_visionWidget->setLayout(m_visionVLayout);

    // SPEECH语音模型
    m_speechWidget = new QWidget;
    m_speechWidget->setAccessibleName("kylin-ai-subsystem-modelconfig_QWidget_m_speechWidget");
    m_speechVLayout = new QVBoxLayout;
    m_speechVLayout->setContentsMargins(0, 0, 0, 0);
    m_speechHLayout = new QHBoxLayout;
    m_speechHLayout->setContentsMargins(16, 0, 16, 0);

    // SPEECH标题
    m_speechLabel = new QLabel;
    m_speechLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_m_speechLabel");
    m_speechLabel->setText(tr("Speech Model"));
    m_speechLabel->setFont(font);

    // SPEECH描述
    m_speechDescLabel = new kdk::KLabel(this);
    m_speechDescLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_kdk::KLabel_m_speechDescLabel");
    m_speechDescLabel->setText(tr("Processing sound and speech, such as recognizing speech and synthesizing speech"));
    m_speechDescLabel->setFixedWidth(402);
    m_speechDescLabel->setFontColor("#808080");

    // 标题和描述放入布局
    m_speechDescVlayout  = new QVBoxLayout();
    m_speechDescVlayout->setSpacing(0);
    m_speechDescVlayout->addWidget(m_speechLabel);
    m_speechDescVlayout->addWidget(m_speechDescLabel);

    // 添加按钮
    m_speechAddButton = new kdk::KBorderlessButton;
    m_speechAddButton->setAccessibleName("kylin-ai-subsystem-modelconfig_kdk::KBorderlessButton_m_speechAddButton");
    m_speechAddButton->setFixedSize(60, 28);
    m_speechAddButton->setIcon(QIcon::fromTheme("list-add-symbolic"));
    m_speechAddButton->setIconSize(QSize(16, 16));
    m_speechAddButton->setText(tr("Add"));

    // 已配置模型
    m_speechModelGroup = new SettingGroup;
    m_speechModelGroup->setAccessibleName("kylin-ai-subsystem-modelconfig_SettingGroup_m_speechModelGroup");
    m_speechHLayout->addLayout(m_speechDescVlayout);
    m_speechHLayout->addStretch();
    m_speechHLayout->addWidget(m_speechAddButton);

    m_speechVLayout->addLayout(m_speechHLayout);
    m_speechVLayout->addWidget(m_speechModelGroup);

    m_speechWidget->setLayout(m_speechVLayout);

    // 滚动区域
    m_scrollVLayout = new QVBoxLayout;
    m_scrollVLayout->setContentsMargins(16, 20, 16, 0);
    m_scrollVLayout->addWidget(m_nlpWidget);
    m_scrollVLayout->addWidget(m_visionWidget);
    m_scrollVLayout->addWidget(m_speechWidget);
    m_scrollVLayout->addStretch();

    m_scrollWidget = new QWidget;
    m_scrollWidget->setAccessibleName("kylin-ai-subsystem-modelconfig_QWidget_m_speechWidget");
    m_scrollWidget->setContentsMargins(0, 0, 0, 0);
    m_scrollWidget->setLayout(m_scrollVLayout);

    m_scrollArea = new QScrollArea(this);
    m_scrollArea->setAccessibleName("kylin-ai-subsystem-modelconfig_QScrollArea_m_scrollArea");
    m_scrollArea->setFixedHeight(420);
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setFrameStyle(QFrame::NoFrame); // 无边框
    m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // 不显示水平滚动条
    m_scrollArea->verticalScrollBar()->setContextMenuPolicy(Qt::NoContextMenu);
    m_scrollArea->verticalScrollBar()->setProperty("drawScrollBarGroove", false);

    m_scrollArea->setWidget(m_scrollWidget);
    m_mainVLayout->addWidget(m_scrollArea);

    m_confirmWidget = new QWidget(this);
    m_confirmWidget->setAccessibleName("kylin-ai-subsystem-modelconfig_QWidget_m_confirmWidget");
    m_confirmButton = new QPushButton(tr("OK"), this);
    m_confirmButton->setAccessibleName("kylin-ai-subsystem-modelconfig_QPushButton_m_confirmButton");
    m_confirmButton->setProperty("isImportant", true);
    m_confirmButtoLayout = new QHBoxLayout();
    m_confirmButtoLayout->setContentsMargins(0, 0, 24, 24);
    m_confirmButtoLayout->addStretch();
    m_confirmButtoLayout->addWidget(m_confirmButton);
    m_confirmWidget->setLayout(m_confirmButtoLayout);
    m_mainVLayout->addStretch();
    m_mainVLayout->addWidget(m_confirmWidget);
}

void CloudModelConfigWidget::initConnect()
{
    connect(m_nlpAddButton, &QPushButton::clicked, this, [this](){
        this->nlpAddModelItem();
    });
    connect(m_visionAddButton, &QPushButton::clicked, this, [this](){
        this->visionAddModelItem();
    });
    connect(m_speechAddButton, &QPushButton::clicked, this, [this](){
        this->speechAddModelItem();
    });
    connect(m_confirmButton, &QPushButton::clicked, this, [this](){
        this->close();
    });

}

void CloudModelConfigWidget::nlpAddModelItem()
{
   // 设置为随父窗口居中
   ModelConfigDialog settingDialog(this);
   settingDialog.initUIData(AiCapability::Nlp ,DeployType::PublicCloud);
   settingDialog.exec();
}

void CloudModelConfigWidget::visionAddModelItem()
{
    // 设置为随父窗口居中
    ModelConfigDialog settingDialog(this);
    settingDialog.initUIData(AiCapability::Vision,DeployType::PublicCloud);
    settingDialog.exec();
}

void CloudModelConfigWidget::speechAddModelItem()
{
    ModelConfigDialog settingDialog(this);
    settingDialog.initUIData(AiCapability::Speech,DeployType::PublicCloud);
    settingDialog.exec();
}

bool CloudModelConfigWidget::eventFilter(QObject *watched, QEvent *event)
{
    Q_UNUSED(watched);

    // 模型配置
    ModelItem *clickedModelItem = qobject_cast<ModelItem*>(watched);

    if (clickedModelItem) {

        if (event->type() == QEvent::MouseButtonRelease) {

            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

            if (mouseEvent->button() == Qt::LeftButton) { // 判断左键
               // 切换模型
                clickCloudModel(clickedModelItem->getAICapability(), clickedModelItem->getModelName());
                return true;
            }
        }
    }

    return QWidget::eventFilter(watched,event);
}

void CloudModelConfigWidget::clickCloudModel(AiCapability capability, QString modelName)
{
    //KyInfo() << "正要切换到" << static_cast<int>(capability) << modelName ;
    //KyInfo() << "当前正在回答的选中模型为" << nlpSelectedModel;
    bool ret = checkModelSelection(capability, modelName);
    if (ret == true) {
        return;
    } else {
        if ((capability == AiCapability::Nlp &&  (getModelStatus(nlpSelectedModel) == ModelStatus::Running))
                || (capability == AiCapability::Vision &&  (getModelStatus(visionSelectedModel) == ModelStatus::Running))
                || (capability == AiCapability::Speech &&  (getModelStatus(speechSelectedModel) == ModelStatus::Running))) {
            // NLP or VISION or SPEECH 正在使用
            KyInfo() << "正在使用" << static_cast<int>(capability);
            bool canProceed = showModelInUseMessage(this);
            if (canProceed == true) {
                clickCloudModel(capability, modelName);
            } else {
                 KyInfo() << "取消本次操作";
                return;
            }
        } else {
            bool ret = setSelectCloudModelName(capability, DeployType::PublicCloud, modelName);
            if (ret == true) {
                switchModelItem(capability, modelName);
                KyInfo() << modelName << " 设置为选中模型成功";
            } else {
                showErrorMessage(tr("Model switching failed"),this);
                KyInfo() << modelName << " 设置为选中模型失败";
            }
        }

    }
}

void CloudModelConfigWidget::loadModelConfig()
{
    // 清空modelmap所有控件
    m_nlpModelMap.clear();
    m_visionModelMap.clear();
    m_speechModelMap.clear();

    // 删除ModelItem对象
    for (ModelItem* item : m_nlpModelItemMap) {
        if (item) {
            delete item;
            item = nullptr;
        }
    }
    m_nlpModelItemMap.clear();

    for (ModelItem* item : m_visionModelItemMap) {
        if (item) {
            delete item;
            item = nullptr;
        }
    }
    m_visionModelItemMap.clear();

    for (ModelItem* item : m_speechModelItemMap) {
        if (item) {
            delete item;
            item = nullptr;
        }
    }
    m_speechModelItemMap.clear();

    m_nlpModelItemList.clear();
    m_visionModelItemList.clear();
    m_speechModelItemList.clear();

    m_nlpModelGroup->removeAndDeleteAllWidget();
    m_visionModelGroup->removeAndDeleteAllWidget();
    m_speechModelGroup->removeAndDeleteAllWidget();

    m_nlpModelMapUI.clear();
    m_visionModelMapUI.clear();
    m_speechModelMapUI.clear();

    addFreeTrialTitleItem();
    loadModels();
    hideTrialList();
}

void CloudModelConfigWidget::loadModels() {
    loadFreeTrialModels();
    loadNoFreeModels();
}

void CloudModelConfigWidget::loadNoFreeModels() {
    ModelConfig mc;
    std::string nlpModel = mc.getCurrentModelName(AiCapability::Nlp, DeployType::PublicCloud);
    std::string visionModel = mc.getCurrentModelName(AiCapability::Vision, DeployType::PublicCloud);
    std::string speechModel = mc.getCurrentModelName(AiCapability::Speech, DeployType::PublicCloud);

    KyInfo() << "loadModelConfig-------------getCurrentModelName" << "nlpModel" << QString::fromStdString(nlpModel) << "visionModel" << QString::fromStdString(visionModel) <<"speechModel" << QString::fromStdString(speechModel);

    nlpSelectedModel = QString::fromStdString(nlpModel);
    visionSelectedModel = QString::fromStdString(visionModel);
    speechSelectedModel = QString::fromStdString(speechModel);

    for (auto capability : {AiCapability::Nlp, AiCapability::Vision, AiCapability::Speech}) {
        const auto models = mc.getExtendedModels(capability);
        for (const auto &model : models) {
            //过滤云端模型
            if(model.deployType == DeployType:: PublicCloud)
            {
                PublicCloudModel publicCloudModel;
                publicCloudModel.capability = model.capability;
                publicCloudModel.vendor = QString::fromStdString(model.vendor);
                publicCloudModel.modelName = QString::fromStdString(model.modelName);
                publicCloudModel.multiAuths  = mc.getModelAuthentications(model.modelName);

                KyInfo() << "loadModelConfig模型名称" <<  QString::fromStdString(model.modelName);
                KyInfo() <<  "loadModelConfig厂商" << QString::fromStdString(model.vendor);
                for (const auto &authen : publicCloudModel.multiAuths) {
                    for (const auto &au : authen.authentications) {
                        if (au.key == "appIdContinuous" || au.key == "apiKeyContinuous" || au.key == "secretKeyContinuous") {
                            if (au.value != "") {
                                continuousSelected = true;
                            }
                        } else if (au.key == "appIdRealTime" || au.key == "apiKeyRealTime") {
                            if (au.value != "") {
                                realtimeSelected = true;
                            }
                        }
                    }
                }

                switch (capability) {
                case AiCapability::Nlp:
                    loadModelItem(publicCloudModel, nlpSelectedModel);
                    break;
                case AiCapability::Vision:
                    loadModelItem(publicCloudModel, visionSelectedModel);
                    break;
                case AiCapability::Speech:
                    loadModelItem(publicCloudModel, speechSelectedModel);
                    break;
                default:
                    break;
                }
            }
        }
    }
}

void CloudModelConfigWidget::addFreeTrialTitleItem() {
    UkccFrame *itemFrame = new UkccFrame;
    itemFrame->setAccessibleName("kylin-ai-subsystem-modelconfig_UkccFrame_itemFrame");
    itemFrame->setMinimumWidth(496);
    itemFrame->setMaximumWidth(496);
    itemFrame->setFixedHeight(56);

    m_freeTrialLabel = new QLabel(this);
    m_freeTrialLabel->setAccessibleName("kylin-ai-subsystem-modelconfig_QLabel_freeTrialLabel");
    m_freeTrialLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    m_freeTrialLabel->setText(tr("Free Trial Account"));

    QHBoxLayout *hLayout = new QHBoxLayout(itemFrame);
    hLayout->setContentsMargins(16, 10, 6, 10);
    hLayout->addWidget(m_freeTrialLabel);
    hLayout->addStretch();

    m_showOrHideTrialListButton = new QToolButton(itemFrame);
    m_showOrHideTrialListButton->setAccessibleName("kylin-ai-subsystem-modelconfig_QToolButton_showOrHideTrialListButton");
    m_showOrHideTrialListButton->setFixedSize(38, 38);
    m_showOrHideTrialListButton->setIcon(QIcon::fromTheme("ukui-down-symbolic"));
    m_showOrHideTrialListButton->setProperty("useButtonPalette", true);
    m_showOrHideTrialListButton->setAutoRaise(true);
    hLayout->addWidget(m_showOrHideTrialListButton);

    connect(m_showOrHideTrialListButton, &QToolButton::clicked, this, [this]() {
        m_isExpendState = !m_isExpendState;
        m_isExpendState ? showTrialList() : hideTrialList();
    });

    m_freeTrialModelGroup->addWidget(itemFrame);
}

void CloudModelConfigWidget::loadFreeTrialModels() {
    ModelConfig mc;
    std::vector<Model> models =
        mc.getFreeTrialModels(kyai::config::model::AiCapability::Nlp);
    QString curModelName =
        mc.getCurrentModelName(AiCapability::Nlp, DeployType::PublicCloud).c_str();

    for (const auto &model : models) {
        PublicCloudModel publicCloudModel;
        publicCloudModel.modelName = QString::fromStdString(model.modelName);
        if (publicCloudModel.modelName.isEmpty()) {
            KyInfo() << "Free trial account model name is empty !";
            continue;
        }
        loadFreeTrialModelItem(publicCloudModel,
                               publicCloudModel.modelName == curModelName);
    }
}

void CloudModelConfigWidget::loadFreeTrialModelItem(PublicCloudModel model, bool isSelected) {
    QString modelName = model.modelName;
    UkccFrame *itemFrame = new UkccFrame;
    itemFrame->setAccessibleName("kylin-ai-subsystem-modelconfig_UkccFrame_itemFrame");
    itemFrame->setMinimumWidth(496);
    itemFrame->setMaximumWidth(496);
    itemFrame->setFixedHeight(56);
    itemFrame->setObjectName(modelName);
    QHBoxLayout *layItem = new QHBoxLayout(itemFrame);
    layItem->setContentsMargins(0, 0, 0, 0);

    ModelItem *item = new ModelItem(AiCapability::Nlp, modelName, true, this);
    item->setAccessibleName("kylin-ai-subsystem-modelconfig_ModelItem_item");
    if (isSelected) {
        item->showSelectedIcon(true);
    }
    item->installEventFilter(this);
    layItem->addWidget(item);

    // 删除被选中模型后,剩下模型中设置列表第一个为选中
    // 点击免费账号显示隐藏按钮,从列表获取免费模型，设置显示与隐藏
    m_nlpModelItemList.append(item);
    // 点击切换模型时，需要通过m_nlpModelItemMap保存的modelName进行确认
    m_nlpModelItemMap[modelName] = item;

    m_freeTrialModelGroup->addWidget(itemFrame);
}

void CloudModelConfigWidget::loadModelItem(PublicCloudModel model, QString curSelectedName)
{
    ModelConfig mc;
    std::vector<MultiAuthentication> multiAuths = mc.getModelAuthentications(model.modelName.toStdString());
    bool isValueEmpty = false;
    bool isContinuousValueEmpty = false;
    bool isRealtimeValueEmpty = false;

    KyInfo() << "loadModelConfig模型名称" <<  model.modelName << multiAuths.size();
    for (const auto &authen : multiAuths) {
        KyInfo() << "loadModelConfig配置项名称" << QString::fromStdString(authen.itemName);
        for (const auto &au : authen.authentications) {
            if (au.key == "appIdRealTime" || au.key == "apiKeyRealTime") {
                if (au.value == "") {
                    isContinuousValueEmpty = true;
                }
            } else if (au.key == "appIdContinuous" || au.key == "apiKeyContinuous" || au.key == "secretKeyContinuous") {
                if (au.value == "") {
                    isRealtimeValueEmpty = true;
                }
            } else {
                if (au.value == "") {
                    isValueEmpty = true;
                }
            }
        }
    }

    if (model.modelName == "讯飞-语音大模型") {
        if (isContinuousValueEmpty && isRealtimeValueEmpty) {
            KyInfo() << model.modelName << "验证信息为空，不加载";
            return;
        }
    } else {
        if(isValueEmpty) {
           KyInfo() << model.modelName << "验证信息为空，不加载";
           return;
        }
    }

    UkccFrame *itemFrame = new UkccFrame;
    itemFrame->setAccessibleName("kylin-ai-subsystem-modelconfig_UkccFrame_itemFrame");
    itemFrame->setMinimumWidth(496);
    itemFrame->setMaximumWidth(496);
    itemFrame->setFixedHeight(56);
    itemFrame->setObjectName(model.modelName);
    QHBoxLayout *layItem = new QHBoxLayout(itemFrame);
    layItem->setContentsMargins(0, 0, 0, 0);

    ModelItem *item = new ModelItem(model.capability, model.modelName, false, this);
    item->setAccessibleName("kylin-ai-subsystem-modelconfig_ModelItem_item");
    item->installEventFilter(this);
    connect(item, &ModelItem::sigEdit, this, &CloudModelConfigWidget::onEditModelItem);
    connect(item, &ModelItem::sigDelete, this, &CloudModelConfigWidget::onDeleteModelItem);

    layItem->addWidget(item);

    if (model.capability == AiCapability::Nlp)
    {
        m_nlpModelItemList.append(item);
        m_nlpModelMap[model.modelName] = model;
        m_nlpModelItemMap[model.modelName] = item;
        m_nlpModelMapUI[model.modelName] = itemFrame;
        m_nlpModelGroup->addWidget(itemFrame);

        // 设置为选中
        if (model.modelName == curSelectedName) {
            item->showSelectedIcon(true);
            nlpSelectedModel = model.modelName;
        }
    }
    else if (model.capability == AiCapability::Vision)
    {
        m_visionModelItemList.append(item);
        m_visionModelMap[model.modelName] = model;
        m_visionModelItemMap[model.modelName] = item;
        m_visionModelMapUI[model.modelName] = itemFrame;
        m_visionModelGroup->addWidget(itemFrame);

        // 设置为选中
        if (model.modelName == curSelectedName) {
            item->showSelectedIcon(true);
            visionSelectedModel = model.modelName;
        }
    }
    else if (model.capability == AiCapability::Speech)
    {
        m_speechModelItemList.append(item);
        m_speechModelMap[model.modelName] = model;
        m_speechModelItemMap[model.modelName] = item;
        m_speechModelMapUI[model.modelName] = itemFrame;
        m_speechModelGroup->addWidget(itemFrame);

        // 设置为选中
        if (model.modelName == curSelectedName) {
            item->showSelectedIcon(true);
            speechSelectedModel = model.modelName;
        }
    }

}

void CloudModelConfigWidget::addModelItem(PublicCloudModel model)
{
    UkccFrame *itemFrame = new UkccFrame;
    itemFrame->setAccessibleName("kylin-ai-subsystem-modelconfig_UkccFrame_itemFrame");
    itemFrame->setMinimumWidth(496);
    itemFrame->setMaximumWidth(496);
    itemFrame->setFixedHeight(56);
    itemFrame->setObjectName(model.modelName);
    QHBoxLayout *layItem = new QHBoxLayout(itemFrame);
    layItem->setContentsMargins(0, 0, 0, 0);

    ModelItem *item = new ModelItem(model.capability, model.modelName, false, this);
    item->setAccessibleName("kylin-ai-subsystem-modelconfig_ModelItem_item");
    item->installEventFilter(this);
    connect(item, &ModelItem::sigEdit, this, &CloudModelConfigWidget::onEditModelItem);
    connect(item, &ModelItem::sigDelete, this, &CloudModelConfigWidget::onDeleteModelItem);

    layItem->addWidget(item);

    if (model.capability == AiCapability::Nlp)
    {
        m_nlpModelItemList.append(item);
        m_nlpModelMap[model.modelName] = model;
        m_nlpModelItemMap[model.modelName] = item;
        m_nlpModelMapUI[model.modelName] = itemFrame;
        m_nlpModelGroup->addWidget(itemFrame);

        // 第一个添加的模型，设置为选中
        if (m_nlpModelItemMap.count() == 1) {
            item->showSelectedIcon(true);
            nlpSelectedModel = model.modelName;
        }
    }
    else if (model.capability == AiCapability::Vision)
    {
        m_visionModelItemList.append(item);
        m_visionModelMap[model.modelName] = model;
        m_visionModelItemMap[model.modelName] = item;
        m_visionModelMapUI[model.modelName] = itemFrame;
        m_visionModelGroup->addWidget(itemFrame);

        // 第一个添加的模型，设置为选中
        if (m_visionModelItemMap.count() == 1) {
            item->showSelectedIcon(true);
            visionSelectedModel = model.modelName;
        }
    }
    else if (model.capability == AiCapability::Speech)
    {
        m_speechModelItemList.append(item);
        m_speechModelMap[model.modelName] = model;
        m_speechModelItemMap[model.modelName] = item;
        m_speechModelMapUI[model.modelName] = itemFrame;
        m_speechModelGroup->addWidget(itemFrame);

        // 第一个添加的模型，设置为选中
        if (m_speechModelItemMap.count() == 1) {
            item->showSelectedIcon(true);
            speechSelectedModel = model.modelName;
        }
    }
}

void CloudModelConfigWidget::onEditModelItem(AiCapability capability, QString modelName)
{
    KyInfo() << QString("AiCapability=%0, ModelName=%1").arg((qint32)capability).arg(modelName);
    if (!polkit()) {
        return;
    }

    if (capability == AiCapability::Nlp) {
        // 随父窗口居中
        ModelConfigDialog settingDialog(m_nlpModelMap[modelName], this);
        settingDialog.exec();

    } else if (capability == AiCapability::Vision) {
        // 随父窗口居中
        ModelConfigDialog settingDialog(m_visionModelMap[modelName], this);
        settingDialog.exec();

    } else if (capability == AiCapability::Speech) {
        // 随父窗口居中
        ModelConfigDialog settingDialog(m_speechModelMap[modelName], this);
        settingDialog.exec();

    }

}

void CloudModelConfigWidget::onDeleteModelItem(AiCapability capability, QString modelName)
{
     bool isCheckSelected = checkModelSelection(capability, modelName);
     if (isCheckSelected)
     {
         // 删除当前选中模型
         if ((capability == AiCapability::Nlp &&  (getModelStatus(nlpSelectedModel) == ModelStatus::Running))
                 || (capability == AiCapability::Vision &&  (getModelStatus(visionSelectedModel) == ModelStatus::Running))
                 || (capability == AiCapability::Speech &&  (getModelStatus(speechSelectedModel) == ModelStatus::Running))) {
             // NLP or VISION or SPEECH 正在使用，重试弹窗
             KyInfo() << "正在使用" << static_cast<int>(capability) << modelName;
             bool canProceed = showModelInUseMessage(this);
             if (canProceed == true) {
                 onDeleteModelItem(capability, modelName);
             } else {
                 KyInfo() << "取消本次操作";
                 return;
             }

         } else {
             // 未使用，确认弹窗
             bool canProceed = showConfirmMessage(this);
             if (canProceed == true) {
                 bool ret = clearModelMultiAuths(capability, modelName);
                 if (ret == true) {
                     deleteModelItem(capability,  modelName);
                     KyInfo() << modelName << " 验证信息clear成功";
                 } else {
                     showErrorMessage(tr("Failed to delete model"), this);
                     KyInfo() << modelName << " 验证信息clear失败, 删除失败";
                 }
             } else {
                 KyInfo() << "取消本次操作";
                 return;
             }
        }
     } else {
         // 删除非选中模型，确认弹窗
         bool canProceed = showConfirmMessage(this);
         if (canProceed == true) {
             ModelConfig mc;
             bool ret = mc.clearModelAuthentications(modelName.toStdString());
             if (ret == true) {
                 deleteModelItem(capability,  modelName);
                 KyInfo() << modelName << " 验证信息clear成功";
             } else {
                 showErrorMessage(tr("Failed to delete model"), this);
                 KyInfo() << modelName << " 验证信息clear失败, 删除失败";
             }
         } else {
             KyInfo() << "取消本次操作";
             return;
         }
     }
}

void CloudModelConfigWidget::deleteModelItem(AiCapability capability, QString modelName)
{
    ModelConfig mc;
    QString curModelName = QString::fromStdString(mc.getCurrentModelName(capability,DeployType::PublicCloud));
    bool isCheckSelected = checkModelSelection(capability, modelName);
    KyInfo() << "currentmodelname" << curModelName << "要删除的modelname" << modelName << "isCheckSelected" << isCheckSelected;

    if (capability == AiCapability::Nlp)
    {
        // 手动删除 ModelItem 对象
        if (m_nlpModelItemMap.contains(modelName)) {
            if (m_nlpModelItemMap[modelName]) {
                m_nlpModelItemList.removeOne(m_nlpModelItemMap[modelName]);

                delete m_nlpModelItemMap[modelName];
                m_nlpModelItemMap[modelName] = nullptr;
            }
        }
        m_nlpModelMap.remove(modelName);
        m_nlpModelItemMap.remove(modelName);
        m_nlpModelGroup->removeWidget(m_nlpModelMapUI[modelName]);
        m_nlpModelMapUI.remove(modelName);

        // 如果删除选中模型,需重新设置currentmodelname
        if(curModelName == modelName || isCheckSelected)
        {
            if (m_nlpModelItemMap.count() > 0) {
                // 删除后，设置剩下模型中的第一个为选中
                ModelItem* firstItem = m_nlpModelItemList.first();
                QString firstModelName = firstItem->getModelName();

                KyInfo() << "============删除后 nlp firstModelName" << firstModelName;

                bool ret = setSelectCloudModelName(capability, DeployType::PublicCloud, firstModelName); // set sdk
                if (ret == true) {
                    switchModelItem(firstItem->getAICapability(), firstItem->getModelName());
                    KyInfo() << modelName << " 设置为选中模型成功";
                } else {
                    showErrorMessage(tr("Model setup failed"), this);
                    KyInfo() << modelName << " 设置为选中模型失败";
                    return;
                }

            } else {
                // 删除后无模型
                KyInfo() << " nlpModelItemMap为空";
                nlpSelectedModel = "";
            }
        }
    }
    else if (capability == AiCapability::Vision)
    {
        // 手动删除 ModelItem 对象
        auto item = m_visionModelItemList.takeAt(m_visionModelItemList.indexOf(m_visionModelItemMap[modelName]));
        if (m_visionModelItemMap.contains(modelName)) {
            if (m_visionModelItemMap[modelName]) {
                delete m_visionModelItemMap[modelName];
                m_visionModelItemMap[modelName] = nullptr;
            }
        }
        m_visionModelMap.remove(modelName);
        m_visionModelItemMap.remove(modelName);
        m_visionModelGroup->removeWidget(m_visionModelMapUI[modelName]);
        m_visionModelMapUI.remove(modelName);

        // 如果删除选中模型,需重新设置currentmodelname
        if(curModelName == modelName || isCheckSelected)
        {
            if (m_visionModelItemMap.count() > 0) {
                // 删除后，设置剩下模型中的第一个为选中
                ModelItem* firstItem = m_visionModelItemList.first();
                QString firstModelName = firstItem->getModelName();

                KyInfo() << "============删除后 vision firstModelName" << firstModelName;

                bool ret = setSelectCloudModelName(capability, DeployType::PublicCloud, firstModelName); // set sdk
                if (ret == true) {
                    switchModelItem(firstItem->getAICapability(), firstItem->getModelName());
                    KyInfo() << modelName << " 设置为选中模型成功";
                } else {
                    showErrorMessage(tr("Model setup failed"), this);
                    KyInfo() << modelName << " 设置为选中模型失败";
                    return;
                }

            } else {
                // 删除后无模型
                KyInfo() << " visionModelItemMap为空";
                visionSelectedModel = "";
            }
        }

    }
    else if (capability == AiCapability::Speech)
    {
        // 手动删除 ModelItem 对象
        auto item = m_speechModelItemList.takeAt(m_speechModelItemList.indexOf(m_speechModelItemMap[modelName]));
        if (m_speechModelItemMap.contains(modelName)) {
            if (m_speechModelItemMap[modelName]) {
                delete m_speechModelItemMap[modelName];
                m_speechModelItemMap[modelName] = nullptr;
            }
        }
        m_speechModelMap.remove(modelName);
        m_speechModelItemMap.remove(modelName);
        m_speechModelGroup->removeWidget(m_speechModelMapUI[modelName]);
        m_speechModelMapUI.remove(modelName);

        // 如果删除选中模型,需重新设置currentmodelname
        if(curModelName == modelName || isCheckSelected)
        {
            if (m_speechModelItemMap.count() > 0) {

                // 删除后，设置剩下模型中的第一个为选中
                ModelItem* firstItem = m_speechModelItemList.first();
                QString firstModelName = firstItem->getModelName();

                KyInfo() << "============删除后 speech firstModelName" << firstModelName;

                bool ret = setSelectCloudModelName(capability, DeployType::PublicCloud, firstModelName); // set sdk
                if (ret == true) {
                    switchModelItem(firstItem->getAICapability(), firstItem->getModelName());
                    KyInfo() << modelName << " 设置为选中模型成功";
                } else {
                    showErrorMessage(tr("Model setup failed"), this);
                    KyInfo() << modelName << " 设置为选中模型失败";
                    return;
                }

            } else {
                // 删除后无模型
                KyInfo() << " speechModelItemMap为空";
                speechSelectedModel = "";
            }
        }
    }
}

bool CloudModelConfigWidget::checkModelSelection(AiCapability capability, QString modelName)
{
    if (capability == AiCapability::Nlp) {
        if (modelName == nlpSelectedModel) {
            return true;
        } else {
            return false;
        }

    } else if (capability == AiCapability::Vision) {
        if (modelName == visionSelectedModel) {
            return true;
        } else {
            return false;
        }

    } else if (capability == AiCapability::Speech) {
        if (modelName == speechSelectedModel) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

void CloudModelConfigWidget::updateModelMap(PublicCloudModel editModel, AiCapability capability, QString modelName)
{
    if (capability == AiCapability::Nlp) {
        m_nlpModelMap[modelName] = editModel;

    } else if (capability == AiCapability::Vision) {
        m_visionModelMap[modelName] = editModel;

    } else if (capability == AiCapability::Speech) {
        m_speechModelMap[modelName] = editModel;

    } else {
        return;
    }
}


bool CloudModelConfigWidget::setSelectCloudModelConfig(PublicCloudModel model)
{
    KyInfo() << "setSelectCloudModelConfig----" << model.modelName;

    bool isValueEmpty = false;

    for (const auto &authen : model.multiAuths) {
        for (const auto &au : authen.authentications) {
            if (au.key == "appIdRealTime" || au.key == "apiKeyRealTime") {
                if (au.value == "" && realtimeSelected == true) {
                    isValueEmpty = true;
                }
            } else if (au.key == "appIdContinuous" || au.key == "apiKeyContinuous" || au.key == "secretKeyContinuous") {
                if (au.value == "" && continuousSelected == true) {
                    isValueEmpty = true;
                }
            } else {
                if (au.value == "") {
                    isValueEmpty = true;
                }
            }
        }
    }

    if (isValueEmpty == true) {
        KyInfo() << model.modelName << "验证信息为空，设置失败";
        return false;
    }

    ModelConfig mc;
    bool ret1 = mc.setModelAuthentications(model.modelName.toStdString(), model.multiAuths);

    if (ret1 == true)
    {
        bool ret2 = setSelectCloudModelName(model.capability, DeployType::PublicCloud, model.modelName);
        if (ret2 == false)
        {
            return false;
        }
    } else {
        KyInfo() << "setModelAuthentications failed:" << ret1;
        return false;
    }
    return true;
}

bool CloudModelConfigWidget::setSelectCloudModelName(AiCapability capability, DeployType deployType, QString modelName)
{
    KyInfo() << "setSelectCloudModelName" << modelName;
    ModelConfig mc;
    bool ret2 = mc.setCurrentModelName(capability, deployType, modelName.toStdString());

    if ( ret2 == true)
    {
        KyInfo() << "setCurrentModelName success:"<< ret2;
    } else {
        KyInfo() << "setCurrentModelName failed:"<< ret2;
    }
    return ret2;
}

void CloudModelConfigWidget::editSelectCloudModel(PublicCloudModel model, bool isContinuousSelected, bool isRealTimeSelected, bool isValueChanged)
{
    bool isSwitchStateChanged = false;

    if (model.capability == AiCapability::Speech) {
        if (continuousSelected != isContinuousSelected) {
            isSwitchStateChanged = true;
        }
        if (realtimeSelected != isRealTimeSelected) {
            isSwitchStateChanged = true;
        }
    }

   if ((model.capability == AiCapability::Nlp &&  (getModelStatus(nlpSelectedModel) == ModelStatus::Running))
            || (model.capability == AiCapability::Vision &&  (getModelStatus(visionSelectedModel) == ModelStatus::Running))
            || (model.capability == AiCapability::Speech &&  (getModelStatus(speechSelectedModel) == ModelStatus::Running))) {
        // NLP or VISION or SPEECH 正在使用，重试弹窗
        KyInfo() << "正在使用" << static_cast<int>(model.capability);

        if (isValueChanged == false && isSwitchStateChanged == false) {
            KyInfo() << "检查无修改内容，仅查看，关闭弹窗";
            return;
        }

        bool canProceed = showModelInUseMessage(this);
        if (canProceed == true) {
            editSelectCloudModel(model, isContinuousSelected, isRealTimeSelected, isValueChanged);
        } else {
            KyInfo() << "取消本次操作";
            return;
        }

    } else {
        // 未使用
        ModelConfig mc;
        // 当前选中的，无需再setCurrentModelName
        bool ret = mc.setModelAuthentications(model.modelName.toStdString(), model.multiAuths);
        if (ret == true) {
            // 发送信号告知已设置模型，重新创建会话
            if (model.capability == AiCapability::Nlp) {
                m_nlpModelMap[model.modelName] = model;

            } else if (model.capability== AiCapability::Vision) {
                m_visionModelMap[model.modelName] = model;

            } else if (model.capability== AiCapability::Speech) {
                m_speechModelMap[model.modelName] = model;

            }

            if (model.capability == AiCapability::Speech) {
                // 同步两个开关的状态
                continuousSelected = isContinuousSelected;
                realtimeSelected = isRealTimeSelected;
            }

        } else {
            showErrorMessage(tr("Model Editing failed"), this);
            KyInfo() << "编辑模型" << model.modelName << "失败";
        }
   }

}

void CloudModelConfigWidget::switchModelItem(AiCapability capability, QString modelName)
{
    QMap<QString, ModelItem*> *modelItemMap = nullptr;

    if (capability == AiCapability::Nlp) {
        modelItemMap = &m_nlpModelItemMap;

    } else if (capability == AiCapability::Vision) {
        modelItemMap = &m_visionModelItemMap;

    } else if (capability == AiCapability::Speech) {
        modelItemMap = &m_speechModelItemMap;
    }

    if (modelItemMap)
    {
        foreach (const auto& modelItemName, modelItemMap->keys()) {
            ModelItem* modelItem = modelItemMap->value(modelItemName);
            if (modelItem->getModelName() == modelName) {
                KyInfo() << "匹配成功，展示图标";
                modelItem->showSelectedIcon(true);

                if (capability == AiCapability::Nlp) {
                    nlpSelectedModel = modelName;

                } else if (capability == AiCapability::Vision) {
                    visionSelectedModel = modelName;

                } else if (capability == AiCapability::Speech) {
                    speechSelectedModel = modelName;
                }

            } else {
                // 不匹配，隐藏图标
                KyInfo() << "不匹配，隐藏图标";
                modelItem->showSelectedIcon(false);
            }
        }
    }
}

bool CloudModelConfigWidget::clearModelMultiAuths(AiCapability capability, QString modelName)
{
    ModelConfig mc;
    bool ret = mc.clearModelAuthentications(modelName.toStdString());

    return ret;

}

void CloudModelConfigWidget::showErrorMessage(const QString &message, QWidget *parent)
{
    QMessageBox msgBox(parent);
    msgBox.setIcon(QMessageBox::Question);
    msgBox.setText(message);

    QPushButton *cancelButton = msgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
    QPushButton *sureButton = msgBox.addButton(tr("Ok"), QMessageBox::AcceptRole);
    msgBox.setDefaultButton(sureButton);
    msgBox.exec();
}

bool CloudModelConfigWidget::showModelInUseMessage(QWidget* parent) {
    QMessageBox retryMsgBox(parent);
    retryMsgBox.setText(tr("Sorry, the kylin-aiassistant is currently using this model for a task. Please wait for the task to finish before attempting again."));
    retryMsgBox.setIcon(QMessageBox::Critical);

    QPushButton *cancelButton = retryMsgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
    QPushButton *retryButton = retryMsgBox.addButton(tr("Retry"), QMessageBox::AcceptRole);
    retryMsgBox.setDefaultButton(retryButton);
    retryMsgBox.exec();

    if ((QPushButton *)retryMsgBox.clickedButton() == retryButton) {
        return true;
    }
    return false;
}

bool CloudModelConfigWidget::showConfirmMessage(QWidget* parent) {
    QMessageBox confirmMsgBox(this);
    confirmMsgBox.setText(tr("Deleting this model may cause apps that rely on this model to not function properly, are you sure you want to remove it?"));
    confirmMsgBox.setIcon(QMessageBox::Question);

    QPushButton *cancelButton = confirmMsgBox.addButton(tr("Cancel"), QMessageBox::RejectRole);
    QPushButton *sureButton = confirmMsgBox.addButton(tr("Delete"), QMessageBox::AcceptRole);
    confirmMsgBox.setDefaultButton(sureButton);
    confirmMsgBox.exec();

    if ((QPushButton *)confirmMsgBox.clickedButton() == sureButton) {
        return true;
    }
    return false;
}

/* 通过polkit提权 */
bool CloudModelConfigWidget::polkit()
{
    PolkitQt1::Authority::Result result;
    result = PolkitQt1::Authority::instance()->checkAuthorizationSync(
                "org.kylin.aiassistant.action",
                PolkitQt1::UnixProcessSubject(QCoreApplication::applicationPid()),
                PolkitQt1::Authority::AllowUserInteraction);
    KyInfo() << "PolkitQt1 Authority result:" << result;
    if (result == PolkitQt1::Authority::Yes) { //认证通过
        KyInfo() << QString("operation authorized");
        return true;
    } else {
        KyInfo() << QString("not authorized");
        return false;
    }
}

QMap<QString, ModelItem*>& CloudModelConfigWidget::getModelItemMap(AiCapability capability)
{
    if (capability == AiCapability::Nlp) {
        return m_nlpModelItemMap;
    } else if (capability == AiCapability::Vision) {
        return m_visionModelItemMap;
    } else if (capability == AiCapability::Speech) {
        return m_speechModelItemMap;
    }
}

void CloudModelConfigWidget::showTrialList() {
    m_showOrHideTrialListButton->setIcon(QIcon::fromTheme("ukui-up-symbolic"));
    for (ModelItem* modelItem : m_nlpModelItemList) {
        if (modelItem && modelItem->parentWidget() && modelItem->isTrialModel()) {
            modelItem->parentWidget()->show();
        }
    }
}

void CloudModelConfigWidget::hideTrialList() {
    m_showOrHideTrialListButton->setIcon(QIcon::fromTheme("ukui-down-symbolic"));
    for (ModelItem* modelItem : m_nlpModelItemList) {
        if (modelItem && modelItem->parentWidget() && modelItem->isTrialModel()) {
            modelItem->parentWidget()->hide();
        }
    }
}

ModelStatus CloudModelConfigWidget::getModelStatus(QString modelName)
{
    ModelConfig mc;
    ModelStatus ret = mc.getModelStatus(modelName.toStdString());
    KyInfo() << QString("%1 ModelStatus = %2").arg(modelName).arg((qint32)ret);
    return ret;
}

void CloudModelConfigWidget::showCentered()
{
   if (QWidget* mainWindow = QApplication::activeWindow())
   {

       QRect mainGeom = mainWindow->geometry();
       move(mainGeom.x() + (mainGeom.width() - width()) / 2,
       mainGeom.y() + (mainGeom.height() - height()) / 2+ 15);
   }
   adjustPosition(this); // 调用内部调整逻辑
}


