#include "msgpane.h"

#include <QThread>
#include <QVariant>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QKeyEvent>
#include <QWebEngineSettings>
#include <ukuistylehelper/ukuistylehelper.h>
#include <QMessageBox>
#include <QMap>

#include "chatoperator.h"
#include "cpushbuttonex.h"
#include "global/kaglobal.h"
#include "tipwidget.h"
#include "renamedialog.h"

//与SDK接口角色对齐
QMap<QString, int> actorLable ={
    {"中英文翻译",1},
    {"英中文翻译",2},
    {"文本扩写",11},
    {"文本润色",12},
    {"内容质检",13},
    {"邮件回复",14},
    {"总结概况",15},
    {"工作总结",16},
    {"代码生成",17}
};

CMsgPane::CMsgPane(QWidget *parent) : QWidget(parent)
{
    createAllChildWnd();
    initCtrl();
    initSolts();
    relayout();

    bubble_show_count = 0;
    initChatOperator();
    initBubbleUpdateTimer();
}

void CMsgPane::createAllChildWnd()
{
#define NEW_OBJECT(pObj, TYPE) \
    if (NULL == pObj) { pObj = new TYPE(this); }

    NEW_OBJECT(m_pViewChat, QWebEngineView);
    NEW_OBJECT(m_channel, QWebChannel);
    NEW_OBJECT(m_channelMsg, ChannelMessage);
    NEW_OBJECT(m_btnVoice, CPushButtonEx);
    NEW_OBJECT(m_labSeparatorLine, QLabel);
//    NEW_OBJECT(m_recorder, Recorder);
    NEW_OBJECT(m_runtimeRecorder, RuntimeRecorder);
    NEW_OBJECT(m_meetingRecorder, MeetingRecorder);

    NEW_OBJECT(m_sendBar, KASendBar);
    NEW_OBJECT(m_buttonSetup, QPushButton);
}

void CMsgPane::initCtrl()
{
    // 按照设计稿设计，语音按钮大小为 16x16
    m_btnVoice->setFixedSize(16, 16);
    m_btnVoice->setIcon(QIcon(QString(":/icon/icon/voice.svg")));
    m_btnVoice->hide();

    m_labSeparatorLine->setFixedHeight(1);
    m_labSeparatorLine->setStyleSheet("background-color:#4A7ABA");
    m_labSeparatorLine->hide();

    m_pViewChat->page()->setWebChannel(m_channel);
    m_channel->registerObject(QStringLiteral("channelMsg"), m_channelMsg);

    m_pViewChat->setContextMenuPolicy(Qt::NoContextMenu);
    m_pViewChat->load(QUrl("qrc:/html/html/index1.html"));
//    m_pViewChat->load(QUrl("qrc:/html/html/meeting-detail.html"));
    m_pViewChat->show();
    m_pViewChat->setFixedWidth(402);
    connect(m_pViewChat, &QWebEngineView::loadFinished, this, &CMsgPane::OnWebViewLoaded);
    connect(m_pViewChat, &QWebEngineView::urlChanged, this, &CMsgPane::onUrlChanged);

    // 按照设计稿设计，聊天界面大小为 402x568
//    this->setFixedSize(402, 568);
}

