#include "voicethread.h"
#include "global/voiceusingmanager.h"

#include <error.h>
#include <list>
#include <algorithm>
#include <iostream>
#include <QEventLoop>
#include <QObject>
#include <QBuffer>
#include <QUrl>
#include <QMutexLocker>

static VoiceThread *g_voiceThread = nullptr;

VoiceThread::VoiceThread(QObject *parent)
    : QThread{parent}
{
    initChildModule();
    initConnect();

    start();
}

VoiceThread::~VoiceThread()
{
    quitThread();

    if (!wait(3000)) {
        terminate();
        wait();
    }

    closeSpeechSession();
    closeReaderSession();

    // 清理代理对象
    if (m_readerProxy) {
        delete m_readerProxy;
        m_readerProxy = nullptr;
    }
    if (m_speechProxy) {
        delete m_speechProxy;
        m_speechProxy = nullptr;
    }

    // 清理工作线程
    if (m_readerThread) {
        m_readerThread->quit();
        m_readerThread->wait();
        delete m_readerThread;
        m_readerThread = nullptr;
    }
    if (m_speechThread) {
        m_speechThread->quit();
        m_speechThread->wait();
        delete m_speechThread;
        m_speechThread = nullptr;
    }

    // 清理对象（对象会在工作线程中自动清理）
    if (m_chatReader) {
        m_chatReader->deleteLater();
        m_chatReader = nullptr;
    }
    if (m_chatSpeech) {
        m_chatSpeech->deleteLater();
        m_chatSpeech = nullptr;
    }
}

VoiceThread::VoiceChatState VoiceThread::getCurVoiceState() const
{
    
    return m_currentVoiceState;
}

int VoiceThread::getCurVoiceVolume() const
{
    return m_currentVoiceVolume;
}

bool VoiceThread::isOndeviceSpeechModel() const
{
    ModelConfig mc;
    // 尝试获取本地语音模型名称
    int ondeviceScheduling = mc.getModelSchedulingPriority(DeployType::Ondevice);
    KyInfo() << "当前本地模型优先级" << ondeviceScheduling;
    std::string localModelStr = mc.getCurrentModelName(AiCapability::Speech, DeployType::Ondevice);
    QString speechString = QString::fromStdString(localModelStr);
    KyInfo() << "当前本地模型内容" << speechString;

    if(ondeviceScheduling == 1) {

        return true;
    }
    else {

        return false;
    }
}

VoiceThread *VoiceThread::getPtr()
{
    if (g_voiceThread == nullptr) {
        g_voiceThread = new VoiceThread;
    }

    return g_voiceThread;
}

void VoiceThread::initVoiceThread()
{
    if(m_chatAnswer) {
        m_chatAnswer->initChatSession();
    }

    return;
}

void VoiceThread::sendQuestion(QString text, QString filePath)
{
    if(m_chatAnswer) {
        m_chatAnswer->sendQuestion(text, filePath);
        setVoiceState(VoiceChatState::SendQuestioning);
        KyInfo() << "成功发送文字到大模型准备回复";
    }

    return;
}

void VoiceThread::initConnect()
{
    //将持续语音识别内容通过统一接口转发到前端（通过代理对象）
    connect(m_speechProxy, &VoiceChatSpeechControlProxy::sigReceiveSpeechRecognitionMessage ,this, &VoiceThread::slGetSpeechRecognitionResult);
    connect(m_speechProxy, &VoiceChatSpeechControlProxy::sigCurSpeechVolume, this, &VoiceThread::slUpdateCurrnetVolume);
    // 连接语音识别已开始信号，从 Initializing 切换到 Recording
    connect(m_speechProxy, &VoiceChatSpeechControlProxy::speechRecognitionStarted, this, [this]() {
        if(m_currentVoiceState == VoiceChatState::Initializing) {
            setVoiceState(VoiceChatState::Recording);
        }
    });
    connect(m_chatAnswer, &VoiceChatAnswer::sigReceiveChatAnswerMessage, this, &VoiceThread::getAnswerTextReslut);
    connect(m_chatAnswer, &VoiceChatAnswer::sigBeginReplying, this, &VoiceThread::setAnswerStatue);
    connect(m_chatAnswer, &VoiceChatAnswer::sigInterruptSuessful, this, &VoiceThread::interruptReplyEnd);
    connect(m_readerProxy, &VoiceChatReaderControlProxy::sigReadEnd, this, &VoiceThread::onCurrentReadingEnd);
    connect(m_readerProxy, &VoiceChatReaderControlProxy::sigReceiveReaderMessage,this, &VoiceThread::onShowReadingError);
    connect(VoiceUsingManager::getInstance(), &VoiceUsingManager::sigInterruptUsing, this,[&](bool isSendByVoiceChat){
        if(isSendByVoiceChat) {
            return;
        }
        if(m_currentVoiceState == VoiceChatState::Idle) {
            return;
        }
        KyInfo() << "当前正在执行打断原有语音通话的流程";
        stopVoiceChat();
    });

    return;
}

