#include "frmupload.h"
#include "ui_frmupload.h"
#include <QtDebug>
#include <QImageReader>
#include <QStandardPaths>

FrmUpload::FrmUpload(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::FrmUpload)
{
    ui->setupUi(this);
    initFrom();
    initWidget();
    connect(TCHttpService::getInstance(), &TCHttpService::signal_uploadFileSec, this, &FrmUpload::slot_uploadFileSec);

    QButtonGroup *buttonGroup = new QButtonGroup(this);
    buttonGroup->setExclusive(true); // 确保每次只有一个按钮被选中

    // 添加按钮到组中
    buttonGroup->addButton(ui->btnHTML);
    buttonGroup->addButton(ui->btnMarkdown);
    buttonGroup->addButton(ui->btnUBB);
    buttonGroup->addButton(ui->btnUrl);

    // 设置样式表
    QString buttonStyle = R"(
    QPushButton {
        color: black;
    }
    QPushButton:checked {
        color: #409EFF
    }
)";
    ui->btnHTML->setStyleSheet(buttonStyle);
    ui->btnMarkdown->setStyleSheet(buttonStyle);
    ui->btnUBB->setStyleSheet(buttonStyle);
    ui->btnUrl->setStyleSheet(buttonStyle);
}

FrmUpload::~FrmUpload()
{
    delete ui;
}

void FrmUpload::slot_uploadFileSec(QString url)
{
    qDebug() << "slot_uploadFileSec:" << url;
    QClipboard* clipboard = QApplication::clipboard();


    if (copyType == COPY_TYPE_MARKDOWN) {
        clipboard->setText(QString("![](%1)").arg(url));
    }
    if (copyType == COPY_TYPE_URL) {
        clipboard->setText(url);
    }
    if (copyType == COPY_TYPE_UBB) {
        // [IMG]https://imagehyj.oss-cn-hangzhou.aliyuncs.com/blog/logo512.png[/IMG]
        clipboard->setText(QString("[IMG]%1[/IMG]").arg(url));
    }
    if (copyType == COPY_TYPE_HTML) {
        clipboard->setText(QString("<img src=\"%1\"/>").arg(url));

        // QThread::sleep(50);
    }

}

bool FrmUpload::eventFilter(QObject *watched, QEvent *event)
{
    static bool mousePressed = false;
    if (watched == ui->frmUpload) {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->type() == QMouseEvent::MouseButtonPress && mouseEvent->button() == Qt::LeftButton) {
            mousePressed = true;
            return  true;
        }
        else if (mouseEvent->type() == QMouseEvent::MouseButtonRelease && mouseEvent->button() == Qt::LeftButton && mousePressed == true) {
            QStringList fileList = QFileDialog::getOpenFileNames(this, "选择图片", "C:\\", "Files (*);;"
                                                                                       "PNG (*.png);;"
                                                                                       "JPG (*.jpg);;"
                                                                                       "JPEG (*.jpeg);;"
                                                                                       "SVG (*.svg)");
            uploadFiles(fileList);
            mousePressed = false;
            return true;
        }
        else {
            return false;
        }
    }

    return QWidget::eventFilter(watched, event);
}

void FrmUpload::dragEnterEvent(QDragEnterEvent *event)
{
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
    else {
        event->ignore();
    }
}

void FrmUpload::dropEvent(QDropEvent *event)
{
    QStringList uploadList;
    const QMimeData* mimeData = event->mimeData();
    if (!mimeData->hasUrls()) {
        return;
    }
    QList<QUrl> urlList = mimeData->urls();


#if !DEBUG
    foreach (QUrl url, urlList) {
        qDebug() << url.toLocalFile();
    }
#endif

    foreach (QUrl url, urlList) {
        QFileInfo fileInfo(url.toLocalFile());
        if (fileInfo.isDir()) {
            continue;
        }
        else {
//            QImageReader reader(url.toLocalFile());
//            if (!reader.imageFormat()) {
//                uploadList << url.toLocalFile();
//            TCHttpService::getInstance()->apiMd5(fileInfo.absoluteFilePath());
            }
        }

}

