#include "ReturnKeyLockManager.h"
#include <QDebug>
#include <QDateTime>
#include <QRandomGenerator>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>

#include "../usr/config.h"
#include "../usr/BluetoothClient.h"
#include "InteractiveCAN.h"
#include "../httpclient/WorkNodeFormModel.h"

ReturnKeyLockManager* ReturnKeyLockManager::m_instance = nullptr;

ReturnKeyLockManager::ReturnKeyLockManager(QObject* parent)
    : QObject(parent)
    , m_isProcessing(false)
    , m_isVisible(false)
    , m_totalKeys(0)
    , m_successKeys(0)
    , m_failedKeys(0)
    , m_totalLocks(0)
    , m_successLocks(0)
    , m_failedLocks(0)
    , m_confirmCountdown(20)
{
    m_currentReadingStatus = "正在读取锁/钥匙状态......";

    m_workDetail = new HttpGetWorkNodeDetail(this);
    m_httpClient = new HttpClient(this);
    connect(m_workDetail, &HttpGetWorkNodeDetail::signalGetRequestData, m_httpClient, &HttpClient::slotGetRequestData);
    connect(m_httpClient, &HttpClient::signalResponseGetWorkNodeDetail, m_workDetail, &HttpGetWorkNodeDetail::slotHttpResponseGetWorkNodeDetail);
    
    // 处理队列定时器
    m_processTimer = new QTimer(this);
    m_processTimer->setInterval(500);  // 500ms处理一个
    connect(m_processTimer, &QTimer::timeout, this, &ReturnKeyLockManager::processNextInQueue);
    
    // 确认倒计时定时器
    m_confirmTimer = new QTimer(this);
    m_confirmTimer->setInterval(1000);
    connect(m_confirmTimer, &QTimer::timeout, this, &ReturnKeyLockManager::onConfirmCountdownTick);
}

ReturnKeyLockManager::~ReturnKeyLockManager()
{
    m_processTimer->stop();
    m_confirmTimer->stop();
}

ReturnKeyLockManager* ReturnKeyLockManager::instance()
{
    if (!m_instance) {
        m_instance = new ReturnKeyLockManager();
    }
    return m_instance;
}

ReturnKeyLockManager* ReturnKeyLockManager::create(QQmlEngine*, QJSEngine*)
{
    return instance();
}

void ReturnKeyLockManager::setIsVisible(bool visible)
{
    qDebug() << "[ReturnKeyLockManager] setIsVisible:" << visible << "当前:" << m_isVisible;
    if (m_isVisible != visible) {
        m_isVisible = visible;
        qDebug() << "[ReturnKeyLockManager] isVisible 已更新为:" << m_isVisible << ", 发出 isVisibleChanged 信号";
        emit isVisibleChanged();
        
        if (visible) {
            startConfirmCountdown();
        } else {
            stopConfirmCountdown();
        }
    }
}

void ReturnKeyLockManager::onNfcDetected(const QString& nfcId, const QString& deviceType, int slotIndex)
{
    QMutexLocker locker(&m_mutex);
    
    qDebug() << "[ReturnKeyLockManager] NFC检测到:" << nfcId << "类型:" << deviceType << "插槽:" << slotIndex;
    
    // 去重检查
    if (m_nfcIdSet.contains(nfcId)) {
        qDebug() << "[ReturnKeyLockManager] NFC已存在，跳过:" << nfcId;
        return;
    }
    
    // 添加到集合
    m_nfcIdSet.insert(nfcId);
    
    // 创建设备信息
    ReturnDeviceInfo info;
    info.nfcId = nfcId;
    info.deviceType = deviceType;
    info.slotIndex = slotIndex;
    info.status = "pending";
    info.statusMessage = "等待处理";
    info.returnTime = getCurrentTimeString();
    info.hasTask = false;
    info.isDeviceError = false;
    
    // 加入待处理队列
    m_pendingQueue.enqueue(info);
    m_deviceMap[nfcId] = info;
    
    // 更新统计
    if (deviceType == "key") {
        m_totalKeys++;
    } else {
        m_totalLocks++;
    }
    emit statisticsChanged();

    setIsVisible(true);
    
    // 显示页面（如果还没显示）
    if (!m_isVisible) {
        emit requestShowPage();
    }
    
    // 启动处理
    if (!m_processTimer->isActive()) {
        m_isProcessing = true;
        emit isProcessingChanged();
        m_processTimer->start();
    }
    
    emit dataUpdated();
}