void VoiceThread::initChildModule()
{
    // 创建 VoiceChatReader 对象（在工作线程中）
    m_chatReader = new VoiceChatReader();
    
    // 创建 VoiceChatReader 的工作线程
    m_readerThread = new QThread();
    // 将 VoiceChatReader 移动到工作线程
    m_chatReader->moveToWorkerThread(m_readerThread);
    
    // 创建代理对象，用于在 VoiceThread 中异步调用
    m_readerProxy = new VoiceChatReaderControlProxy(m_chatReader, this);
    
    // 创建 VoiceChatSpeech 对象（在工作线程中）
    m_chatSpeech = new VoiceChatSpeech();
    
    // 创建 VoiceChatSpeech 的工作线程
    m_speechThread = new QThread();
    // 将 VoiceChatSpeech 移动到工作线程
    m_chatSpeech->moveToWorkerThread(m_speechThread);
    
    // 创建代理对象，用于在 VoiceThread 中异步调用
    m_speechProxy = new VoiceChatSpeechControlProxy(m_chatSpeech, this);
    
    m_chatAnswer = VoiceChatAnswer::getPtr();
    mClipboard = QApplication::clipboard();
    m_database = ChatDatabase::getChatDatabase();
    if (mClipboard == nullptr) {
        KyInfo() << "Cannot get QApplication::clipboard!";
    }
    return;
}

void VoiceThread::setNlpModel(QString name)
{
    if(m_chatAnswer) {
        m_chatAnswer->setModel(name);
    }
}

void VoiceThread::setDeepThinking(bool checked)
{
    if(m_chatAnswer) {
        m_chatAnswer->setDeepThinking(checked);
    }
}

void VoiceThread::setWebSearch(bool checked)
{
    if(m_chatAnswer) {
        m_chatAnswer->setWebSearch(checked);
    }
}