void FrmUpload::initFrom()
{
    ui->frmUpload->setMinimumSize(QSize(400, 200));
    ui->btnHTML->setText("HTML");
    ui->btnFastUpload->setText("剪贴板上传");
    ui->btnMarkdown->setText("Markdown");
    ui->btnUrl->setText("URL");
    ui->btnUBB->setText("UBB");

    ui->btnMarkdown->setChecked(true);
    ui->btnHTML->setChecked(false);
    ui->btnUBB->setChecked(false);
    ui->btnUrl->setChecked(false);
}

void FrmUpload::initWidget()
{
    ui->frmUpload->installEventFilter(this);
    this->setAcceptDrops(true);
    setWindowFlags(Qt::FramelessWindowHint); // 移除系统边框
    setAttribute(Qt::WA_TranslucentBackground); // 启用透明背景
//    ui->frmUpload->setAcceptDrops(true);
}

void FrmUpload::uploadFiles(QStringList fileList)
{
    if (!TCHttpService::getInstance()->getOnlineState())
        return;
    foreach (QString p, fileList) {
        qDebug() << "upload:" << p;
        TCHttpService::getInstance()->apiUpload(p);
    }
    // TCHttpService::getInstance()->apiMyfileCount();
    // TCHttpService::getInstance()->apiMyfileNormal();

}

void FrmUpload::on_btnFastUpload_clicked()
{
    // QString addDataPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
    // QString cacheDirPath = addDataPath + "/cache/";
    QDir cacheDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
    if (!cacheDir.exists()) {
        cacheDir.mkpath(".");
    }
    QClipboard* clipboard = QApplication::clipboard();
    const QMimeData* mimeData = clipboard->mimeData();

    if (mimeData->hasImage()) {
        QImage image = clipboard->image();
        if (!image.isNull()) {
            RenameType renametype = FileConfigDecode::getInstance()->getRenameType();
            qDebug() << "renameType:" << renametype;
            if (renametype == RENAME_TYPE_NORMAL) {
                bool ok;
                QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz");
                QString text = QInputDialog::getText(this, "重命名图片", "输入文件名", QLineEdit::Normal, timestamp, &ok);
                if (ok && !text.isEmpty()) {
                    QString filePath = cacheDir.filePath(text + ".png");

                    if (image.save(filePath, "PNG")) {
                        TCHttpService::getInstance()->apiUpload(filePath);
                    }
                }
            }

            if (renametype == RENAME_TYPE_TIME) {
                qDebug() << "time rename";
                QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz");
                QString filePath = cacheDir.filePath(timestamp + ".png");

                if (image.save(filePath, "PNG")) {
                    TCHttpService::getInstance()->apiUpload(filePath);
                }
            }
            else {
                QString timestamp = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmsszzz");
                QString filePath = cacheDir.filePath("clipboard_" + timestamp + ".png");

                if (image.save(filePath, "PNG")) {
                    TCHttpService::getInstance()->apiUpload(filePath);
                }
            }

        }
        clipboard->clear();
    }
}


void FrmUpload::on_btnMarkdown_clicked()
{
    if (!ui->btnMarkdown->isChecked())
        return;
    copyType = COPY_TYPE_MARKDOWN;
    ui->btnMarkdown->setChecked(true);
    ui->btnUrl->setChecked(false);
    ui->btnHTML->setChecked(false);
    ui->btnUBB->setChecked(false);
    qDebug() << copyType;
}


void FrmUpload::on_btnUrl_clicked()
{
    if (!ui->btnUrl->isChecked())
        return;
    copyType = COPY_TYPE_URL;
    ui->btnMarkdown->setChecked(false);
    ui->btnUrl->setChecked(true);
    ui->btnHTML->setChecked(false);
    ui->btnUBB->setChecked(false);
    qDebug() << copyType;
}


void FrmUpload::on_btnHTML_clicked()
{
    if (!ui->btnHTML->isChecked())
        return;
    copyType = COPY_TYPE_HTML;
    ui->btnMarkdown->setChecked(false);
    ui->btnUrl->setChecked(false);
    ui->btnHTML->setChecked(true);
    ui->btnUBB->setChecked(false);
    qDebug() << copyType;
}


void FrmUpload::on_btnUBB_clicked()
{
    if (!ui->btnUBB->isChecked())
        return;
    copyType = COPY_TYPE_UBB;
    ui->btnMarkdown->setChecked(false);
    ui->btnUrl->setChecked(false);
    ui->btnHTML->setChecked(false);
    ui->btnUBB->setChecked(true);
    qDebug() << copyType;
}

