#include "RunDataCacheRefresh.h"

#include "InteractiveData.h"
#include "InteractiveHttp.h"

#include "../user/httpclient.h"
#include "../user/config.h"
extern config *pconfig;


#include <QFile>

// 用于临时存储http json返回值的函数
void TempFuncWriteData(const QString &path, const QByteArray &data)
{
    QFile file(path);
    if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        file.write(data);
        file.close();
    }
}


RunDataCacheRefresh::RunDataCacheRefresh(InteractiveTask *task, QMutex *mutex)
    : RunAbstract(task, mutex)
{


}

void RunDataCacheRefresh::run()
{
    // 获取物资属性值
    httpGetMaterialProp();
    // 获取物资类型
    httpGetMaterialType();
    // 获取物资信息
    // httpGetMaterialInfo();


    // // 获取异常类型字典值
    // httpGetExceptionTypeDict();
    // // 获取严重等级字典值
    // httpGetSeverityLevelDict();
    // 获取异常物资信息
    httpGetExMaterialInfo();

    // 获取物资柜物资错放异常

}


void RunDataCacheRefresh::httpGetMaterialProp()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();
    // 访问http服务
    QString strUrl = "http://" + pconfig->httpHost + pconfig->getMaterialPropList_url;
    QByteArray inData = QString("cabinetCode=" + pconfig->devUuid).toUtf8();
    QByteArray outData;

    httpClient::getRequest(strUrl, pSingletonData->m_token, inData, outData);

    // 进行数据写操作
    QWriteLocker locker(&pSingletonData->m_dataCacheLock);

    // 如果数据发生改变，缓存信息
    if (pSingletonData->m_jsonCacheMaterialProp != outData)
    {
        // 缓存json信息
        pSingletonData->m_jsonCacheMaterialProp = outData;

        // 清理缓存数据
        pSingletonData->m_dataCacheMaterialPropId.clear();
        pSingletonData->m_dataCacheMaterialPropName.clear();
        pSingletonData->m_dataCacheMaterialPropPropertyId.clear();
        pSingletonData->m_dataCacheMaterialPropPropertyName.clear();

        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &error);
        if (error.error == QJsonParseError::NoError)
        {
            if(!(jsonDoc.isNull() || jsonDoc.isEmpty()))
            {
                QJsonObject jsonObjRoot = jsonDoc.object();
                if(jsonObjRoot.contains("code") && jsonObjRoot.contains("data"))
                {
                    QJsonObject jsonObjData = jsonObjRoot.value("data").toObject();
                    if(jsonObjRoot.value("code").toInt() == 200 && jsonObjData.contains("records"))
                    {
                        QJsonArray jsonArrRecords = jsonObjData.value("records").toArray();
                        for (int i = 0; i < jsonArrRecords.count(); ++i)
                        {
                            if (!jsonArrRecords.at(i).isObject())
                            {
                                continue;
                            }

                            QJsonObject jsonObjRecord = jsonArrRecords.at(i).toObject();

                            QString recordId = jsonObjRecord.value("recordId").toString();
                            QString valueName = jsonObjRecord.value("valueName").toString();
                            QString propertyId = jsonObjRecord.value("propertyId").toString();
                            QString propertyName = jsonObjRecord.value("propertyName").toString();


                            pSingletonData->m_dataCacheMaterialPropId.append(recordId);
                            pSingletonData->m_dataCacheMaterialPropName.insert(recordId, valueName);
                            pSingletonData->m_dataCacheMaterialPropPropertyId.insert(recordId, propertyId);
                            pSingletonData->m_dataCacheMaterialPropPropertyName.insert(recordId, propertyName);

                        }
                    }
                }
            }
        }
    }
}
void RunDataCacheRefresh::httpGetMaterialType()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();
    // 访问http服务
    QString strUrl = "http://" + pconfig->httpHost + pconfig->getMaterialTypeList_url;
    QByteArray inData = QString("current=1&size=-1").toUtf8();
    QByteArray outData;

    httpClient::getRequest(strUrl, pSingletonData->m_token, inData, outData);


    // 进行数据写操作
    QWriteLocker locker(&pSingletonData->m_dataCacheLock);


    // 如果数据发生改变，缓存信息
    if (pSingletonData->m_jsonCacheMaterialType != outData)
    {
        // 缓存json信息
        pSingletonData->m_jsonCacheMaterialType = outData;

        // 清理缓存数据
        pSingletonData->m_dataCacheMaterialTypeId.clear();
        pSingletonData->m_dataCacheMaterialTypeName.clear();
        pSingletonData->m_dataCacheMaterialTypePicture.clear();
        pSingletonData->m_dataCacheMaterialTypeAncestors.clear();
        pSingletonData->m_dataCacheMaterialTypePropertyIds.clear();


        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &error);
        if (error.error == QJsonParseError::NoError)
        {
            if(!(jsonDoc.isNull() || jsonDoc.isEmpty()))
            {
                QJsonObject jsonObjRoot = jsonDoc.object();
                if(jsonObjRoot.contains("code") && jsonObjRoot.contains("data"))
                {
                    QJsonObject jsonObjData = jsonObjRoot.value("data").toObject();
                    if(jsonObjRoot.value("code").toInt() == 200 && jsonObjData.contains("records"))
                    {
                        QJsonArray jsonArrRecords = jsonObjData.value("records").toArray();
                        for (int i = 0; i < jsonArrRecords.count(); ++i)
                        {
                            if (!jsonArrRecords.at(i).isObject())
                            {
                                continue;
                            }

                            QJsonObject jsonObjRecord = jsonArrRecords.at(i).toObject();

                            QString materialsTypeId = jsonObjRecord.value("materialsTypeId").toString();
                            QString materialsTypeName = jsonObjRecord.value("materialsTypeName").toString();
                            QString materialsTypeIcon = jsonObjRecord.value("materialsTypeIcon").toString();
                            QString materialsTypePicture = jsonObjRecord.value("materialsTypePicture").toString();
                            QStringList ancestors = jsonObjRecord.value("ancestors").toString().split(",");
                            QStringList propertyIds = jsonObjRecord.value("propertyIds").toString().split(",");

                            pSingletonData->m_dataCacheMaterialTypeId.append(materialsTypeId);
                            pSingletonData->m_dataCacheMaterialTypeName.insert(materialsTypeId, materialsTypeName);
                            pSingletonData->m_dataCacheMaterialTypeIcon.insert(materialsTypeId, materialsTypeIcon);
                            pSingletonData->m_dataCacheMaterialTypePicture.insert(materialsTypeId, materialsTypePicture);
                            pSingletonData->m_dataCacheMaterialTypeAncestors.insert(materialsTypeId, ancestors);
                            pSingletonData->m_dataCacheMaterialTypePropertyIds.insert(materialsTypeId, propertyIds);

                        }
                    }
                }
            }
        }
    }
}

