#include "InteractiveCore.h"
#include "InteractiveWork.h"

InteractiveCore::InteractiveCore(QObject *parent)
    : QObject(parent)
{
    m_timerDataChcheRefresh = startTimer(TIMER_DATA_CHCHE_REFRESH);

    connect(SINGLETON_CREATE(InteractiveWork)(), &InteractiveWork::signal_completed,
            this, &InteractiveCore::slot_completed);
    connect(SINGLETON_CREATE(InteractiveWork)(), &InteractiveWork::signal_failstart,
            this, &InteractiveCore::slot_failstart);

    SINGLETON_CREATE(InteractiveWork)()->start();
}

void InteractiveCore::appendTask(InteractiveTask::TaskType type, QVariant request, QJSValue callback)
{
    InteractiveTask* task = new InteractiveTask();
    task->type = type;
    task->request = request;
    task->callback = callback;
    SINGLETON_CREATE(InteractiveWork)()->appendTask(task);
}

void InteractiveCore::slot_completed(InteractiveTask *task)
{
    if (qobject_cast<InteractiveTask*>(task))
    {
        if (task->callback.isCallable())
        {
            QJSValueList args;
            // 如果是string类型
            if (task->respond.typeId() == QMetaType::QString)
            {
                args << task->respond.toString();
            }
            // 如果是bytearray类型
            else if(task->respond.typeId() == QMetaType::QByteArray)
            {
                args << QString(task->respond.toByteArray());
            }
            // 如果是int类型
            else if (task->respond.typeId() == QMetaType::Int)
            {
                args << task->respond.toInt();
            }
            // 如果是其他类型
            else
            {
                // ...
            }

            task->callback.call(args);
        }
    }

    delete task;
}

void InteractiveCore::slot_failstart(InteractiveTask *task)
{
    delete task;
}

void InteractiveCore::timerEvent(QTimerEvent *event)
{
    // 定时刷新服务缓存
    if (event->timerId() == m_timerDataChcheRefresh)
    {
        // 获取异常类型字典值
        appendTask(InteractiveTask::TypeHttpGet_exception_type, QVariant(), QJSValue());
        // 获取严重等级字典值
        appendTask(InteractiveTask::TypeHttpGet_severity_level, QVariant(), QJSValue());

        // 获取物资柜id
        appendTask(InteractiveTask::TypeHttpGet_selectIsMaterialsCabinetByCode, QVariant(), QJSValue());

        // 查询物资信息All
        appendTask(InteractiveTask::TypeHttpGet_getIsMaterialsPage, QVariant(), QJSValue());
    }

}


// void InteractiveCore::slot_tid_update_Ex(quint16 count, QList<QString> tidList, const QVariant &user)
// {
//     QString strType = user.toString();
//     if (strType == "物资取还" || strType == "物资检查" || strType == "手动更换" || strType == "异常处理")
//     {

//     }
//     else if (strType == "自动更换")
//     {

//     }
// }
