#pragma once

#include "exportData.h"
#include "QtCore\qfile.h"
#include "QtCore\qtextstream.h"
#include <QUrl>
#include <QFile>
#include <QObject>
#include <QByteArray>
#include <QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>

class FtpManager
{
private:
    QUrl url;
    QNetworkAccessManager manager;

public:
    FtpManager() {
        /* 设置通讯协议 */
        url.setScheme("ftp");
        /* 设置用户名 */
        url.setUserName("FTP2");
        /* 设置密码 */
        url.setPassword("123");
        /* 设置主机，也可以是域名 */
        url.setHost("192.168.1.170");
        /* 设置端口号，一般为21 */
        url.setPort(666);
    }

    void uploadSingleFile(QString filePath, QString remotePath) {

        // 设置路径
        url.setPath(remotePath);
        qDebug() << "uploadSingleFile path " << url.path();

        // 装载本地文件
        QFile file(filePath);
        bool isopen = false;
        isopen = file.open(QIODevice::ReadOnly);
        qDebug() << "Open file " << isopen;
        if (isopen) {
            // 读取本地文件数据
            QByteArray data = file.readAll();
            file.close();

            // 上传数据，上传成功后会在远端创建文件
            manager.setNetworkAccessible(QNetworkAccessManager::Accessible);
            QNetworkReply* reply = manager.put(QNetworkRequest(url), data);

            QEventLoop eventLoop;
            //QObject::connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
            //// 进入等待，但事件循环依然进行 */
            //eventLoop.exec();

            //QObject::connect(reply, &QNetworkReply::finished, [&]() {
            //	if (reply->error() == QNetworkReply::NoError) {
            //		// 读取响应数据
            //		QByteArray responseData = reply->readAll();
            //		// 处理响应数据
            //		qDebug() << "Received response:" << responseData;
            //	}
            //	else {
            //		// 处理错误
            //		qDebug() << "Error occurred:" << reply->errorString();
            //	}

            //	// 清理资源
            //	reply->deleteLater();
            //	});
        }
    }
};
