#ifndef DATALOADER_H
#define DATALOADER_H

#include <QObject>
#include <QRunnable>
#include <QThreadPool>
#include <QHash>
#include <QMutex>
#include <QVariant>

class DataLoader : public QObject
{
    Q_OBJECT

public:
    explicit DataLoader(QObject* parent = nullptr);
    ~DataLoader();

    void requestData(const QString& dataKey);
    void cancelRequest(const QString& dataKey);
    void setMaxThreads(int count);

signals:
    void dataLoaded(const QString& dataKey, const QVariant& data);
    void errorOccurred(const QString& dataKey, const QString& error);

public slots:
    void handleShutdown();

private:
    class LoadTask : public QRunnable
    {
    public:
        LoadTask(DataLoader* loader, const QString& key)
            :m_loader(loader), m_key(key)
        {
            setAutoDelete(false);//禁用自动析构，由DataLoader控制管理
        }

        void run() override
        {
            QVariant data = fetchRealData(m_key);
            emit m_loader->dataLoaded(m_key, data);
        }

    private:
        QVariant fetchRealData(const QString& dataKey);

        DataLoader* m_loader;
        QString m_key;
    };

    QThreadPool m_threadPool;
    QHash<QString, LoadTask*> m_runningTasks;
    QMutex m_taskMutex;
};

#endif