void VoiceThread::sendMessage(const QString message)
{
    QJsonObject data = QJsonDocument::fromJson(message.toUtf8()).object();

    if (!data.contains("msgType")) {
        KyInfo() << "Not carried msgType!";
        return;
    }

    if (!data["msgType"].isString()) {
        KyInfo() << "The type is not a string!";
        return;
    }

    QString msgType = data["msgType"].toString();
    // 启动语音通话
    if (msgType == "startVoiceChat") {
        startVoiceChat();
        return;
    }

    // 打断语音回复
    if (msgType == "interruptReply") {
        interruptReply();
        return;
    }

    // 停止语音通话
    if (msgType == "stopVoiceChat") {
        stopVoiceChat();
        return;
    }

    // 发送语音内容进行回复
    if (msgType == "sendVoiceQuestion") {
        sendVoiceQuestion(data);

    }
    // 停止问题答案回复
    if (msgType == "stopAnswerQuestionChat") {
        stopReply();
    }

    // 发送文本进行语音合成并朗读
    if (msgType == "sendAnswerTextRead") {
        QJsonObject msgBody = data["msgBody"].toObject();
        if(!msgBody.contains("answerText") || !msgBody["answerText"].isString()) {
            KyInfo() << "Not carried answerText!";

            return;
        }
        QString answerText = msgBody["answerText"].toString();
        startReading(answerText ,0);
    }

    // 发送待朗读文本进行语音合成并朗读
    if (msgType == "pushWaitingReadText") {
        QJsonObject msgBody = data["msgBody"].toObject();
        if(!msgBody.contains("waitingReadText") || !msgBody["waitingReadText"].isString()) {
            KyInfo() << "Not carried waitingReadText!";

            return;
        }

        QString answerText = msgBody["waitingReadText"].toString();
        int answerIndex = msgBody["answerIndex"].toInt();
        pushWaitingReadText(answerText,answerIndex);

    }


    // 复制所选内容
    if (msgType == "sendCopyText") {
        sendCopyText(data);

        return;
    }

    // 朗读单个回答
    if (msgType == "singleAnswerTextRead") {
        QJsonObject msgBody = data["msgBody"].toObject();
        if(!msgBody.contains("singleAnswerText") || !msgBody["singleAnswerText"].isString()) {
            KyInfo() << "Not carried singleAnswerText!";

            return;
        }
        QString answerText = msgBody["singleAnswerText"].toString();
        startSingleAnswerReading(answerText ,0);
    }

    // 暂停单个回答的朗读
    if (msgType == "singleAnswerTextPauseRead") {
        QJsonObject msgBody = data["msgBody"].toObject();
        if(!msgBody.contains("singleAnswerIndex") || !msgBody["singleAnswerIndex"].isDouble()) {
            KyInfo() << "Not carried singleAnswerText!";

            return;
        }
        int answerIndex = msgBody["singleAnswerIndex"].toInt();
        pauseSingleAnswerReading(answerIndex);
    }

    // 继续单个回答的朗读
    if (msgType == "singleAnswerTextContinueRead") {
        QJsonObject msgBody = data["msgBody"].toObject();
        if(!msgBody.contains("singleAnswerIndex") || !msgBody["singleAnswerIndex"].isDouble()) {
            KyInfo() << "Not carried singleAnswerText!";

            return;
        }
        int answerIndex = msgBody["singleAnswerIndex"].toInt();
        contiueSingleAnswerReading(answerIndex);

    }

    // 删除单个回答
    if (msgType == "deleteCurAnswer") {
        QJsonObject msgBody = data["msgBody"].toObject();
        if(!msgBody.contains("uniqueIndex") || !msgBody["uniqueIndex"].isDouble()) {
            KyInfo() << "Not carried uniqueIndex!";

            return;
        }
        if(!msgBody.contains("msgIndex") || !msgBody["msgIndex"].isDouble()) {
            KyInfo() << "Not carried msgIndex!";

            return;
        }
        int uniqueIndex = msgBody["uniqueIndex"].toInt();
        int msgIndex = msgBody["msgIndex"].toInt();
        deleteMessageByIndex(uniqueIndex, msgIndex);
    }

    return;
}

QString VoiceThread::sendMessageSync(const QString message)
{

    return QString();
}

bool VoiceThread::startVoiceChat()
{
    //TODO:概率错误时第二次进行问答，会有气泡无法提供的情况，启动后二次显示时状态码为6
    if(m_speechProxy) {
        // 先设置为初始化状态，显示加载动画
        setVoiceState(VoiceChatState::Initializing);
        
        bool startFlag = m_speechProxy->startSpeechRecognition();
        KyInfo() << "启动持续语音识别结果：" << startFlag << m_currentVoiceState;

        if(startFlag) {
            // 启动成功则设置会话ID并准备存入数据库
            this->setVoiceID(ConfigManager::getInstance()->getConfigValue("voice-id").toInt());
            // 发送信号重置唯一索引id和清空当前已有对话列表
            emit resetUniqueIndexAndModelList();
            // 注意：真正的 Recording 状态会在语音识别真正开始时通过信号切换
        } else {
            // 初始化失败，回到 Idle 状态
            setVoiceState(VoiceChatState::Idle);
        }

        return startFlag;
    }

    return false;
}