void ReturnKeyLockManager::onDeviceError(const QString& deviceType, int slotIndex)
{
    QMutexLocker locker(&m_mutex);
    
    bool isFilter = false;
    // TODO: 添加一层过滤： 如果是上锁隔离或解除隔离节点
    if (WorkNodeFormModel::instance()->modelType() == "releaseIsolation" || WorkNodeFormModel::instance()->modelType() == "isolation") {
        if (InteractiveCAN::instance()->keyNfc() != "" && deviceType == "key") {
            qDebug() << "[onDeviceError] " << m_currTask.lockNfcs;
            isFilter = true;
        }
    }
    qDebug() << "[ReturnKeyLockManager] 设备异常:" << deviceType << "插槽:" << slotIndex;
    
    // 创建异常设备信息
    ReturnDeviceInfo info;
    if (isFilter) {
        info.nfcId = InteractiveCAN::instance()->keyNfc();
        info.deviceType = deviceType;
        info.slotIndex = slotIndex;
        info.status = "pending";
        info.statusMessage = "等待处理";
        info.returnTime = getCurrentTimeString();
        info.hasTask = false;
        info.isDeviceError = false;
    }
    else {
        info.nfcId = QString("ERROR_%1_%2").arg(deviceType).arg(slotIndex);
        info.deviceType = deviceType;
        info.slotIndex = slotIndex;
        info.status = "error";
        info.statusMessage = "设备读取异常";
        info.returnTime = getCurrentTimeString();
        info.hasTask = false;
        info.isDeviceError = true;
    }
    // 去重检查
    if (m_nfcIdSet.contains(info.nfcId)) {
        return;
    }
    m_nfcIdSet.insert(info.nfcId);

    if (isFilter) {
        // 加入待处理队列
        m_pendingQueue.enqueue(info);
        m_deviceMap[info.nfcId] = info;

        // 更新统计
        if (deviceType == "key") {
            m_totalKeys++;
        } else {
            m_totalLocks++;
        }
        emit statisticsChanged();

        // 启动处理
        if (!m_processTimer->isActive()) {
            m_isProcessing = true;
            emit isProcessingChanged();
            m_processTimer->start();
        }
    }
    else {
        // 添加到异常列表
        m_errorDevices.append(info);
        m_deviceMap[info.nfcId] = info;
    }

    setIsVisible(true);
    
    // 显示页面
    if (!m_isVisible) {
        emit requestShowPage();
    }
    
    emit dataUpdated();
}