void CMsgPane::initSolts()
{
//    connect(m_recorder, &Recorder::sigSendMsg, this, &CMsgPane::onSendMsg);
    connect(m_runtimeRecorder, &RuntimeRecorder::sigShowText, this, &CMsgPane::onShowText);
    connect(m_meetingRecorder, &MeetingRecorder::sigShowSpeech, this, &CMsgPane::onShowSpeech);

    connect(m_buttonSetup, &QPushButton::clicked, [this](){emit sigSetup();});

//    connect(g_gsettings, &QGSettings::changed, [this](QString key){
//        if (key == "isNlpSetup")
//            updateModelStatus();
//    });

    connect(m_channelMsg, &ChannelMessage::sigMessageFromJs, this, &CMsgPane::onSendMsg);
    connect(m_channelMsg, &ChannelMessage::sigClearFromJs, this, &CMsgPane::onClearMsg);
    connect(m_channelMsg, &ChannelMessage::sigUpdateReply, this, &CMsgPane::onUpdateReply);
    connect(m_channelMsg, &ChannelMessage::sigStopReply, this, &CMsgPane::onStopReply);
    connect(m_channelMsg, &ChannelMessage::sigSaveMessageList, this, &CMsgPane::onSaveMessageList);
    connect(m_channelMsg, &ChannelMessage::sigGetMessageList, this, &CMsgPane::onLoadMessageList);
    //录音功能
    connect(m_channelMsg, &ChannelMessage::sigStartRecord, this, &CMsgPane::onSendAudio);
    connect(m_channelMsg, &ChannelMessage::sigStopRecord, this, &CMsgPane::onStopAudio);
    connect(m_channelMsg, &ChannelMessage::sigStartRuntime, this, &CMsgPane::onSendRuntimeAudio);
    connect(m_channelMsg, &ChannelMessage::sigStopRuntime, this, &CMsgPane::onStopRuntimeAudio);
    //语音听写
    connect(m_channelMsg, &ChannelMessage::sigClearDictation, this, &CMsgPane::onClearDictation);
    connect(m_channelMsg, &ChannelMessage::sigCopyDictation, this, &CMsgPane::onCopyDictation);
    //会议助手
    connect(m_channelMsg, &ChannelMessage::sigStartMeeting, this, &CMsgPane::onSendMeetingAudio);
    connect(m_channelMsg, &ChannelMessage::sigPauseMeeting, this, &CMsgPane::onPauseMeetingAudio);
    connect(m_channelMsg, &ChannelMessage::sigStopMeeting, this, &CMsgPane::onStopMeetingAudio);

    connect(m_channelMsg, &ChannelMessage::sigRename, this, &CMsgPane::onRename);
    connect(m_channelMsg, &ChannelMessage::sigMeetingList, this, &CMsgPane::onMeetingList);



    qint64 uid = static_cast<qint64>(getuid());
    QDBusInterface iface("org.freedesktop.Accounts",
                         "/org/freedesktop/Accounts",
                         "org.freedesktop.Accounts",
                         QDBusConnection::systemBus());
    QDBusReply<QDBusObjectPath>objPath = iface.call("FindUserById", uid);
    QDBusConnection::systemBus().connect("org.freedesktop.Accounts",
                                         objPath.value().path(),
                                         "org.freedesktop.Accounts.User",
                                         QString("Changed"), this, SLOT(userAccountsChanged()));
}

void CMsgPane::initChatOperator()
{
    m_chatOperator = new ChatOperator;
    connect(m_chatOperator, &ChatOperator::reply, this, &CMsgPane::onRecvMsg);
    connect(m_chatOperator, &ChatOperator::sigSendMessageError, [this](){
        QString jsStr = QString("addRecvMsg(\"%1\")").arg(tr("Sending message failed, please ensure that the Key is set correctly and the network is unobstructed."));
        m_pViewChat->page()->runJavaScript(jsStr);
        QString jsStr1 = QString("isReplyEnd(true)");
        m_pViewChat->page()->runJavaScript(jsStr1);
        m_sendBar->setEditEnabled(true);
    });
    connect(m_chatOperator, &ChatOperator::sigSessionCompleted, [this](){
        // 只有在单次回答对话结束后才允许点击清除会话按钮
        m_sendBar->setClearEnabled(true);
    });
    connect(m_chatOperator, &ChatOperator::sigGenerateSummary, this, &CMsgPane::onGenerateSummary);
}

void CMsgPane::initBubbleUpdateTimer()
{
    bubble_update_timer = new QTimer;
    bubble_update_timer->setInterval(40);
    connect(bubble_update_timer, &QTimer::timeout, this, &CMsgPane::updateBubble);
}