void VoiceThread::pauseVoiceChat()
{
    if(m_speechProxy) {
        m_speechProxy->pauseSpeechRecognition();
        KyInfo() << "暂停持续语音识别结果";
    }

    return;
}

void VoiceThread::continueVoiceChat()
{
    if(m_speechProxy) {
        m_speechProxy->continueSpeechRecognition();
        KyInfo() << "继续持续语音识别结果";
    }

    return;
}

void VoiceThread::stopVoiceChat()
{
    //停止回答时需要打断回复，并彻底停止语音通话

    // 标记当前为停止回答状态
    is_stopingVoice = true;

    // 停止持续语音识别
    if(m_speechProxy) {
        m_speechProxy->stopSpeechRecognition();
        m_speechProxy->closeSpeechSession();
    }
    // 打断回复
    if(m_chatAnswer && m_chatAnswer->getCurrentAnswerStatus()) {
        m_chatAnswer->interruptReply();
        m_chatAnswer->setInterrupt(true); //设置当前正在执行打断
        is_Interrupting = true;
    }
    else {
        // 不在回复状态则直接销毁会话
        closeAnswerSession();
    }
    // 打断朗读
    if(m_readerProxy && m_readerProxy->getCurrentReaderStatus()) {
        m_readerProxy->interruptReading();
    }
    else {
        // 不再朗读状态则停止朗读销毁会话
        stopReading();
        closeReaderSession();
    }

    // 如果当前不是正在打断，则将正在停止回答的状态值为false，当前结束语音通话已完成
    if(!is_Interrupting && is_stopingVoice) {
        is_stopingVoice = false;
    }
    // 结束当前会话时更新会话存储索引ID
    updateVoiceChatIndex();
    // 设置状态为完成通话状态
    setVoiceState(VoiceChatState::Finish);

    return;
}

void VoiceThread::updateVoiceChatIndex()
{
    int curID = this->getVoiceID();
    if(curID == ConfigManager::getInstance()->getConfigValue("voice-id").toInt() )
    {
        ConfigManager::getInstance()->updateConfig("voice-id",(curID + 1)%INT_MAX);
        KyInfo() << "语音通话记录id信息已更新为" << ConfigManager::getInstance()->getConfigValue("voice-id").toInt();
    }

}

void VoiceThread::interruptReply()
{

    //打断回答的核心逻辑：收到停止回答的信号，文本对话是发送停止信号，等待当前回复停止，停止后发送信号到前端
    //朗读停止是停止播放器，清空待朗读队列，将是否需要朗读置为false

    // 打断逻辑：停止AI回复，停止朗读，启动重新语音识别
    if(m_chatAnswer && m_chatAnswer->getCurrentAnswerStatus()) {
        m_chatAnswer->interruptReply();
        m_chatAnswer->setInterrupt(true); //设置当前正在执行打断
        is_Interrupting = true;
    }
    if(m_chatReader && m_chatReader->getCurrentReaderStatus()) {
        m_chatReader->interruptReading();
    }
    KyInfo() << "当前打断状态为" << is_Interrupting;
    if(is_Interrupting == false ) {
        KyInfo() << "本次打断未发现暂停项，开始执行打断后流程";
        // 非正在停止语音通话则继续进行持续语音识别，进行停止通话时在打断完成后销毁朗读会话和回答会话
        if(is_stopingVoice) {
            closeAnswerSession();
            closeReaderSession();
            //结束当前会话时更新会话存储索引ID
            updateVoiceChatIndex();
            // 设置状态为完成通话状态
            setVoiceState(VoiceChatState::Finish);
            is_stopingVoice  = false;

            return;
        }
        else {
        m_speechProxy->continueSpeechRecognition();
        setVoiceState(VoiceChatState::Recording);
        }
    }

    return;
}

