#include "HttpGetWorkNodeDetail.h"

#include <QJsonObject>
#include <QJsonArray>
#include <QFile>

#include "WorkNodeFormModel.h"
#include "../usr/config.h"
#include "../interactive/InteractiveData.h"

QJsonObject parseJsonString(const QString jsonStr)
{
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonStr.toUtf8());
    if (!jsonDoc.isNull() && !jsonDoc.isEmpty() && jsonDoc.isObject()) {
        return jsonDoc.object();
    }
    return QJsonObject();
}

bool parseJsonToFormControl(const QJsonObject& jsonObj, FormControl& formControl)
{
    if (jsonObj.contains("id")) {
        formControl.m_id = jsonObj.value("id").toString();
    }
    // 控件名称
    if (jsonObj.contains("label")) {
        formControl.m_label = jsonObj.value("label").toString();
    }
    // 控件类型
    if (jsonObj.contains("type")) {
        formControl.m_type = jsonObj.value("type").toString();
    }
    // 字段名称
    if (jsonObj.contains("name")) {
        formControl.m_name = jsonObj.value("name").toString();
    }
    // 可选操作
    if (jsonObj.contains("options")) {
        QJsonArray fieldOptions = jsonObj.value("options").toArray();
        formControl.m_options.clear();
        for (auto iter = fieldOptions.begin(); iter != fieldOptions.end(); ++iter) {
            if (!iter->isObject()) {
                continue;
            }
            QString label, value;
            QJsonObject iterObj = iter->toObject();
            if (iterObj.contains("label")) {
                label = iterObj.value("label").toString();
            }
            if (iterObj.contains("value")) {
                value = iterObj.value("value").toString();
            }
            formControl.m_options.append(QString("%1,%2").arg(label, value));
        }
    }
    // 占位符文本
    if (jsonObj.contains("placeholder")) {
        formControl.m_placeholder = jsonObj.value("placeholder").toString();
    }
    if (jsonObj.contains("required")) {
        formControl.m_required = jsonObj.value("required").toBool(false);
    }
    if (jsonObj.contains("requiredMessage")) {
        formControl.m_requiredMsg = jsonObj.value("requiredMessage").toString();
    }
    if (jsonObj.contains("gridColumns")) {
        formControl.m_gridColumns = jsonObj.value("gridColumns").toInt();
    }
    // 表单回显值
    if (jsonObj.contains("value")) {
        if (jsonObj.value("value").isString()) {
            formControl.m_value = jsonObj.value("value").toString();
        } else if (jsonObj.value("value").isBool()) {
            formControl.m_value = jsonObj.value("value").toBool() ? "true" : "false";
        } else if (jsonObj.value("value").isDouble()) {
            formControl.m_value = QString::number(jsonObj.value("value").toDouble());
        }
    }
    return true;
}

HttpGetWorkNodeDetail::HttpGetWorkNodeDetail(QObject *parent)
    : QThread(parent)
{

}

HttpGetWorkNodeDetail::~HttpGetWorkNodeDetail()
{
    clearWorkNodeFormModel();
}

void HttpGetWorkNodeDetail::clearWorkNodeFormModel()
{
    WorkNodeFormModel::instance()->clear();
    WorkNodeFormModel::instance()->setFormJsonInfo("");
    WorkNodeFormModel::instance()->setFormName("");
    WorkNodeFormModel::instance()->setDescription("");
}

void HttpGetWorkNodeDetail::run()
{

    httpRequestGetWorkNodeDetail();
}

void HttpGetWorkNodeDetail::httpRequestGetWorkNodeDetail()
{
    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->workNodeDetail;
    jsonRoot.insert("nodeId", this->m_nodeId);
    qDebug() << "[HttpGetWorkNodeDetail] " << url << this->m_nodeId;

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

    emit signalGetRequestData(timestampSeconds, url, jsonData, GetInteractiveData()->m_token);
}

void HttpGetWorkNodeDetail::httpRequestGetFormById()
{
    if (m_formId == 0) return;

    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->workNodeDetailForm;
    jsonRoot.insert("id", this->m_formId);

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

    emit signalGetRequestData(timestampSeconds, url, jsonData, GetInteractiveData()->m_token);
}