void CMsgPane::relayout()
{
    QVBoxLayout *layoutRMain = new QVBoxLayout();;
    layoutRMain->addWidget(m_pViewChat);
    layoutRMain->addWidget(m_labSeparatorLine);

    m_buttonSetup->setFocusPolicy(Qt::NoFocus);
    m_buttonSetup->setProperty("isImportant", true);
    m_buttonSetup->setText(tr("Configure Now"));

//    layoutRMain->addWidget(m_sendBar);
    m_sendBar->setVisible(false);
    layoutRMain->addWidget(m_buttonSetup);

    updateModelStatus();

    layoutRMain->setSpacing(0);
    layoutRMain->setMargin(0);

    setLayout(layoutRMain);
}

void CMsgPane::onBackBtnClicked()
{
    qDebug() << "当前页面"<< m_pViewChat->url();
    if(m_pViewChat->url() == QUrl("qrc:/html/html/meeting-recording.html"))
    {
        onStopMeetingAudio();
    } else {
        m_pViewChat->load(QUrl("qrc:/html/html/index1.html"));
        //加载主页面聊天记录
        onLoadMessageList();
    }
}

void CMsgPane::onUrlChanged(const QUrl &url)
{
    emit sigUrlChanged(url);
}

void CMsgPane::onClearMsg()
{
    m_chatOperator->clearSession();
    QString jsStr1 = QString("contextCleared()");
    m_pViewChat->page()->runJavaScript(jsStr1);

}

void CMsgPane::onSendMsg(const QString &msgHead, const QString &msg)
{
    m_chatOperator->target = RECVMSG;
    new_reply = true;
    bool flag = false;
    //识别是否为系统控制命令

    //1、判断是否为dbus命令
    if (StartUpTools::getInstance()->inspectCtrl(msg)) {
        QTime dieTime = QTime::currentTime().addMSecs(800);
        while (QTime::currentTime() < dieTime) {
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
        }
        qInfo() << "The wake word was matched successfully!";
        flag = true;
    }
    QString key = StartUpTools::getInstance()->findNmKey(msg);
    if (!key.isEmpty()) {
        QTime dieTime = QTime::currentTime().addMSecs(800);
        while (QTime::currentTime() < dieTime) {
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
        }
        qInfo() << "The wake word was matched successfully!";
        StartUpTools::getInstance()->startUp(key);
        flag = true;
    }
    //2、判断打开还是关闭操作
    opType op = StartUpTools::getInstance()->isExit(msg);
    if (op != ORTHER){
        QString target = msg.mid(2);
        QString punctuation = ".,;:!？。";
        for (int i = 0; i < punctuation.length(); ++i) // 删除标点符号
            target.remove(punctuation[i]);
        key = StartUpTools::getInstance()->findKey(target);

        //3、判断是否为可支持应用
        if (!key.isEmpty()) {
            QTime dieTime = QTime::currentTime().addMSecs(800);
            while (QTime::currentTime() < dieTime) {
                QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
            }
            qInfo() << "The wake word was matched successfully!";
            if (op == CLOSE) {
                StartUpTools::getInstance()->killProcess(key);
            } else if (op == OPEN){
                StartUpTools::getInstance()->startUp(key);
            }
            flag = true;
        }
    }

    //判断是否有标签模板
    if(msgHead != ""){
        int actorId = actorLable[msgHead];
        m_chatOperator->setActor(actorId);
    }
    pushMsg("addMsg", msgHead, msg);

    if (flag){
         pushMsg("addRecvMsg", "", "好的，已为您执行操作");
         QString jsStr1 = QString("isReplyEnd(true)");
         m_pViewChat->page()->runJavaScript(jsStr1);
         return;
    }
    if (!m_chatOperator->sendMessage(msg))
    {
        // 发送失败，提示用户
        // 需要sdk接口改为异步之后处理
        pushMsg("addRecvMsg", "", tr("Sending message failed, please ensure that the Key is set correctly and the network is unobstructed."));
        QString jsStr1 = QString("isReplyEnd(true)");
        m_pViewChat->page()->runJavaScript(jsStr1);
        m_sendBar->setEditEnabled(true);
    }
    QString js_str2 = QString("setReplyStale()"); //设置上一条回答不可重新生成
    m_pViewChat->page()->runJavaScript(js_str2);
}