void VoiceThread::interruptReplyEnd()
{
    KyInfo() << "============interruptReplyEnd=============";
    is_Interrupting = false;
    emit sigInterruptSuccessful();
    // 非正在停止语音通话则继续进行持续语音识别，进行停止时无需设置状态或进行持续语音识别
    if(!is_stopingVoice) {
        m_speechProxy->continueSpeechRecognition();
        setVoiceState(VoiceChatState::Recording);
    }
    else {
        is_stopingVoice = false;
        closeAnswerSession();
        closeReaderSession();
        //结束当前会话时更新会话存储索引ID
        updateVoiceChatIndex();
        // 设置状态为完成通话状态
        setVoiceState(VoiceChatState::Finish);
    }
    return;
}

void VoiceThread::stopReply()
{
    if(m_chatAnswer) {
        m_chatAnswer->stopReply();
        setVoiceState(VoiceChatState::Recording);
        KyInfo() << "结束问答回复";
    }

    return;
}

void VoiceThread::closeSpeechSession()
{
    if(m_speechProxy) {
        m_speechProxy->closeSpeechSession();
    }

    return;
}

void VoiceThread::slGetSpeechRecognitionResult(const QString message)
{
    if(m_currentVoiceState == VoiceChatState::Recognizing || m_currentVoiceState == VoiceChatState::Recording ||m_currentVoiceState == VoiceChatState::Initializing) {
        //发送到前端进行气泡生成
        emit receiveMessage(message);
    }
    else {
        KyInfo() << "当前持续语音识别结果不在识别和翻译状态，当前内容已抛弃，无需添加到问答中:"<<message;
    }

    return;
}

void VoiceThread::slUpdateCurrnetVolume(const int curVolume)
{
    m_currentVoiceVolume = curVolume;
    emit voiceMicVolumeChanged();
}

void VoiceThread::closeAnswerSession()
{
    if(m_chatAnswer) {
        m_chatAnswer->closeSession();
    }

    return;
}

void VoiceThread::getAnswerTextReslut(const QString msg)
{
    //只有在非空闲和完成状态下才发送消息到前端
    if(m_currentVoiceState == VoiceChatState::Idle || m_currentVoiceState == VoiceChatState::Finish) {
        KyInfo() << "当前会话处理处于空闲或完成状态中，，当前内容已抛弃，无需添加到问答中:"<<msg;
    }
    else {
        // 发送气泡到前端进行回复
        emit receiveMessage(msg);
    }

    return;
}

void VoiceThread::startReading(const QString &msg, int index)
{
    // 朗读前判断是否需要朗读，当前的状态为正在语音识别中时，无需朗读
    if (m_currentVoiceState == VoiceChatState::Recording) {
        KyInfo() << "当前已经设置状态为朗读状态，无需进行朗读";
        return;
    }

    if(m_readerProxy) {
        bool startFlag = m_readerProxy->sendReadingText(msg, index);
        if (startFlag) {
            KyInfo() << "发送待朗读文本信息成功";
            setVoiceState(VoiceChatState::Reading);
        }
    }

    return;
}

void VoiceThread::pushWaitingReadText(const QString &msg, int index)
{
    KyInfo() << "===================pushWaitingReadText==================";

    if(is_Interrupting) {
        KyInfo() << "打断状态时，不发送朗读内容";
        return;
    }
    if(!m_readerProxy){
        KyInfo() << "朗读模块已销毁";
        return;
    }
    if(m_currentVoiceState == VoiceChatState::Recording ||
        m_currentVoiceState == VoiceChatState::Recognizing) {
         KyInfo() << "当前正在录音或识别状态，不发送朗读内容";
         return;
     }
    //如果当前正在朗读，
    if(m_currentVoiceState == VoiceChatState::Reading)
    {
        int curReadIndex = m_readerProxy->getCurrentReadIndex();
        //判断当前是否为相同的索引，如果索引相同，则追加待朗读内容，
        if( curReadIndex == index) {

            KyInfo() << "当前索引相同，追加朗读内容";
            m_readerProxy->updateCurReadIndex(index);
            m_readerProxy->insertWaitingReadingListItem(msg);

        }
        //如果索引不同，则停止朗读，清空原有列表，重新开始朗读
        else {
            KyInfo() << "当前索引不相同，启动朗读内容";
            m_readerProxy->stopReading();
            m_readerProxy->clearWaitingReadingList();
            m_readerProxy->updateCurReadIndex(index);
            m_readerProxy->insertWaitingReadingListItem(msg);
        }
    }
    // 未在朗读则启动朗读
    else {
        KyInfo() << "启动朗读内容，更新索引及待朗读内容";
        m_readerProxy->updateCurReadIndex(index);
        m_readerProxy->insertWaitingReadingListItem(msg);
    }

    return;

}