void ReturnKeyLockManager::onApiResponse(const QString& nfcId, bool success, const QVariantMap& data)
{
    QMutexLocker locker(&m_mutex);
    
    if (!m_deviceMap.contains(nfcId)) {
        qWarning() << "[ReturnKeyLockManager] 未知NFC响应:" << nfcId;
        return;
    }
    
    ReturnDeviceInfo& info = m_deviceMap[nfcId];
    
    if (success) {
        info.status = data.value("returnStatus", "success").toString();
        info.statusMessage = data.value("statusMessage", "归还成功").toString();
        info.taskId = data.value("taskId", "").toString();
        info.taskName = data.value("taskName", "").toString();
        info.taskOrderNo = data.value("orderNo", "").toString();
        info.taskWorker = data.value("worker", "").toString();
        info.hasTask = !info.taskId.isEmpty();
        
        // 更新统计
        if (info.status == "success") {
            if (info.deviceType == "key") {
                m_successKeys++;
            } else {
                m_successLocks++;
            }
        } else {
            if (info.deviceType == "key") {
                m_failedKeys++;
            } else {
                m_failedLocks++;
            }
        }
    } else {
        info.status = "failed";
        info.statusMessage = data.value("errorMessage", "归还失败").toString();
        info.hasTask = false;
        
        if (info.deviceType == "key") {
            m_failedKeys++;
        } else {
            m_failedLocks++;
        }
    }

    if (WorkNodeFormModel::instance()->modelType() == "releaseIsolation" && m_taskGroups.contains(m_currTask.taskCode)) {
        m_taskGroups[m_currTask.taskCode].append(info);

        QList<QString> lockRfids;
        lockRfids << nfcId;

        InteractiveCAN::instance()->setTaskCode(m_currTask.taskCode.toInt());
//        InteractiveCAN::instance()->httpRequestPostUpdateBackLock(lockRfids);
    }
    else {
        // 分类到对应组
        if (!info.hasTask) {
            m_noTaskDevices.append(info);
        }
        else {
            if (!m_taskGroups.contains(info.taskId)) {
                m_taskGroups[info.taskId] = QList<ReturnDeviceInfo>();
            }
            m_taskGroups[info.taskId].append(info);
        }
    }
    
    emit statisticsChanged();
    emit dataUpdated();
}

void ReturnKeyLockManager::slotReceivedJobTicket(const BLERWorkTicketResult &result)
{
    qDebug() << "[slotReceivedJobTicket] " << result.resultDoc;
    if (result.resultDoc.isNull() || result.resultDoc.isEmpty()) return;
    QJsonObject root = result.resultDoc.object();

    if (!root.contains("data")) return;
    QJsonArray dataList = root.value("data").toArray();
    if (dataList.isEmpty()) return;

    // 目前只考虑一把钥匙的情况
    QJsonObject firstObj = dataList[0].toObject();
    if (!firstObj.contains("taskCode")) return;

    m_currTask.taskCode = firstObj.value("taskCode").toString();
    if (!root.contains("lockList")) return;
    QJsonArray lockList = root.value("lockList").toArray();

    for (int i = 0; i < lockList.count(); i++) {
        QJsonObject itemObj = lockList[i].toObject();
        if (itemObj.contains("rfid")) {
            m_currTask.lockNfcs.append(itemObj.value("rfid").toString());
        }
    }

    m_currentReadingStatus = QString("正在读取钥匙状态...");
    m_isProcessing = true;
    emit currentReadingStatusChanged();

    // 根据nodeId获取任务详情
    m_workDetail->setNodeId(m_currTask.taskCode);
    m_workDetail->start();

    InteractiveCAN::instance()->setTaskCode(m_currTask.taskCode.toInt());
    InteractiveCAN::instance()->httpRequestGetWorkTicketByNodeId();
}

void ReturnKeyLockManager::processNextInQueue()
{
    QMutexLocker locker(&m_mutex);
    
    if (m_pendingQueue.isEmpty()) {
        m_processTimer->stop();
        m_isProcessing = false;
        m_currentReadingStatus = "读取完成";
        emit isProcessingChanged();
        emit currentReadingStatusChanged();
        return;
    }
    
    ReturnDeviceInfo info = m_pendingQueue.dequeue();
    m_currentReadingStatus = QString("正在读取%1状态...").arg(info.deviceType == "key" ? "钥匙" : "锁仓");
    emit currentReadingStatusChanged();
    
//    // 临时：模拟API响应（实际使用时删除这段，改为真实API调用）
    QVariantMap mockData;
    mockData["returnStatus"] = "success";
    mockData["statusMessage"] = "";
//    mockData["taskId"] = QString("task_%1").arg(QRandomGenerator::global()->bounded(3));
//    mockData["taskName"] = QString("作业任务%1").arg(QRandomGenerator::global()->bounded(3) + 1);
//    mockData["orderNo"] = QString("WO-2024-%1").arg(QRandomGenerator::global()->bounded(100), 3, 10, QChar('0'));
    mockData["taskId"] = "";
    mockData["taskName"] = "";
    mockData["orderNo"] = "";
    mockData["worker"] = "";
    
    locker.unlock();
    if (info.deviceType == "key") {
        m_currTask.keyNfc = info.nfcId;
        InteractiveCAN::instance()->connectBLEDevice(info.nfcId);
    }
    else {
        QList<QString> lockRfids;
        lockRfids << info.nfcId;

        InteractiveCAN::instance()->httpRequestPostUpdateBackLock(lockRfids);
//        onApiResponse(info.nfcId, true, mockData);
    }
}