void CMsgPane::onStopReply()
{
    new_reply = true;
    recv_message ="";
    bubble_show_count = 0;
    bubble_update_timer->stop();
    QString jsStr1 = QString("isReplyEnd(true)");
    m_pViewChat->page()->runJavaScript(jsStr1);
    m_chatOperator->stopChat();

}

void CMsgPane::onUpdateReply(const QString &msgHead, const QString &msg)
{
    new_reply = true;
    bool flag = false;
    //识别是否为系统控制命令

    //1、判断是否为dbus命令
    if (StartUpTools::getInstance()->inspectCtrl(msg)) {
        QTime dieTime = QTime::currentTime().addMSecs(800);
        while (QTime::currentTime() < dieTime) {
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
        }
        qInfo() << "The wake word was matched successfully!";
        flag = true;
    }
    QString key = StartUpTools::getInstance()->findNmKey(msg);
    if (!key.isEmpty()) {
        QTime dieTime = QTime::currentTime().addMSecs(800);
        while (QTime::currentTime() < dieTime) {
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
        }
        qInfo() << "The wake word was matched successfully!";
        StartUpTools::getInstance()->startUp(key);
        flag = true;
    }
    //2、判断打开还是关闭操作
    opType op = StartUpTools::getInstance()->isExit(msg);
    if (op != ORTHER){
        QString target = msg.mid(2);
        key = StartUpTools::getInstance()->findKey(target);

        //3、判断是否为可支持应用
        if (!key.isEmpty()) {
            QTime dieTime = QTime::currentTime().addMSecs(800);
            while (QTime::currentTime() < dieTime) {
                QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
            }
            qInfo() << "The wake word was matched successfully!";
            if (op == CLOSE) {
                StartUpTools::getInstance()->killProcess(key);
            } else if (op == OPEN){
                StartUpTools::getInstance()->startUp(key);
            }
            flag = true;
        }
    }

    //判断是否有标签模板
    if(msgHead != ""){

    }
    if (flag){
         pushMsg("addRecvMsg", "", "好的，已为您执行操作");
         QString jsStr1 = QString("isReplyEnd(true)");
         m_pViewChat->page()->runJavaScript(jsStr1);
         return;
    }
    if (!m_chatOperator->sendMessage(msg))
    {
        // 发送失败，提示用户
        // 需要sdk接口改为异步之后处理
        pushMsg("addRecvMsg", "", tr("Sending message failed, please ensure that the Key is set correctly and the network is unobstructed."));
        QString jsStr1 = QString("isReplyEnd(true)");
        m_pViewChat->page()->runJavaScript(jsStr1);
    }
}

void CMsgPane::OnWebViewLoaded()
{
    QTimer::singleShot(1000, this, [this](){
#ifdef QT_DEBUG
    // only for debug
//        pushMsg("addMsg", "小麒小麒，谁是世界上最好的操作系统？");
//        pushMsg("addRecvMsg", "关于哪个操作系统是最好的，这是一个非常主观的问题，取决于个人偏好、需求和使用情境。以下是一些常见的操作系统，每个都有其优点和适用场景。");
//        pushMsg("cutoffMsg", "-------上下文关联已清除-------");
//        pushMsg("addMsg", "小麒小麒，谁是世界上最好的操作系统？");
//        pushMsg("addRecvMsg", "关于哪个操作系统是最好的，这是一个非常主观的问题，取决于个人偏好、需求和使用情境。以下是一些常见的操作系统，每个都有其优点和适用场景。");
//        pushMsg("flush", "0");
#endif
    });

    initCurrentUserName();
    initCurrentUserIcon();
}

void CMsgPane::onRecvMsg(QString msg, bool is_end, int index)
{
    if (new_reply)
    {
        pushMsg("addRecvMsg", "", "");
    }
    recv_message.append(msg);
    new_reply = is_end;
    if (!bubble_update_timer->isActive())
        bubble_update_timer->start();

    QString jsStr1 = QString("isReplyEnd(false)");
    m_pViewChat->page()->runJavaScript(jsStr1);
}