void VoiceThread::stopReading()
{
    if(m_readerProxy) {
        m_readerProxy->stopReading();
        setVoiceState(VoiceChatState::Recording);
        KyInfo() << "停止朗读成功";
    }

    return;
}

void VoiceThread::closeReaderSession()
{
    if(m_readerProxy) {
        m_readerProxy->closeReaderSession();
    }

    return;
}

void VoiceThread::onCurrentReadingEnd()
{
    //朗读结束后应当重新启动持续语音识别
    if(m_speechProxy) {
        m_speechProxy->continueSpeechRecognition();
        setVoiceState(VoiceChatState::Recording);
    }
}

void VoiceThread::onShowReadingError(const QString errorMsg)
{
    //发送到前端进行气泡生成
    emit receiveMessage(errorMsg);
}

void VoiceThread::sendCopyText(const QJsonObject &data)
{
    KyInfo() << "sendCopyText : ";

    if (!data.contains("msgBody")) {
        KyInfo() << "Not carried msgBody!";
        return;
    }

    if (!data["msgBody"].isObject()) {
        KyInfo() << "The type is not an object!";
        return;
    }

    QJsonObject msgBody = data["msgBody"].toObject();
    if(!msgBody.contains("copyText") || !msgBody["copyText"].isString()) {
        KyInfo() << "Not carried copyText!";
        return;
    }

    QString copyText = msgBody["copyText"].toString();

    KyInfo() << "sendCopyText : " << copyText;

    if (mClipboard == nullptr) {
        KyInfo() << "Clipboard not initialized!";
        return;
    }

    mClipboard->setText(copyText);

    return;
}

void VoiceThread::startSingleAnswerReading(const QString &data, const int index)
{
    KyInfo() << "startSingleAnswerReading : "  << data << index;

    //当前状态判断，如果当前正在识别，则停止语音识别
    if(m_currentVoiceState == VoiceChatState::Recognizing)
    {
        m_speechProxy->stopSpeechRecognition();
    }
    //如果当前正在朗读，则打断朗读,清空原有朗读队列，并发送新的数据
    if(m_currentVoiceState == VoiceChatState::Reading)
    {
        m_readerProxy->interruptReading();
    }

    //发送朗读数据
    if(m_readerProxy) {
        m_readerProxy->updateCurReadIndex(index);
        bool startFlag = m_readerProxy->sendReadingText(data, index);
        if (startFlag) {
            KyInfo() << "发送待朗读文本信息成功";
            setVoiceState(VoiceChatState::Reading);
        }

    }

    return;
}

void VoiceThread::setAnswerStatue()
{
    if (m_currentVoiceState == VoiceChatState::Idle || m_currentVoiceState == VoiceChatState::Finish) {
            KyInfo() << "当前已停止通话，忽略回答状态设置";
            return;
        }
    KyInfo() << "根据前端收到的首次回答信号，开始设置当前回答状态为回答中";
    m_currentVoiceState = VoiceChatState::Answering;
    emit voiceStateChanged();

    return;
}

void VoiceThread::pauseSingleAnswerReading(const int index)
{
    //暂停单个朗读， TODO：是否需要判断当前暂停时区分当前正在回复内容，同时将状态切换到识别状态
    if(m_currentVoiceState != VoiceChatState::Reading)
    {
        return;
    }

    if(m_readerProxy) {
        m_readerProxy->pauseReading();
        //发送信号更新前端朗读按钮样式
        parseResetSingleAnswerReading(index);
    }
    m_speechProxy->continueSpeechRecognition();
    setVoiceState(VoiceChatState::Recording);

    return;
}