void HttpGetWorkNodeDetail::slotHttpResponseGetWorkNodeDetail(QByteArray data)
{
    clearWorkNodeFormModel();
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
        return;
    }
    if (jsonDoc.isNull() || jsonDoc.isEmpty()) {
        emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("code")) {
        int codeValue = rootObj.value("code").toInt();
        if (codeValue == 408) {
            emit signalWorkNodeDetailReturnStat(408, "处理超时，请稍后重试。");
            return;
        }
        if(codeValue == 200 || codeValue == 0) {
            if(rootObj.contains("data")) {
                QJsonObject vDataObj = rootObj.value("data").toObject();
                if (vDataObj.empty()) {
                    emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
                    return;
                }

                if (vDataObj.contains("formId")) {
                    m_formId = vDataObj.value("formId").toInt();
                }

                if (!vDataObj.contains("formData")) {
                    httpRequestGetFormById();
                    return;
                }

                if (!vDataObj.contains("type")) {
                    emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
                    return;
                }
                if (vDataObj.contains("id") && vDataObj.value("id").isDouble()) {
                    WorkNodeFormModel::instance()->setWorkId(vDataObj.value("id").toInt());
                }

                if (vDataObj.contains("isolationPoints") && vDataObj.value("isolationPoints").isString()) {
                    QString isolationPoints = vDataObj.value("isolationPoints").toString();
                    WorkNodeFormModel::instance()->setIsolationPoints(isolationPoints);
                }
                if (vDataObj.contains("nodeUserList") && vDataObj.value("nodeUserList").isArray()) {
                    WorkNodeFormModel::instance()->setNodeUserList(vDataObj.value("nodeUserList").toArray());
                }
                if (vDataObj.contains("points") && vDataObj.value("points").isArray()) {
                    WorkNodeFormModel::instance()->setPointsList(vDataObj.value("points").toArray());
                }
                // 页面分类：审核、录入信息
                WorkNodeFormModel::instance()->setModelType(vDataObj.value("type").toString());
                // 任务进度(1取设备 /解除共锁 2上锁/取设备解锁 3共锁/还设备)
                if (vDataObj.contains("nodeProgress")) {
                    WorkNodeFormModel::instance()->setNodeProgress(vDataObj.value("nodeProgress").toString());
                }
                if (vDataObj.contains("workerUserName")) {
                    WorkNodeFormModel::instance()->setWorkerName(vDataObj.value("initiatorName").toString());
                }
                if (vDataObj.contains("orderNo")) {
                    WorkNodeFormModel::instance()->setOrderNo(vDataObj.value("orderNo").toString());
                }
                if (vDataObj.contains("nodeName")) {
                    WorkNodeFormModel::instance()->setNodeNmae(vDataObj.value("nodeName").toString());
                }

                QJsonObject formData = parseJsonString(vDataObj.value("formData").toString());
                WorkNodeFormModel::instance()->setFormJsonInfo(vDataObj.value("formData").toString());
                
                // description：优先从 data 根取，若无则从 formData 取（仅审核等接口可能返回）
                if (vDataObj.contains("description") && vDataObj.value("description").isString()) {
                    WorkNodeFormModel::instance()->setDescription(vDataObj.value("description").toString());
                } else if (formData.contains("description") && formData.value("description").isString()) {
                    WorkNodeFormModel::instance()->setDescription(formData.value("description").toString());
                } else {
                    WorkNodeFormModel::instance()->setDescription("");
                }
                
                if (formData.isEmpty()) {
                    emit signalWorkNodeDetailReturnStat(0, "解析表单页完成");
                    return;
                }
                // 解析表单名称（当前任务名称）
                if (formData.contains("name") && formData.value("name").isString()) {
                    WorkNodeFormModel::instance()->setFormName(formData.value("name").toString());
                } else {
                    WorkNodeFormModel::instance()->setFormName("");
                }
                
                // 解析单个页面表单信息
                int gridColumns = 1;
                if (formData.contains("conf")) {
                    QJsonObject confObj = parseJsonString(formData.value("conf").toString());
                    if (confObj.contains("formConfig")) {
                        QJsonObject formConfObj = confObj.value("formConfig").toObject();
                        if (formConfObj.contains("layoutColumns")) {
                            gridColumns = formConfObj.value("layoutColumns").toInt(1);
                        }
                    }
                }
                if (!formData.contains("fields")) {
                    httpRequestGetFormById();
                    return;
                }
                if (!formData.value("fields").isArray()) {
                    emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
                    return;
                }
                QJsonArray fieldsList = formData.value("fields").toArray();

                int gridIndex = 0;
                for (auto iter = fieldsList.begin(); iter != fieldsList.end(); ++iter, gridIndex++) {
                    QJsonDocument fieldDoc = QJsonDocument::fromJson(QByteArray::fromStdString(iter->toString().toStdString().c_str()));
                    QJsonObject fieldRoot = fieldDoc.object();
                    // 当前控件
                    FormControl formControl;

                    if (!parseJsonToFormControl(fieldRoot, formControl)) {
                        continue;
                    }

                    formControl.m_gridCount = fieldsList.count();
                    formControl.m_gridColumns = gridColumns;
                    formControl.m_gridGroupName = "formData";
                    formControl.m_gridIndex = gridIndex;
                    WorkNodeFormModel::instance()->append(formControl);

                    // gridColumns = formControl.m_gridColumns;
                    // gridCount = 0;
                    // if (formControl.m_type != "grid") {
                    //     formControl.m_parentFieldId = formControl.m_id;     // 如果不是grid布局，那么其父id就是其本身
                    //     WorkNodeFormModel::instance()->append(formControl);
                    // }
                    // // 子控件
                    // if (!fieldRoot.contains("children")) {
                    //     continue;
                    // }
                    // if (!fieldRoot.value("children").isArray()) {
                    //     continue;
                    // }

                    // QJsonArray childrenArr = fieldRoot.value("children").toArray();
                    // gridCount = childrenArr.count();
                    // int gridIndex = 0;
                    // for (auto iter = childrenArr.begin(); iter != childrenArr.end(); ++iter, gridIndex++) {
                    //     if (!iter->isObject()) {
                    //         continue;
                    //     }
                    //     QJsonObject iterObj = iter->toObject();
                    //     FormControl subFormControl;
                    //     if (!parseJsonToFormControl(iterObj, subFormControl)) {
                    //         continue;
                    //     }

                    //     subFormControl.m_parentFieldId = formControl.m_id;
                    //     subFormControl.m_gridColumns = gridColumns;
                    //     subFormControl.m_gridIndex = gridIndex;
                    //     subFormControl.m_gridCount = gridCount;
                    //     WorkNodeFormModel::instance()->append(subFormControl);
                    // }
                }
                emit signalWorkNodeDetailReturnStat(0, "解析表单页完成");
            }
        }
    }
}