void CMsgPane::onGenerateSummary(QString msg, bool is_end, int index)
{
    if (index == 0){
        m_summary="";
    }
    msg.replace("\\", "\\\\");
    msg.replace("\n", "\\n");
    msg.replace("\"", "\\\"");
    m_summary.append(msg);
    if(is_end){
        saveMeetingToFile();
        m_chatOperator->clearSession();
    }
}

void CMsgPane::onShowText(const QString text)
{
    pushMsg("showText", "", text);
}

void CMsgPane::onShowSpeech(const QString text)
{
    QString msg = text;
    msg.replace('\n', "");
    QString js_str = QString("updateMsg('%1')").arg(msg);
    qDebug() << js_str;
    m_pViewChat->page()->runJavaScript(js_str);
}

/**
 * @brief CMsgPane::updateBubble 按字去更新内容
 */
void CMsgPane::updateBubble()
{
    bool loading = bubble_show_count == recv_message.length();
    if (new_reply && loading)
    {
        recv_message = "";
        bubble_show_count = 0;
        bubble_update_timer->stop();

        QString jsStr = QString("isReplyEnd(true)");
        m_pViewChat->page()->runJavaScript(jsStr);
        return;
    }
    QString show_msg = recv_message.left(loading ? bubble_show_count : ++bubble_show_count);
    if (!loading)
        loading_dot_index = 0;
    QString dot_dot = "...";
    pushMsg("updateMsg", "", show_msg.append(dot_dot.left(loading ? loading_dot_index++ / 10 % 4 : 0)));
}

/**
 * @brief CMsgPane::updateModelStatus
 *          模型设置更新
 */
void CMsgPane::updateModelStatus()
{
    if (g_gsettings->keys().contains("isNlpSetup") && g_gsettings->get("isNlpSetup").toBool())
    {
 //        m_sendBar->show();
        m_buttonSetup->hide();
    }
    else
    {
        m_sendBar->hide();
        m_buttonSetup->show();
    }
}

void CMsgPane::pushMsg(QString func, QString msgHead, QString msg)
{
    msg.replace("\\", "\\\\");
    msg.replace("\n", "\\n");
    msg.replace("\"", "\\\"");
    if(func == "addMsg"){
        QString js_str = QString("%1(\"%2\",\"%3\")").arg(func).arg(msgHead).arg(msg);
        m_pViewChat->page()->runJavaScript(js_str);

        QString js_str2 = QString("setReplyStale()"); //设置上一条回答不可重新生成
        m_pViewChat->page()->runJavaScript(js_str2);
    }else{
//        msg.replace('\n', "");
        QString js_str = QString("%1(\"%2\")").arg(func).arg(msg);
//        qDebug() << js_str;
        m_pViewChat->page()->runJavaScript(js_str);
    }
}

void CMsgPane::initCurrentUserName()
{
    QString objpath = QString("/org/freedesktop/Accounts/User%1").arg(getuid());

    QString userName;
    QDBusInterface *iproperty = new QDBusInterface("org.freedesktop.Accounts",
                                                   objpath,
                                                   "org.freedesktop.DBus.Properties",
                                                   QDBusConnection::systemBus());
    QDBusReply<QMap<QString, QVariant> > ipropertyReply = iproperty->call("GetAll", "org.freedesktop.Accounts.User");
    if (ipropertyReply.isValid()){
        QMap<QString, QVariant> propertyMap = ipropertyReply.value();

        userName = propertyMap.find("RealName").value().toString();
    }

    QString js_str = QString("%1(\"%2\")").arg("setUser").arg(userName);
    m_pViewChat->page()->runJavaScript(js_str);

    return;
}

void CMsgPane::initCurrentUserIcon()
{

    QString objpath = QString("/org/freedesktop/Accounts/User%1").arg(getuid());

    QString iconfile;
    QDBusInterface *iproperty = new QDBusInterface("org.freedesktop.Accounts",
                                                   objpath,
                                                   "org.freedesktop.DBus.Properties",
                                                   QDBusConnection::systemBus());
    QDBusReply<QMap<QString, QVariant> > ipropertyReply = iproperty->call("GetAll", "org.freedesktop.Accounts.User");
    if (ipropertyReply.isValid()){
        QMap<QString, QVariant> propertyMap = ipropertyReply.value();

        iconfile = propertyMap.find("IconFile").value().toString();
    }

    QImage image(iconfile);

    QByteArray ba;
    QBuffer buf(&ba);
    image.save(&buf, "png");
    buf.close();
    QString base64Str = QString::fromLocal8Bit(ba.toBase64());
    QString base64StrIcon = "data:image/png;base64," + base64Str;

    QString js_str = QString("%1(\"%2\")").arg("setUserIcon").arg(base64StrIcon);
    m_pViewChat->page()->runJavaScript(js_str);

    return;
}

