#include <QHBoxLayout>
#include <qmap.h>

#include "printpreviewform.h"
#include "ui_printpreviewform.h"
#include "global.h"
#include "logger.h"

PrintPreviewForm::PrintPreviewForm(QWidget *parent) : QWidget(parent),
                                                      ui(new Ui::PrintPreviewForm),
                                                      _printer(new QPrinter(QPrinter::HighResolution)) {
    ui->setupUi(this);

    _printer->setPageSize(QPageSize(QPageSize::A4));
    _printer->setOrientation(QPrinter::Landscape);
    // _printer->setOutputFormat(QPrinter::NativeFormat);    // 关键

    _customPrintPreviewDialog = new QPrintPreviewDialog(_printer, this);
    _customPrintPreviewDialog->setWindowFlags(_customPrintPreviewDialog->windowFlags()
                                              | Qt::WindowMaximizeButtonHint
                                              | Qt::WindowMinimizeButtonHint);

    // _painter = new QPainter(_printer);

    QObject::connect(_customPrintPreviewDialog,
                     &QPrintPreviewDialog::paintRequested,
                     this,
                     &PrintPreviewForm::slotPaintRequested);
}

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

void PrintPreviewForm::setPixmap(const QPixmap &pixmap) {
    logde << "setPixmap...";

    _pixmap = pixmap;

    if (!_customPrintPreviewDialog)
        return;
    if (auto pv = _customPrintPreviewDialog->findChild<QPrintPreviewWidget *>()) {
        pv->updatePreview();    // 触发 paintRequested
    } else {
        _customPrintPreviewDialog->update();    // 退化处理
    }

    // repaint();
#if 0
    if (_customPrintPreviewDialog) {
        _customPrintPreviewDialog->repaint();    // 强制刷新
        _customPrintPreviewDialog->update();     // 刷新预览窗口

        _printer->setOrientation(
            _printer->orientation() == QPrinter::Landscape
                ? QPrinter::Portrait
                : QPrinter::Landscape);

        _printer->setOrientation(QPrinter::Landscape);


        _customPrintPreviewDialog->repaint();    // 强制刷新
        _customPrintPreviewDialog->update();     // 刷新预览窗口
        // _customPrintPreviewDialog->updatePreview();    // 刷新预览
    }
#endif

    // slotPaintRequested(_printer);
}

void PrintPreviewForm::slotPaintRequested(QPrinter *printer) {
    logde << "slotPaintRequested...";

    const int ConTextHeight = 100;

    printer->setOrientation(QPrinter::Landscape);
    QPainter painter(printer);

#if 0
    // 重置 painter 状态（清除之前的设置）
    painter.resetTransform();
    painter.setPen(Qt::black);
    painter.setBrush(Qt::NoBrush);
    painter.setOpacity(1.0);
#endif


    // 获取页面矩形区域
    QRect pageRect = printer->pageRect();

    // 绘制主框
    QRect frameRect(50, 50, pageRect.width() - 100, pageRect.height() - 100);
    QPen  pen(Qt::black, 1);    // 设置笔的宽度和颜色
    painter.setPen(pen);
    painter.drawRect(frameRect);

    // 绘制图像区域
    QRect imageRect = frameRect;
    imageRect.setHeight(imageRect.height() - ConTextHeight * 7);

    if (!_pixmap.isNull()) {
        QPixmap resizedPixmap =
            _pixmap.scaled(imageRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(imageRect, resizedPixmap);
    } else {
        logde << "pixmap is null.";
        return;
    }
    // 绘制文件信息区域
    QRect fileInfoRect(frameRect.x(),
                       frameRect.y() + imageRect.height(),
                       frameRect.width(),
                       ConTextHeight);
    painter.drawRect(fileInfoRect);

    QString fileName    = Global::getFileName(Global::_curveFileDataVtr.first().filePath);
    QString fileInfoStr = QString("  设备：差式扫描量热仪  文件名：") + fileName;

    painter.drawText(fileInfoRect,
                     Qt::AlignLeft | Qt::AlignVCenter,
                     fileInfoStr);

    // 绘制实验信息区域
    QRect experimentRect(frameRect.x(),
                         fileInfoRect.y() + fileInfoRect.height(),
                         2000,
                         ConTextHeight * 6);

    painter.drawRect(experimentRect);

    Global::ExperimentInfo exInfo = Global::_curveFileDataVtr.first().ei;
    if (Global::_curveFileDataVtr.empty()) {
        exInfo = Global::_experimentInfo;
    }

    QString experimentInfoStr = QString("  样品名称：%1 \n"
                                        "  样品重量：%2 mg\n"
                                        "  实验日期：%3 \n"
                                        "  实验人员：%4 \n")
                                    .arg(exInfo.sampleName)
                                    .arg(exInfo.sampleWeight)
                                    .arg(exInfo.date)
                                    .arg(exInfo.experimentor);
    painter.drawText(experimentRect, Qt::AlignLeft | Qt::AlignTop, experimentInfoStr);

    // 绘制阶段信息
    QRect phaseInfoRect(experimentRect.x() + experimentRect.width(), experimentRect.y(),
                        frameRect.width() - experimentRect.width(),
                        experimentRect.height());

    QVector<Global::PhaseTotalInfo> &phaseTotalVtr = Global::_curveFileDataVtr.first().phaseTotalVtr;

    logde << "phaseTotalVtr size:" << phaseTotalVtr.size();


    QMap<int, Phase> phaseMap;

    for (Global::PhaseTotalInfo &ptInfo : phaseTotalVtr) {
        phaseMap.insert(ptInfo.phaseIndex, ptInfo.phase);
        logde << "cutoff temp:" << ptInfo.phase.cutoff_temp;
    }

    QString phaseInfoStr;
    for (auto it = phaseMap.constBegin(); it != phaseMap.constEnd(); ++it) {
        logde << "Key:" << it.key() << ", Onoff:" << it.value().onoff;

        if (!it.value().onoff) {
            break;
        }

        QString gasName;
        switch (it.value().gas) {
            case GasType::NC:
                gasName = "NC";
                break;
            case GasType::N2:
                gasName = "N2";
                break;
            case GasType::O2:
                gasName = "O2";
                break;
            default:
                break;
        }

        phaseInfoStr.append(QString("阶段:%1  截止温度:%2  扫描速率:%3  恒温时间:%4  气氛:%5 \n")
                                .arg(QString::number(it.key()))
                                .arg(QString::number(it.value().cutoff_temp, 'f', 3))
                                .arg(QString::number(it.value().temp_flow, 'f', 3))
                                .arg(QString::number(it.value().constant_temp_time_min, 'f', 3))
                                .arg(gasName));
    }


    painter.drawText(phaseInfoRect,
                     Qt::AlignLeft | Qt::AlignTop,
                     phaseInfoStr);
}
