#include "HttpGetJobTickets.h"

#include <QJsonObject>
#include <QJsonArray>

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

HttpGetJobTickets::HttpGetJobTickets(QObject *parent)
    : QThread(parent)
{
}

HttpGetJobTickets::~HttpGetJobTickets()
{
    // 注意：不要在析构函数中清空 JobTicketModel 数据
    // 因为可能有多个 HttpGetJobTickets 实例，一个实例销毁时不应影响共享的数据模型
    // cleanJobTicketsModel();
}

void HttpGetJobTickets::run()
{
    httpRequestGetJobTickets();
}

void HttpGetJobTickets::cleanJobTicketsModel()
{
    JobTicketModel::instance()->clear();
}

void HttpGetJobTickets::httpRequestGetJobTickets()
{
    QJsonObject jsonRoot;
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 timestampSeconds = currentDateTime.toMSecsSinceEpoch();

    QString url = Config()->jobTicketsUrl;

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

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

void HttpGetJobTickets::slotHttpResponseGetJobTickets(QByteArray data)
{
    QJsonParseError error;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &error);
    if (error.error != QJsonParseError::NoError) {
        emit signalJobTicketsReturnStat(-3, "无法查询到作业任务");
        return;
    }
    if (jsonDoc.isNull() || jsonDoc.isEmpty()) {
        emit signalJobTicketsReturnStat(-3, "无法查询到作业任务");
        return;
    }

    QJsonObject rootObj = jsonDoc.object();
    if(rootObj.contains("code"))
    {
        int codeValue = rootObj.value("code").toInt();
        if (codeValue == 408) {
            emit signalJobTicketsReturnStat(408, "处理超时，请稍后重试。");
            return;
        }
        if(codeValue == 200 || codeValue == 0) {
            if(rootObj.contains("data")) {
                QJsonObject vDataObj = rootObj.value("data").toObject();
                if (vDataObj.empty()) {
                    cleanJobTicketsModel();
                    return;
                }
                if (!vDataObj.contains("list")) {
                    cleanJobTicketsModel();
                    return;
                }
                if (!vDataObj.value("list").isArray()) {
                    return;
                }
                cleanJobTicketsModel();

                QJsonArray listData = vDataObj.value("list").toArray();
                for (auto iter = listData.begin(); iter != listData.end(); ++iter) {
                    if (!iter->isObject()) {
                        continue;
                    }
                    QJsonObject eleObj = iter->toObject();
                    // 解析单个作业票信息
                    JobTicket ticket;
                    if (eleObj.contains("workId")) {
                        ticket.m_workId = eleObj.value("workId").toInt() ;
                    }
                    if (eleObj.contains("nodeId")) {
                        ticket.m_nodeId = eleObj.value("nodeId").toInt() ;
                    }
                    if (eleObj.contains("orderNo") && eleObj.value("orderNo").isString()) {
                        ticket.m_orderNo = eleObj.value("orderNo").toString() ;
                    }
                    if (eleObj.contains("name") && eleObj.value("name").isString()) {
                        ticket.m_name = eleObj.value("name").toString() ;
                    }
                    if (eleObj.contains("urgencyLevel") && eleObj.value("urgencyLevel").isString()) {
                        ticket.m_urgencyLevel = eleObj.value("urgencyLevel").toString() ;
                    }
                    if (eleObj.contains("completionTime") && eleObj.value("completionTime").isString()) {
                        ticket.m_completionTime = eleObj.value("completionTime").toString() ;
                    }
                    if (eleObj.contains("cancellationReason") && eleObj.value("cancellationReason").isString()) {
                        ticket.m_cancellationReason = eleObj.value("cancellationReason").toString() ;
                    }
                    if (eleObj.contains("initiatorName") && eleObj.value("initiatorName").isString()) {
                        ticket.m_initiatorName = eleObj.value("initiatorName").toString() ;
                    }
                    if (eleObj.contains("workerUserName") && eleObj.value("workerUserName").isString()) {
                        ticket.m_workerUserName = eleObj.value("workerUserName").toString() ;
                    }
                    if (eleObj.contains("workTime")) {
                        qint64 workTimeStamp = eleObj.value("workTime").toDouble();
                        if (workTimeStamp > 0) {
                            QDateTime dateTime = QDateTime::fromMSecsSinceEpoch(workTimeStamp);
                            ticket.m_workTime = dateTime.toString("yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    if (eleObj.contains("currentNodeId") && eleObj.value("currentNodeId").isString()) {
                        ticket.m_currentNodeId = eleObj.value("currentNodeId").toString() ;
                    }
                    if (eleObj.contains("currentNodeName") && eleObj.value("currentNodeName").isString()) {
                        ticket.m_currentNodeName = eleObj.value("currentNodeName").toString() ;
                    }
                    if (eleObj.contains("approvalStatus") && eleObj.value("approvalStatus").isString()) {
                        QString status = eleObj.value("approvalStatus").toString() ;
                        if (status == "approved") {
                            ticket.m_approvalStatus = "已完成";
                            ticket.m_approvalStatusColor = "#0acb57";
                        }
                        else if (status == "running") {
                            ticket.m_approvalStatus = "进行中";
                            ticket.m_approvalStatusColor = "#1677ff";
                        }
                        else if (status == "pending") {
                            ticket.m_approvalStatus = "未开始";
                            ticket.m_approvalStatusColor = "#e5e5e5";
                        }
                        else if (status == "unaudited") {
                            ticket.m_approvalStatus = "未审核";
                            ticket.m_approvalStatusColor = "#e5e5e5";
                        }
                        else if (status == "rejected") {
                            ticket.m_approvalStatus = "驳回";
                            ticket.m_approvalStatusColor = "#e5e5e5";
                        }
                        else {
                            ticket.m_approvalStatus = status ;
                            ticket.m_approvalStatusColor = "#e5e5e5";
                        }
                    }

                    JobTicketModel::instance()->append(ticket);
                }
                emit signalJobTicketsReturnStat(0, "已查询到作业任务");
                return;
            }
        }
    }
    emit signalJobTicketsReturnStat(-3, "无法查询到作业任务");
    return;
}
