#include "eaichatinfojsoncontrol.h"
#include <QStandardPaths>
#include <QJsonDocument>
#include <QJsonObject>
#include <QFile>
#include <QTextStream>
#include <QMap>

EaiChatInfoJsonControl::EaiChatInfoJsonControl()
{
    auto dirPath = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    m_chatInfoPath = dirPath + "/ChatInfo.json";
}

EaiChatInfoJsonControl &EaiChatInfoJsonControl::localChatInfoJsonControl()
{
    static EaiChatInfoJsonControl control;
    return control;
}

void EaiChatInfoJsonControl::writeChatInfoJSON(QMap<QString, QVector<uos_ai::Conversations> > assisConvs)
{
    QFile file(m_chatInfoPath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) { // 打开文件用于写入，并截断文件
        // 打开文件失败
        return;
    }
    QJsonObject chatInfoObject;
    QMapIterator<QString, QVector<uos_ai::Conversations>> i(assisConvs);
    QByteArray convsData;

    while (i.hasNext()) {
        i.next();
        uos_ai::Conversations::convs2Json(convsData, i.value());
        chatInfoObject[i.key()] =QJsonDocument::fromJson(convsData).array();
    }

    QJsonDocument chatInfoDoc(chatInfoObject);
    file.write(chatInfoDoc.toJson(QJsonDocument::Indented)); // 使用Indented格式化输出
    file.close();
}

void EaiChatInfoJsonControl::getAllChatInfoJSON(QMap<QString, QVector<uos_ai::Conversations> > &assisConvs)
{
    QJsonArray convsArray;

    QFile file(m_chatInfoPath);
    if (!file.open(QIODevice::ReadOnly)) {
        // 打开文件失败
        QJsonDocument jsonDocError(convsArray);
        return;
    }
    // 读取文件内容
    QByteArray jsonData = file.readAll();
    file.close();
    // 解析JSON
    QJsonDocument chatInfoDoc = QJsonDocument::fromJson(jsonData);
    QJsonObject jsonObject = chatInfoDoc.object();

    for (QJsonObject::const_iterator it = jsonObject.constBegin(); it != jsonObject.constEnd(); ++it) {
        QJsonDocument jsonDoc(it.value().toArray());
        QVector<uos_ai::Conversations> convs;
        uos_ai::Conversations::json2Convs(convs, jsonDoc.toJson());
        assisConvs[it.key()] = convs;
    }
}

void EaiChatInfoJsonControl::clearChatInfoJSON(QMap<QString, QVector<uos_ai::Conversations>> assisConvs)
{
    writeChatInfoJSON(assisConvs);
}



