#include "RunMaterialManualReplaceSubmit.h"

#include "InteractiveData.h"
#include "InteractiveConf.h"

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

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

}

void RunMaterialManualReplaceSubmit::run()
{
    InteractiveData *pSingletonData = SINGLETON_CREATE(InteractiveData)();

    QStringList currentRegular; // 正常的
    QStringList currentUnusual; // 异常的
    QStringList currentCabinet; // 柜中的

    // 获取正常物资
    for(auto it = pconfig->materialLoanStateList.cbegin(); it != pconfig->materialLoanStateList.cend(); ++it)
    {
        if(it.value() == SERVER_MATERIAL_LOANSTATE_IN)
        {
            currentRegular.append(it.key());
        }
    }

    // 获取异常物资
    currentUnusual = InteractiveConf::confReadElseMaterials();
    currentCabinet = currentRegular + currentUnusual;


    QJsonObject jsonObjRoot;
    QJsonArray jsonArrList;
    for (int i = 0; i < pSingletonData->m_modelMaterialManualReplace.count(); ++i)
    {
        QVariantMap info = pSingletonData->m_modelMaterialManualReplace.get(i);

        QJsonObject jsonObjData;

        int click = info.value("click").toInt();

        // 维修
        if (click == 1)
        {
            jsonObjData.insert("measure", "维修");
        }
        // 更换
        else if(click == 2)
        {
            jsonObjData.insert("measure", "更换");
        }
        else
        {
            continue;
        }

        QString newMaterialsRfid = info.value("materialsRfid").toString();
        QString oldMaterialsRfid = info.value("oldMaterialsRfid").toString();

        if (oldMaterialsRfid == newMaterialsRfid)
        {
            if (!currentCabinet.contains(oldMaterialsRfid))
            {
                setRespond(QString("{\"code\":-1,\"msg\":\"属于本柜的物资%1不在柜中，请放入\"}").arg(oldMaterialsRfid));
                return;
            }
        }
        else
        {
            if (currentCabinet.contains(oldMaterialsRfid))
            {
                setRespond(QString("{\"code\":-1,\"msg\":\"不属于本柜的物资%1在柜中，请取出\"}").arg(oldMaterialsRfid));
                return;
            }
            if (!currentCabinet.contains(newMaterialsRfid))
            {
                setRespond(QString("{\"code\":-1,\"msg\":\"属于本柜的物资%1不在柜中，请放入\"}").arg(newMaterialsRfid));
                return;
            }
        }

        if (oldMaterialsRfid != newMaterialsRfid)
        {
            currentUnusual.removeAll(newMaterialsRfid);
        }

        jsonObjData.insert("expirationDate", info.value("expirationDate").toString());
        jsonObjData.insert("materialsName", info.value("materialsName").toString());
        jsonObjData.insert("materialsRfid", info.value("materialsRfid").toString());
        jsonObjData.insert("oldMaterialsId", info.value("materialsId").toString());


        QString selectedTypeName = info.value("materialsTypeName").toString();
        QString selectedPropName = info.value("propertiesValue").toString();


        QVariantList types = info.value("types").toList();
        for (int i = 0; i < types.size(); ++i)
        {
            QVariantMap type = types.at(i).toMap();
            QString typeName = type.value("display").toString();
            if (typeName == selectedTypeName)
            {
                jsonObjData.insert("materialsTypeId", type.value("materialsTypeId").toString());

                QVariantList props = type.value("props").toList();
                for (int j = 0; j < props.size(); ++j)
                {
                    QVariantMap prop = props.at(j).toMap();
                    QString propName = prop.value("display").toString();

                    if (propName == selectedPropName)
                    {
                        jsonObjData.insert("propertiesProperty", prop.value("propertiesProperty").toString());
                        jsonObjData.insert("propertiesPropertyId", prop.value("propertiesPropertyId").toString());
                        jsonObjData.insert("propertiesValue", prop.value("propertiesValue").toString());
                        jsonObjData.insert("propertiesValueId", prop.value("propertiesValueId").toString());
                    }
                }
            }
        }

        jsonArrList.append(jsonObjData);
    }

    jsonObjRoot.insert("list", jsonArrList);

    QJsonDocument jsonDoc(jsonObjRoot);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);

    // 访问http服务
    QString strUrl = "http://" + pconfig->httpHost + pconfig->postMaterialReplace_url;
    QByteArray inData = jsonData;
    QByteArray outData;

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

    setRespond(outData);

    // 解析 JSON 数据
    if (!outData.isEmpty())
    {
        QJsonParseError parseError;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(outData, &parseError);

        if (parseError.error != QJsonParseError::NoError)
        {
            qWarning() << "JSON 解析错误:" << parseError.errorString();
            return;
        }

        if (!jsonDoc.isObject())
        {
            qWarning() << "JSON 数据不是对象";
            return;
        }

        QJsonObject jsonObjRoot = jsonDoc.object();

        // 检查 code 字段
        if (jsonObjRoot["code"].toInt() == 200) {
            InteractiveConf::confSaveElseMaterials(currentUnusual);
        } else {
            qWarning() << "返回码不为 200，实际为:" << jsonObjRoot["code"].toInt();
        }
    }


    qDebug() << outData;
}