void VoiceThread::parseResetSingleAnswerReading(const int &index)
{
    QJsonObject msg;
    msg["msgType"] = "updateStatusMsg";

    QJsonObject msgBody;
    msgBody["resetReadingIndex"] = index;
    msg["msgBody"] = msgBody;

    Q_EMIT receiveMessage(QString::fromUtf8(QJsonDocument(msg).toJson()));

    return;
}

void VoiceThread::contiueSingleAnswerReading(const int index)
{
    if(m_currentVoiceState == VoiceChatState::Reading)
    {
        return;
    }

    if(m_readerProxy) {
        m_readerProxy->startReading();
    }

    return;
}

void VoiceThread::setVoiceID(int voiceID)
{
    m_voiceID = voiceID;

    return;
}

int VoiceThread::getVoiceID()
{
    return m_voiceID;
}

void VoiceThread::saveItemToDatabase(const int uniqueIndex, const QString msg)
{
    int curId = this->getVoiceID();
    QString voiceAddressString = QString("v_") + QString::number(curId);
    m_database->insertOne(voiceAddressString, uniqueIndex, msg, 2); // chatType=2 表示语音通话
    m_database->updateOperateTime(voiceAddressString, uniqueIndex); //更新第一条数据的operatime
    int voice_id_database = m_database->selectMaxVoiceHistoryId();
    int voice_id_settings  = ConfigManager::getInstance()->getConfigValue("voice-id").toInt();
    if(curId == (voice_id_database >= voice_id_settings ? voice_id_database : voice_id_settings)) {
        m_database->updateMaxVoiceHistoryId((voice_id_database >= voice_id_settings ? voice_id_database : voice_id_settings));
    }

    return;
}

void VoiceThread::deleteMessageByIndex(int uniqueIndex, int msgIndex)
{
    bool deleteResult;
    if(uniqueIndex < 1) {
        KyInfo() << "本次删除请求无法执行，删除索引必须大于等于1";
        deleteResult = false;
    }
    int curID = this->getVoiceID();
    QString addressAsString = QString("v_") + QString::number(curID);
    bool deleteAnsResult = m_database->deleteBySessionIDAndIndex(addressAsString, uniqueIndex);
    bool deleteQuesResult = m_database->deleteBySessionIDAndIndex(addressAsString, uniqueIndex -1);
    KyInfo() << "当前删除数据库语音通话记录气泡信息：" << addressAsString
                                                 << uniqueIndex
                                                 << deleteAnsResult
                                                 << deleteQuesResult;
    deleteResult = deleteAnsResult && deleteQuesResult;

    Q_EMIT deleteAnswerResult(uniqueIndex, msgIndex,deleteResult);

    return;
}

bool VoiceThread::getCurInterrupt()
{
    return is_Interrupting;
}

void VoiceThread::quitThread()
{
    quit();

    return;
}

void VoiceThread::run()
{
    QEventLoop loop;
    initVoiceThread();
    loop.exec();

    return;
}

void VoiceThread::setVoiceState(VoiceChatState newState)
{
    KyInfo() << "当前待设置的状态为：" << newState;
    m_currentVoiceState = newState;
    emit voiceStateChanged();

    return;
}

void VoiceThread::sendVoiceQuestion(const QJsonObject &data)
{
    if (!data.contains("msgBody")) {
        KyInfo() << "Not carried msgBody!";
        return;
    }

    if (!data["msgBody"].isObject()) {
        KyInfo() << "The type is not an object!";
        return;
    }

    QJsonObject msgBody = data["msgBody"].toObject();
    if(!msgBody.contains("inputMsg") || !msgBody["inputMsg"].isString()) {
        KyInfo() << "Not carried inputMsg!";
        return;
    }
    QString questionMsg = msgBody["questionMsg"].toString();
    if (m_chatAnswer  == NULL) {
        KyInfo() << "voice session  not initialized!";
        return;
    }

    KyInfo() << "voice questionMsg: " << questionMsg;
    this->pauseVoiceChat();
    this->sendQuestion(questionMsg,nullptr);
    return;
}
