#ifndef ASYNCHELPER_H
#define ASYNCHELPER_H

#include <QFuture>
#include <QFutureWatcher>
#include <QObject>
#include <functional>

#include "../network/networkaccessmanager.h"
#include "../widgets/maskoverlay.h"

// 前向声明安全执行回调的辅助函数
void safeExecuteCallback(const std::function<void()>& callback, const QString& callbackType);

class AsyncHelper : public QObject
{
    Q_OBJECT

public:
    static AsyncHelper* instance();

    // 通用的异步请求处理模板
    template<typename T>
    class Request
    {
    public:
        Request(const QFuture<T>& future)
            : m_future(future)
            , m_successCallback(nullptr)
            , m_errorCallback(nullptr)
            , m_finallyCallback(nullptr)
            , m_maskParent(nullptr)
        {}

        // 设置成功回调
        Request& onSuccess(std::function<void(const T&)> callback)
        {
            m_successCallback = callback;
            return *this;
        }

        // 设置错误回调
        Request& onError(std::function<void(const QString&)> callback)
        {
            m_errorCallback = callback;
            return *this;
        }

        // 设置最终回调
        Request& onFinally(std::function<void()> callback)
        {
            m_finallyCallback = callback;
            return *this;
        }

        // 设置遮罩层
        Request& withMask(QWidget* parent)
        {
            if (parent) {
                MaskOverlay::instance()->show(parent, 0, MaskOverlay::ActiveWindow);
                m_maskParent = parent;
            }
            return *this;
        }

        // 执行请求
        void exec()
        {
            auto* watcher = new QFutureWatcher<T>();

            // 复制回调函数，确保在 lambda 中使用的是副本
            auto successCallback = m_successCallback;
            auto errorCallback = m_errorCallback;
            auto finallyCallback = m_finallyCallback;
            auto maskParent = m_maskParent;

            // 处理完成信号
            QObject::connect(watcher,
                             &QFutureWatcher<T>::finished,
                             [watcher, successCallback, errorCallback, finallyCallback, maskParent]() {
                                 if (maskParent) {
                                     MaskOverlay::instance()->hide();
                                 }

                                 T result = watcher->result();
                                 if (successCallback) {
                                     successCallback(result);
                                 }

                                 // 安全执行finally回调
                                 if (finallyCallback) {
                                     safeExecuteCallback(finallyCallback, "finally");
                                 }

                                 watcher->deleteLater();
                             });

            // 处理取消信号 - 同样修改捕获方式
            QObject::connect(watcher,
                             &QFutureWatcher<T>::canceled,
                             [watcher, errorCallback, finallyCallback, maskParent]() {
                                 // 隐藏遮罩层
                                 if (maskParent) {
                                     MaskOverlay::instance()->hide();
                                 }

                                 if (errorCallback) {
                                     errorCallback(QObject::tr("请求被取消"));
                                 }
                                 // 安全执行finally回调
                                 if (finallyCallback) {
                                     safeExecuteCallback(finallyCallback, "finally");
                                 }

                                 watcher->deleteLater();
                             });

            // 设置 Future
            watcher->setFuture(m_future);
        }

    private:
        const QFuture<T>& m_future;
        std::function<void(const T&)> m_successCallback;
        std::function<void(const QString&)> m_errorCallback;
        std::function<void()> m_finallyCallback;
        QWidget* m_maskParent = nullptr;
    };

    // 创建通用请求
    template<typename T>
    static Request<T> request(const QFuture<T>& future)
    {
        return Request<T>(future);
    }

    // 创建 HTTP 请求
    static Request<HttpResponse> http(const QFuture<HttpResponse>& future)
    {
        return Request<HttpResponse>(future);
    }

private:
    explicit AsyncHelper(QObject* parent = nullptr);

    static AsyncHelper* m_instance;
};

#endif // ASYNCHELPER_H
