#ifndef EXPORTTHREAD_H
#define EXPORTTHREAD_H

#include <QThread>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QTextCodec>
#include "databaseutils.h"
#include "QXlsx/header/xlsxdocument.h"
#include "QXlsx/header/xlsxformat.h"
#include "QXlsx/header/xlsxcellrange.h"

class ExportThread : public QThread
{
    Q_OBJECT

public:
    ExportThread(const QString &fileName, int allCount, int autoCount, int manualCount, int qualifiedCount, int upCount, int downCount, QObject *parent = nullptr)
        : QThread(parent), fileName(fileName), all_count(allCount), auto_cnt(autoCount), manual_cnt(manualCount), qualified_cnt(qualifiedCount), up_cnt(upCount), down_cnt(downCount) {}

protected:
    void run() override
    {

        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

        qDebug() << "Export thread started.";

        int totalRows = DatabaseUtils::getResTotalRows();
        qDebug() << "Total rows in database:" << totalRows;

        if (totalRows == 0)
        {
            emit exportFailed("The table is empty. There is no data to export.");
            return;
        }

        QVector<QVariantList> allData = DatabaseUtils::getAllData();
        qDebug() << "Data retrieved from database. Number of rows:" << allData.size();

        if (allData.isEmpty())
        {
            emit exportFailed("No data retrieved from database.");
            return;
        }

        QXlsx::Document xlsx;

        QXlsx::Format titleFormat;
        titleFormat.setFontBold(true);
        titleFormat.setFontSize(14);
        titleFormat.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
        titleFormat.setVerticalAlignment(QXlsx::Format::AlignVCenter);

        qDebug() << "Setting title.";
        xlsx.write("A1", QString::fromUtf8("电阻检测软件导出表"), titleFormat);
        xlsx.mergeCells(QXlsx::CellRange("A1:J1"), titleFormat);

        QXlsx::Format timeFormat;
        timeFormat.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
        timeFormat.setVerticalAlignment(QXlsx::Format::AlignVCenter);

        qDebug() << "Setting export time.";
        xlsx.write("A2", QString("导出时间: %1").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")), timeFormat);
        xlsx.mergeCells(QXlsx::CellRange("A2:J2"), timeFormat);

        QXlsx::Format infoFormat;
        infoFormat.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
        infoFormat.setVerticalAlignment(QXlsx::Format::AlignVCenter);

        QString exportInfo = QString("总检测数: %1, 合格: %2, 超过量程: %3, 小于量程: %4, 合格率: %5")
                                 .arg(all_count)
                                 .arg(qualified_cnt)
                                 .arg(up_cnt)
                                 .arg(down_cnt)
                                 .arg(double(qualified_cnt) / all_count * 100, 0, 'f', 2);

        qDebug() << "Setting export info.";
        xlsx.write("A3", exportInfo, infoFormat);
        xlsx.mergeCells(QXlsx::CellRange("A3:J3"), infoFormat);

        QStringList headers = {QString::fromUtf8("序号"), QString::fromUtf8("车型"), QString::fromUtf8("护面扫码编号"), QString::fromUtf8("加热垫扫码编号"), QString::fromUtf8("实测阻值"), QString::fromUtf8("标准阻值范围"), QString::fromUtf8("检测结果"), QString::fromUtf8("手动/自动"), QString::fromUtf8("检测员"), QString::fromUtf8("检测时间")};
        QXlsx::Format headerFormat;
        headerFormat.setFontBold(true);
        headerFormat.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
        headerFormat.setVerticalAlignment(QXlsx::Format::AlignVCenter);

        qDebug() << "Setting column headers.";
        for (int col = 0; col < headers.size(); ++col)
        {
            xlsx.write(4, col + 1, headers[col], headerFormat);
        }

        QXlsx::Format dataFormat;
        dataFormat.setHorizontalAlignment(QXlsx::Format::AlignHCenter);
        dataFormat.setVerticalAlignment(QXlsx::Format::AlignVCenter);

        qDebug() << "Filling data.";
        for (int row = 0; row < allData.size(); ++row)
        {
            const QVariantList &rowData = allData[row];
            for (int col = 0; col < rowData.size(); ++col)
            {
                xlsx.write(row + 5, col + 1, rowData[col], dataFormat);
            }
        }

        qDebug() << "Saving file to" << fileName;
        if (xlsx.saveAs(fileName))
        {
            qDebug() << "File saved successfully.";
            emit exportSucceeded();
        }
        else
        {
            qDebug() << "Failed to save the file.";
            emit exportFailed("Failed to save the file.");
        }
    }

signals:
    void exportSucceeded();
    void exportFailed(const QString &error);

private:
    QString fileName;
    int all_count;
    int auto_cnt;
    int manual_cnt;
    int qualified_cnt;
    int up_cnt;
    int down_cnt;
};

#endif // EXPORTTHREAD_H