void ReturnKeyLockManager::confirmReturn()
{
    qDebug() << "[ReturnKeyLockManager] 确认归还";
    stopConfirmCountdown();
    closePage();
}

void ReturnKeyLockManager::retrieveFailedDevices()
{
    qDebug() << "[ReturnKeyLockManager] 取出归还失败的设备";
    InteractiveCAN::instance()->updateKeyAndLockStatus(true);
    
    for (auto iter = m_errorDevices.begin(); iter != m_errorDevices.end(); ++iter) {
        qDebug() << iter->nfcId;
        InteractiveCAN::instance()->unlockDevices(iter->nfcId, iter->deviceType);
    }
    
    // 重置倒计时
    m_confirmCountdown = 20;
    emit confirmCountdownChanged();
}

void ReturnKeyLockManager::closePage()
{
    QMutexLocker locker(&m_mutex);
    
    // 清空所有数据
    m_nfcIdSet.clear();
    m_pendingQueue.clear();
    m_deviceMap.clear();
    m_taskGroups.clear();
    m_errorDevices.clear();
    m_noTaskDevices.clear();
    
    m_totalKeys = 0;
    m_successKeys = 0;
    m_failedKeys = 0;
    m_totalLocks = 0;
    m_successLocks = 0;
    m_failedLocks = 0;
    
    m_isProcessing = false;
    m_currentReadingStatus = "正在读取锁/钥匙状态......";
    InteractiveCAN::instance()->updateKeyAndLockStatus(false);
    
    emit statisticsChanged();
    emit isProcessingChanged();
    emit currentReadingStatusChanged();
    
    setIsVisible(false);
}

QVariantList ReturnKeyLockManager::getTaskGroups()
{
//    QMutexLocker locker(&m_mutex);
    QVariantList result;
    qDebug() << "[getTaskGroups] " << m_taskGroups.keys();
    
    for (auto it = m_taskGroups.begin(); it != m_taskGroups.end(); ++it) {
        QVariantMap group;
        group["taskId"] = it.key();
        
        if (!it.value().isEmpty()) {
            const ReturnDeviceInfo& first = it.value().first();
            group["taskName"] = first.taskName;
            group["orderNo"] = first.taskOrderNo;
            group["worker"] = first.taskWorker;
        }
        
        // 计算该任务的成功/失败数
        int success = 0, failed = 0;
        QVariantList devices;
        for (const ReturnDeviceInfo& info : it.value()) {
            QVariantMap device;
            device["nfcId"] = info.nfcId;
            device["deviceType"] = info.deviceType;
            device["slotIndex"] = info.slotIndex;
            device["status"] = info.status;
            device["statusMessage"] = info.statusMessage;
            device["returnTime"] = info.returnTime;
            devices.append(device);
            
            if (info.status == "success") success++;
            else failed++;
        }
        group["devices"] = devices;
        group["hasFailure"] = (failed > 0);
        group["statusText"] = (failed > 0) ? "有失败" : "已完成";
        
        result.append(group);
    }
    
    return result;
}

QVariantList ReturnKeyLockManager::getErrorDevices()
{
//    QMutexLocker locker(&m_mutex);
    QVariantList result;
    
    for (const ReturnDeviceInfo& info : m_errorDevices) {
        QVariantMap device;
        device["nfcId"] = info.nfcId;
        device["deviceType"] = info.deviceType;
        device["slotIndex"] = info.slotIndex;
        device["status"] = info.status;
        device["statusMessage"] = info.statusMessage;
        device["returnTime"] = info.returnTime;
        result.append(device);
    }
    
    return result;
}