void CMsgPane::userAccountsChanged()
{
    initCurrentUserName();
    initCurrentUserIcon();

    return;
}

void CMsgPane::saveDialogToFile(const QString &dialogJsonString)
{
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();

    // 格式化当前时间为字符串，包含年、月、日、小时、分钟和秒
    QString formattedTime = currentTime.toString("yyyyMMdd_hhmmss");

    QString documentsDir = QDir::homePath() + "/文档";

    // 使用格式化后的时间作为文件名
    QString fileName = documentsDir + "/kylin-aiassistant/dialog/dialog_" + formattedTime + ".json";

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return;
    }

    file.write(dialogJsonString.toUtf8());

    file.close();

    // 由于CMsgPane::saveDialogToFile是被异步调用的，所以这里通过信号通知历史会话界面当前已经保存了会话到文件，以此更新历史会话界面。
    emit sigSaveDialog(fileName);

    return;
}

void CMsgPane::saveMessageToFile(const QString &msgJsonString)
{
    QString documentsDir = QDir::homePath() + "/文档";

    QString fileName = documentsDir + "/kylin-aiassistant/dialog/message.json";

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        return;
    }

    file.write(msgJsonString.toUtf8());

    file.close();

    return;
}

void CMsgPane::saveMeetingToFile()
{
    // 获取当前时间
    QDateTime currentTime = QDateTime::currentDateTime();

    // 格式化当前时间为字符串，包含年、月、日、小时、分钟和秒
    QString formattedTime = currentTime.toString("yyyyMMdd_hhmmss");

    QString documentsDir = QDir::homePath() + "/文档";

    // 使用格式化后的时间作为文件名
    QString fileName = documentsDir + "/kylin-aiassistant/meeting/meeting_" + formattedTime + ".txt";

    QFile file(fileName);
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
        return;
    }

    file.write((m_summary + "\n" + m_origin).toUtf8());

    file.close();
}

void CMsgPane::saveDialog()
{
    // 先保存当前会话
    m_pViewChat->page()->runJavaScript("getActiveDialog()", [this](const QVariant &v) { this->saveDialogToFile(v.toString());});

    return;
}

void CMsgPane::clearDialog()
{
    // 然后清除当前会话
    m_pViewChat->page()->runJavaScript("clearActiveDialog()");

    return;
}

void CMsgPane::loadPlugin(QString pluginHtmlFile)
{
    m_pViewChat->load(QUrl(pluginHtmlFile));
}

void CMsgPane::onSendAudio()
{
//    m_recorder->startRecord();

}

void CMsgPane::onStopAudio()
{
//    m_recorder->stopRecord();
    //录音结束，调用recorder的发送接口，异步返回结果
}

void CMsgPane::onSendRuntimeAudio(QString lan, QString target)
{
    m_runtimeRecorder->startRuntimeRecord();
    //开始录音，通过runtimeRecorder实时发送录音数据

    //不应该在此处执行js命令，正确流程是  callback发送信号，触发槽函数，槽函数调用pushMsg。
//    pushMsg("showText", "", "测试听写测试听写测试听写测试听写测试听写测试听写");
}

void CMsgPane::onStopRuntimeAudio()
{
    m_runtimeRecorder->stopRuntimeRecord();
    //停止录音，关闭会话
}

void CMsgPane::onSendMeetingAudio()
{
    m_meetingRecorder->startMeetingRecord();
    pushMsg("startTimer","","");
    //todo : 开始录音之后，调用接口发送音频数据，等待callback返回输出

}