void RunDataCacheRefresh::httpGetMaterialInfo()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();
    // 访问http服务
    QString strUrl = "http://" + pconfig->httpHost + pconfig->getMaterialInfoList_url;
    QByteArray inData = QString("cabinetCode=" + pconfig->devUuid).toUtf8();
    QByteArray outData;

    httpClient::getRequest(strUrl, pSingletonData->m_token, inData, outData);


    // 进行数据写操作
    QWriteLocker locker(&pSingletonData->m_dataCacheLock);
    // 如果数据发生改变，缓存信息
    if (pSingletonData->m_jsonCacheMaterialInfo != outData)
    {
        // 缓存json信息
        pSingletonData->m_jsonCacheMaterialInfo = outData;

        // 清理缓存数据
        pSingletonData->m_dataCacheMaterialInfoId.clear();
        pSingletonData->m_dataCacheMaterialInfoName.clear();
        pSingletonData->m_dataCacheMaterialInfoRfid.clear();
        pSingletonData->m_dataCacheMaterialInfoStat.clear();
        pSingletonData->m_dataCacheMaterialInfoDate.clear();
        pSingletonData->m_dataCacheMaterialInfoTypeId.clear();


        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &error);
        if (error.error == QJsonParseError::NoError)
        {
            if(!(jsonDoc.isNull() || jsonDoc.isEmpty()))
            {
                QJsonObject jsonObjRoot = jsonDoc.object();
                if(jsonObjRoot.contains("code") && jsonObjRoot.contains("data"))
                {
                    QJsonObject jsonObjData = jsonObjRoot.value("data").toObject();
                    if(jsonObjRoot.value("code").toInt() == 200 && jsonObjData.contains("records"))
                    {
                        QJsonArray jsonArrRecords = jsonObjData.value("records").toArray();
                        for (int i = 0; i < jsonArrRecords.count(); ++i)
                        {
                            if (!jsonArrRecords.at(i).isObject())
                            {
                                continue;
                            }

                            QJsonObject jsonObjRecord = jsonArrRecords.at(i).toObject();

                            QString materialsId = jsonObjRecord.value("materialsId").toString();
                            QString materialsName = jsonObjRecord.value("materialsName").toString();
                            QString materialsRfid = jsonObjRecord.value("materialsRfid").toString();
                            QString expirationDate = jsonObjRecord.value("expirationDate").toString();
                            QString materialsTypeId = jsonObjRecord.value("materialsTypeId").toString();
                            QString propertiesValueId = jsonObjRecord.value("propertiesValueId").toString();
                            QString loanState = jsonObjRecord.value("loanState").toString();
                            QString status = jsonObjRecord.value("status").toString();

                            pSingletonData->m_dataCacheMaterialInfoId.append(materialsId);
                            pSingletonData->m_dataCacheMaterialInfoName.insert(materialsId, materialsName);
                            pSingletonData->m_dataCacheMaterialInfoRfid.insert(materialsId, materialsRfid);
                            pSingletonData->m_dataCacheMaterialInfoLoan.insert(materialsId, loanState);
                            pSingletonData->m_dataCacheMaterialInfoStat.insert(materialsId, status);
                            pSingletonData->m_dataCacheMaterialInfoDate.insert(materialsId, expirationDate);
                            pSingletonData->m_dataCacheMaterialInfoTypeId.insert(materialsId, materialsTypeId);
                            pSingletonData->m_dataCacheMaterialInfoPropId.insert(materialsId, propertiesValueId);

                            // 如果类型不存在

                            if (materialsTypeId != "")
                            {
                                if (!pSingletonData->m_dataCacheMaterialTypeId.contains(materialsTypeId))
                                {
                                    QString materialsTypeName = jsonObjRecord.value("materialsTypeName").toString();
                                    QString materialsTypeIcon = jsonObjRecord.value("materialsTypeIcon").toString();
                                    QString materialsTypePicture = jsonObjRecord.value("materialsTypePicture").toString();

                                    // ...

                                    pSingletonData->m_dataCacheMaterialTypeId.append(materialsTypeId);
                                    pSingletonData->m_dataCacheMaterialTypeName.insert(materialsTypeId, materialsTypeName);
                                    pSingletonData->m_dataCacheMaterialTypeIcon.insert(materialsTypeId, materialsTypeIcon);
                                    pSingletonData->m_dataCacheMaterialTypePicture.insert(materialsTypeId, materialsTypePicture);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}


void RunDataCacheRefresh::httpGetExceptionTypeDict()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();
    // 访问http服务，获取字典值
    QString strUrl = "http://" + pconfig->httpHost + "/dev-api/system/dict/data/type/" + "exception_type";
    QByteArray inData;
    QByteArray outData;

    httpClient::getRequest(strUrl, pSingletonData->m_token, inData, outData);

    // // 进行数据写操作
    // QWriteLocker locker(&pSingletonData->m_dataCacheLock);
    // // 如果数据发生改变，缓存信息
    // if (pSingletonData->m_jsonCacheExceptionTypeDict != outData)
    // {
    //     // 缓存json信息
    //     pSingletonData->m_jsonCacheExceptionTypeDict = outData;


    //     // 异常类型字典清理数据缓存
    //     pSingletonData->m_dataCacheExceptionTypeDictCode.clear();
    //     pSingletonData->m_dataCacheExceptionTypeDictLabel.clear();
    //     pSingletonData->m_dataCacheExceptionTypeDictValue.clear();


    //     QJsonParseError error;
    //     QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &error);
    //     if (error.error == QJsonParseError::NoError)
    //     {
    //         if(!(jsonDoc.isNull() || jsonDoc.isEmpty()))
    //         {
    //             QJsonObject jsonObjRoot = jsonDoc.object();
    //             if(jsonObjRoot.contains("code") && jsonObjRoot.contains("data"))
    //             {
    //                 if (jsonObjRoot.value("code").toInt() == 200 && jsonObjRoot.value("data").isArray())
    //                 {
    //                     QJsonArray jsonArrData = jsonObjRoot.value("data").toArray();

    //                     for (int i = 0; i < jsonArrData.size(); ++i)
    //                     {
    //                         if (!jsonArrData.at(i).isObject())
    //                         {
    //                             continue;
    //                         }
    //                         QJsonObject jsonObjData = jsonArrData.at(i).toObject();

    //                         QString dictCode = jsonObjData.value("dictCode").toString();
    //                         QString dictLabel = jsonObjData.value("dictLabel").toString();
    //                         QString dictValue = jsonObjData.value("dictValue").toString();

    //                         if (pSingletonData->m_dataCacheExceptionTypeDictCode.contains(dictCode))
    //                         {
    //                             continue;
    //                         }

    //                         pSingletonData->m_dataCacheExceptionTypeDictCode.append(dictCode);
    //                         pSingletonData->m_dataCacheExceptionTypeDictLabel.insert(dictCode, dictLabel);
    //                         pSingletonData->m_dataCacheExceptionTypeDictValue.insert(dictCode, dictValue);
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }

}

void RunDataCacheRefresh::httpGetSeverityLevelDict()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();
    // 访问http服务，获取字典值
    QString strUrl = "http://" + pconfig->httpHost + "/dev-api/system/dict/data/type/" + "severity_level";
    QByteArray inData;
    QByteArray outData;

    httpClient::getRequest(strUrl, pSingletonData->m_token, inData, outData);

    // // 进行数据写操作
    // QWriteLocker locker(&pSingletonData->m_dataCacheLock);
    // // 如果数据发生改变，缓存信息
    // if (pSingletonData->m_jsonCacheSeverityLevelDict != outData)
    // {
    //     // 缓存json信息
    //     pSingletonData->m_jsonCacheSeverityLevelDict = outData;


    //     // 异常类型字典清理数据缓存
    //     pSingletonData->m_dataCacheSeverityLevelDictCode.clear();
    //     pSingletonData->m_dataCacheSeverityLevelDictLabel.clear();
    //     pSingletonData->m_dataCacheSeverityLevelDictValue.clear();


    //     QJsonParseError error;
    //     QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &error);
    //     if (error.error == QJsonParseError::NoError)
    //     {
    //         if(!(jsonDoc.isNull() || jsonDoc.isEmpty()))
    //         {
    //             QJsonObject jsonObjRoot = jsonDoc.object();
    //             if(jsonObjRoot.contains("code") && jsonObjRoot.contains("data"))
    //             {
    //                 if (jsonObjRoot.value("code").toInt() == 200 && jsonObjRoot.value("data").isArray())
    //                 {
    //                     QJsonArray jsonArrData = jsonObjRoot.value("data").toArray();

    //                     for (int i = 0; i < jsonArrData.size(); ++i)
    //                     {
    //                         if (!jsonArrData.at(i).isObject())
    //                         {
    //                             continue;
    //                         }
    //                         QJsonObject jsonObjData = jsonArrData.at(i).toObject();

    //                         QString dictCode = jsonObjData.value("dictCode").toString();
    //                         QString dictLabel = jsonObjData.value("dictLabel").toString();
    //                         QString dictValue = jsonObjData.value("dictValue").toString();

    //                         if (pSingletonData->m_dataCacheSeverityLevelDictCode.contains(dictCode))
    //                         {
    //                             continue;
    //                         }

    //                         pSingletonData->m_dataCacheSeverityLevelDictCode.append(dictCode);
    //                         pSingletonData->m_dataCacheSeverityLevelDictLabel.insert(dictCode, dictLabel);
    //                         pSingletonData->m_dataCacheSeverityLevelDictValue.insert(dictCode, dictValue);
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }

}

void RunDataCacheRefresh::httpGetExMaterialInfo()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();

    // 访问http服务
    QString strUrl = "http://" + pconfig->httpHost + pconfig->getExMaterialInfoList_url;
    QByteArray inData = QString("cabinetCode=" + pconfig->devUuid).toUtf8();
    QByteArray outData;

    httpClient::getRequest(strUrl, pSingletonData->m_token, inData, outData);


    qDebug() << outData;
    // 进行数据写操作
    QWriteLocker locker(&pSingletonData->m_dataCacheLock);
    // 如果数据发生改变，缓存信息
    if (pSingletonData->m_jsonCacheExMaterialInfo != outData)
    {
        // 缓存json信息
        pSingletonData->m_jsonCacheExMaterialInfo = outData;

        pSingletonData->m_dataCacheExMaterialTypeId.clear();
        pSingletonData->m_dataCacheExMaterialTypeExNumber.clear();

        // 物资信息清理数据缓存
        pSingletonData->m_dataCacheExMaterialInfoId.clear();
        pSingletonData->m_dataCacheExMaterialInfoName.clear();
        pSingletonData->m_dataCacheExMaterialInfoRfid.clear();
        pSingletonData->m_dataCacheExMaterialInfoStat.clear();
        pSingletonData->m_dataCacheExMaterialInfoDate.clear();
        pSingletonData->m_dataCacheExMaterialInfoTypeId.clear();
        pSingletonData->m_dataCacheExMaterialInfoPropId.clear();

        QJsonParseError error;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &error);
        if (error.error == QJsonParseError::NoError)
        {
            if(!(jsonDoc.isNull() || jsonDoc.isEmpty()))
            {
                QJsonObject jsonObjRoot = jsonDoc.object();
                if(jsonObjRoot.contains("code") && jsonObjRoot.contains("data"))
                {
                    if (jsonObjRoot.value("code").toInt() == 200)
                    {
                        QJsonArray jsonArrData = jsonObjRoot.value("data").toArray();

                        for (int i = 0; i < jsonArrData.size(); ++i)
                        {
                            if (!jsonArrData.at(i).isObject())
                            {
                                continue;
                            }

                            QJsonObject jsonObjData = jsonArrData.at(i).toObject();

                            if (!jsonObjData.contains("materials"))
                            {
                                continue;
                            }


                            QString materialsTypeName = jsonObjData.value("materialsTypeName").toString();
                            QString materialsTypeId = jsonObjData.value("materialsTypeId").toString();
                            int exNumber = jsonObjData.value("exNumber").toInt();


                            if (materialsTypeId == "0")
                            {
                                continue;
                            }

                            if (!pSingletonData->m_dataCacheExMaterialTypeId.contains(materialsTypeId))
                            {
                                pSingletonData->m_dataCacheExMaterialTypeId.append(materialsTypeId);
                                pSingletonData->m_dataCacheExMaterialTypeExNumber.insert(materialsTypeId, exNumber);
                            }

                            if (materialsTypeName == "全部")
                            {
                                continue;
                            }

                            QJsonArray jsonArrRecords = jsonObjData.value("materials").toArray();

                            for (int j = 0; j < jsonArrRecords.count(); ++j)
                            {
                                if (!jsonArrRecords.at(j).isObject())
                                {
                                    continue;
                                }

                                QJsonObject jsonObjMaterials = jsonArrRecords.at(j).toObject();

                                QString materialsId = jsonObjMaterials.value("materialsId").toString();
                                QString materialsName = jsonObjMaterials.value("materialsName").toString();
                                QString materialsRfid = jsonObjMaterials.value("materialsRfid").toString();
                                QString expirationDate = jsonObjMaterials.value("expirationDate").toString();
                                QString materialsTypeId = jsonObjMaterials.value("materialsTypeId").toString();
                                QString propertiesValueId = jsonObjMaterials.value("propertiesValueId").toString();
                                QString loanState = jsonObjMaterials.value("loanState").toString();
                                QString status = jsonObjMaterials.value("status").toString();

                                if (pSingletonData->m_dataCacheExMaterialInfoId.contains(materialsId))
                                {
                                    continue;
                                }

                                pSingletonData->m_dataCacheExMaterialInfoId.append(materialsId);
                                pSingletonData->m_dataCacheExMaterialInfoName.insert(materialsId, materialsName);
                                pSingletonData->m_dataCacheExMaterialInfoRfid.insert(materialsId, materialsRfid);
                                pSingletonData->m_dataCacheExMaterialInfoLoan.insert(materialsId, loanState);
                                pSingletonData->m_dataCacheExMaterialInfoStat.insert(materialsId, status);
                                pSingletonData->m_dataCacheExMaterialInfoDate.insert(materialsId, expirationDate);
                                pSingletonData->m_dataCacheExMaterialInfoTypeId.insert(materialsId, materialsTypeId);
                                pSingletonData->m_dataCacheExMaterialInfoPropId.insert(materialsId, propertiesValueId);
                            }
                        }
                    }
                }
            }
        }
    }
}