void HttpGetWorkNodeDetail::slotHttpResponseGetFormById(QByteArray data)
{
    clearWorkNodeFormModel();
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
        return;
    }
    if (jsonDoc.isNull() || jsonDoc.isEmpty()) {
        emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("code"))
    {
        int codeValue = rootObj.value("code").toInt();
        if (codeValue == 408) {
            emit signalWorkNodeDetailReturnStat(408, "处理超时，请稍后重试。");
            return;
        }
        if(codeValue == 200 || codeValue == 0) {
            if(rootObj.contains("data")) {
                QJsonObject vDataObj = rootObj.value("data").toObject();
                if (vDataObj.empty()) {
                    emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
                    return;
                }

                // 解析单个页面表单信息
                int gridColumns = 1;
                if (vDataObj.contains("conf")) {
                    QJsonObject confObj = parseJsonString(vDataObj.value("conf").toString());
                    if (confObj.contains("formConfig")) {
                        QJsonObject formConfObj = confObj.value("formConfig").toObject();
                        if (formConfObj.contains("layoutColumns")) {
                            gridColumns = formConfObj.value("layoutColumns").toInt(1);
                        }
                    }
                }
                if (!vDataObj.contains("fields")) {
                    emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
                    return;
                }
                if (!vDataObj.value("fields").isArray()) {
//                    emit signalWorkNodeDetailReturnStat(-3, "解析表单页面失败");
                    return;
                }
                QJsonArray fieldsList = vDataObj.value("fields").toArray();

                int gridIndex = 0;
                for (auto iter = fieldsList.begin(); iter != fieldsList.end(); ++iter, gridIndex++) {
                    QJsonDocument fieldDoc = QJsonDocument::fromJson(QByteArray::fromStdString(iter->toString().toStdString().c_str()));
                    QJsonObject fieldRoot = fieldDoc.object();
                    // 当前控件
                    FormControl formControl;

                    if (!parseJsonToFormControl(fieldRoot, formControl)) {
                        continue;
                    }

                    formControl.m_gridCount = fieldsList.count();
                    formControl.m_gridColumns = gridColumns;
                    formControl.m_gridGroupName = "formData";
                    formControl.m_gridIndex = gridIndex;
                    WorkNodeFormModel::instance()->append(formControl);
                }
                // 解析表单名称（当前任务名称）
                if (vDataObj.contains("name") && vDataObj.value("name").isString()) {
                    WorkNodeFormModel::instance()->setFormName(vDataObj.value("name").toString());
                } else {
                    WorkNodeFormModel::instance()->setFormName("");
                }
                
                QJsonDocument formDoc(vDataObj);
                WorkNodeFormModel::instance()->setFormJsonInfo(formDoc.toJson(QJsonDocument::Compact));
                emit signalWorkNodeDetailReturnStat(0, "解析表单页完成");
            }
        }
    }
}