void CMsgPane::onPauseMeetingAudio()
{
    m_meetingRecorder->pauseMeetingRecord();
}

void CMsgPane::onStopMeetingAudio()
{

    QMessageBox msg(this->parentWidget());
    msg.setWindowTitle(tr(""));
    msg.setText(tr("Are you sure you want to end the recording? Unable to continue recording in this record after completion."));
    msg.setIcon(QMessageBox::Question);
    msg.addButton(tr("Cancel"), QMessageBox::AcceptRole);
    QPushButton *sureBtn = msg.addButton(tr("Ok"), QMessageBox::RejectRole);
    msg.setDefaultButton(sureBtn);
    msg.exec();

    if ((QPushButton *)msg.clickedButton() == sureBtn) {
        m_meetingRecorder->stopMeetingRecord();
        pushMsg("switchToMeetingPage","","");    
        m_pViewChat->page()->runJavaScript("getMeetingContent()", [this](const QVariant &v) { this->processMessageList(v.toString());});
    }
}

void CMsgPane::onClearDictation()
{
    TipWidget::showTip(tr("Cleared"), 1000, QSize(106, 48), parentWidget(), TipWidget:: OK);
}

void CMsgPane::onCopyDictation()
{
    TipWidget::showTip(tr("Copy Successful"), 1000, QSize(120, 48), parentWidget(), TipWidget::OK);
}

void CMsgPane::onRename(QString originalName)
{
    RenameDialog dialog(originalName, this);
    if (dialog.exec() == QDialog::Accepted) {
        QString newName = dialog.getNewName();
        QString js_str = QString("rename(\"%1\",\"%2\")").arg(originalName).arg(newName);
        m_pViewChat->page()->runJavaScript(js_str);
        qDebug()<< js_str;
    }
}

void CMsgPane::onMeetingList(QString str)
{
    str.replace('\n', "");
    QString js_str = QString("loadMeetingList('%1')").arg(str);
//    qDebug() << js_str;
    m_pViewChat->page()->runJavaScript(js_str);
}

void CMsgPane::processMessageList(QString jsonStr)
{
    m_chatOperator->target = SUMMARY;
    //解析jsonStr，提取content的值，拼接成QString字符串，赋值给m_origin
        QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8());
        if (!jsonDoc.isNull()) {
            if (jsonDoc.isArray()){
                QJsonArray jsonArray = jsonDoc.array();
                for (const QJsonValue &value : jsonArray) {
                    if (value.isObject()) {
                        QJsonObject jsonObject = value.toObject();
                        if (jsonObject.contains("content")) {
                            QString content = jsonObject.value("content").toString();
                            m_origin.append(content);
                        }
                    }
                }
            }
        }
    //设置会议总结角色，发送会议原文
    m_chatOperator->setActor(15);
    m_chatOperator->sendMessage(m_origin);
}

void CMsgPane::onSaveMessageList()
{
    //跳转前更新保存当前会话内容
    m_pViewChat->page()->runJavaScript("getActiveDialog()", [this](const QVariant &v) { this->saveMessageToFile(v.toString());});
}

void CMsgPane::onLoadMessageList()
{
    QString documentsDir = QDir::homePath() + "/文档";
    QString directoryPath = documentsDir + "/kylin-aiassistant/dialog";
    QDir dir(directoryPath);
    if (!dir.exists()) {
        qDebug() << "目录不存在：" << directoryPath;
        return;
    }
    QString fileName = "message.json";
    QFile file(directoryPath + "/" + fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "无法打开文件：" << fileName;
        return;
    }

    QByteArray jsonData = file.readAll();
    file.close();

    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData, &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "JSON 解析错误：" << parseError.errorString();
        return;
    }

    QJsonArray jsonArray = jsonDoc.array();
    QString str = QJsonDocument(jsonArray).toJson(QJsonDocument::Indented);
    str.replace("\\", "\\\\");
    str.replace("\n", "\\n");
    str.replace("\"", "\\\"");
    QString js_str = QString("loadMessageList('%1')").arg(str);
    m_pViewChat->page()->runJavaScript(js_str);
}