QVariantList ReturnKeyLockManager::getNoTaskDevices()
{
//    QMutexLocker locker(&m_mutex);
    QVariantList result;
    
    for (const ReturnDeviceInfo& info : m_noTaskDevices) {
        QVariantMap device;
        device["nfcId"] = info.nfcId;
        device["deviceType"] = info.deviceType;
        device["slotIndex"] = info.slotIndex;
        device["status"] = info.status;
        device["statusMessage"] = info.statusMessage;
        device["returnTime"] = info.returnTime;
        result.append(device);
    }
    
    return result;
}

void ReturnKeyLockManager::testTrigger(const QString& deviceType, int slotIndex)
{
    // 生成测试NFC卡号
    QString testNfcId = QString("TEST%1%2%3")
        .arg(deviceType.toUpper())
        .arg(slotIndex)
        .arg(QRandomGenerator::global()->bounded(10000), 4, 10, QChar('0'));
    
    qInfo() << "[ReturnKeyLockManager] 测试触发:" << deviceType << "插槽:" << slotIndex << "NFC:" << testNfcId;
    
    // 调用正常的NFC检测流程
    onNfcDetected(testNfcId, deviceType, slotIndex);
}

void ReturnKeyLockManager::slotGetJobTicketResult(int stat, const QJsonObject& dataObj)
{
    qDebug() << "[slotGetJobTicketResult] " << stat << dataObj;
    if (!dataObj.contains("ticketStatus")) return;

    int ticketStatus = dataObj.value("ticketStatus").toInt();

    QMutexLocker locker(&m_mutex);

    QString nfcId = m_currTask.keyNfc;

    ReturnDeviceInfo& info = m_deviceMap[nfcId];

    if (stat != 0){
        info.status = "failed";
        info.statusMessage = "获取信息失败";
        info.hasTask = false;

        if (info.deviceType == "key") {
            m_failedKeys++;
        }
        else {
            m_failedLocks++;
        }

        m_errorDevices.append(info);

        emit statisticsChanged();
        emit dataUpdated();
        return;
    }
    else {
        // 0未开始 1待上锁 2进行中 3待解锁 4已解锁 5已结束 6已取消)
        if (ticketStatus == 0 || ticketStatus == 5 || ticketStatus == 6) {
            info.status = "success";
            info.statusMessage = "归还成功";
        }
        else {
            info.status = "failed";
            info.statusMessage = "作业任务未完成";
        }

        info.taskId = WorkNodeFormModel::instance()->workId();
        info.taskName = WorkNodeFormModel::instance()->nodeName();
        info.taskOrderNo = WorkNodeFormModel::instance()->orderNo();
        info.taskWorker = WorkNodeFormModel::instance()->workerName();
        info.hasTask = !info.taskId.isEmpty();

        // 更新统计
        if (info.status == "success") {
            if (info.deviceType == "key") {
                m_successKeys++;
            }
            else {
                m_successLocks++;
            }
        }
        else {
            if (info.deviceType == "key") {
                m_failedKeys++;

            }
            else {
                m_failedLocks++;
            }
        }

        InteractiveCAN::instance()->setTaskCode(WorkNodeFormModel::instance()->workId());

        bool hasTicketInfo = true;
        int target = 0;

        QJsonArray lockInfoList;
        if (dataObj.contains("ticketContent")) {
            QJsonDocument ticketDoc = QJsonDocument::fromJson(QByteArray::fromStdString(dataObj.value("ticketContent").toString().toStdString().c_str()));
            if (ticketDoc.isNull() || ticketDoc.isEmpty()) {
                hasTicketInfo = false;
            }
            else {
                QJsonObject ticketObj = ticketDoc.object();
                if (ticketObj.contains("data")) {
                    QJsonArray dataObj = ticketObj.value("data").toArray();
                    for (auto iter = dataObj.begin(); iter != dataObj.end(); ++iter) {
                        QJsonObject itemObj = iter->toObject();
                        if (!itemObj.contains("taskCode") || !itemObj.contains("dataList")) continue;

                        QString taskCode = itemObj.value("taskCode").toString();

                        QJsonArray dataList = itemObj.value("dataList").toArray();
                        for (auto pointIter = dataList.begin(); pointIter != dataList.end(); ++pointIter) {
                            QJsonObject lockItem;
                            QJsonObject pointItem = pointIter->toObject();

                            lockItem.insert("nodeId", taskCode.toInt());
                            lockItem.insert("pointNfc", pointItem.value("equipRfidNo").toString());
                            lockInfoList.append(lockItem);

                            if (WorkNodeFormModel::instance()->modelType() == "releaseIsolation") {
                                target = 1;
                            }
                            else {
                                target = pointItem.value("target").toInt();
                            }
                        }
                    }
                    QJsonArray lockList = ticketObj.value("lockList").toArray();
                    if (lockList.count() == lockInfoList.count()) {
                         m_currTask.lockNfcs.clear();
                        for (int i = 0; i < lockList.count(); i++) {
                            m_currTask.lockNfcs.append(lockList[i].toObject().value("rfid").toString());
                            QJsonObject lockItem = lockInfoList[i].toObject();
                            lockItem.insert("lockNfc", lockList[i].toObject().value("rfid").toString());
                            lockInfoList.replace(i, lockItem);
                        }
                    }
                }
            }
        }
        if (hasTicketInfo) {
            InteractiveCAN::instance()->httpRequestPostUpdateKeyBack(info.nfcId, target, lockInfoList);
        }

        if (!m_currTask.keyNfc.isEmpty()) {
            InteractiveCAN::instance()->setKeyNfc(m_currTask.keyNfc);
        }
    }

    // 分类到对应组
    if (!info.hasTask) {
        m_noTaskDevices.append(info);
    }
    else {
        if (!m_taskGroups.contains(info.taskId)) {
            m_taskGroups[info.taskId] = QList<ReturnDeviceInfo>();
        }
        m_taskGroups[info.taskId].append(info);
        for (int i = 0; i < m_currTask.lockNfcs.count(); i++) {
            QString lockNfc = m_currTask.lockNfcs[i];
            qDebug() << "[slotGetJobTicketResult] lockNfc: " << lockNfc;
            if (!m_deviceMap.contains(nfcId)) continue;
            for (auto iter = m_noTaskDevices.begin(); iter != m_noTaskDevices.end(); ++iter) {
                if ((*iter).nfcId == lockNfc) {
                    iter = m_noTaskDevices.erase(iter);
                    break;
                }
            }
        }
    }

    if (WorkNodeFormModel::instance()->modelType() == "releaseIsolation") {
        QList<ReturnDeviceInfo> releaseIsolationInfoList = m_taskGroups[m_currTask.taskCode];
        m_taskGroups.clear();
        m_taskGroups[m_currTask.taskCode] = releaseIsolationInfoList;

        setIsVisible(true);
    }

    emit statisticsChanged();
    emit dataUpdated();
}

void ReturnKeyLockManager::startConfirmCountdown()
{
    m_confirmCountdown = 20;
    emit confirmCountdownChanged();
    m_confirmTimer->start();
}

void ReturnKeyLockManager::stopConfirmCountdown()
{
    m_confirmTimer->stop();
}

void ReturnKeyLockManager::onConfirmCountdownTick()
{
    m_confirmCountdown--;
    emit confirmCountdownChanged();
    
    if (m_confirmCountdown <= 0) {
        confirmReturn();
    }
}

void ReturnKeyLockManager::updateStatistics()
{
    emit statisticsChanged();
}

QString ReturnKeyLockManager::getCurrentTimeString()
{
    return QDateTime::currentDateTime().toString("hh:mm:ss");
}

