#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))
  //  ,_customPrintPreviewDialog(new QPrintPreviewDialog(_printer,this))
{
    ui->setupUi(this);

    _printer->setPageSize(QPageSize(QPageSize::A4));
    _printer->setOrientation(QPrinter::Landscape);

    _customPrintPreviewDialog = new QPrintPreviewDialog(_printer,this);

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

    _customPrintPreviewDialog->setWindowFlags(_customPrintPreviewDialog->windowFlags()
                                              | Qt::WindowMaximizeButtonHint
                                              | Qt::WindowMinimizeButtonHint);
}

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

void PrintPreviewForm::setPixmap(const QPixmap &pixmap)
{
#if 0
    QPixmap localPixmap = pixmap;
    localPixmap.scaled(ui->labelPixmap->size());
    ui->labelPixmap->setPixmap(pixmap);
#endif

    _pixmap = pixmap;
}


void PrintPreviewForm::slotPaintRequested(QPrinter *printer)
{
    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


    // 绘制第一页（不需要先调用 newPage()）
    //        painter.drawText(100, 100, "Page 1");

    QRect pageRect = printer->pageRect();
    qDebug()<<"rect:"<<pageRect;

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

    // Draw image.
    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<<"piamap is null.";
        return;
    }
    // file info
    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);

    // Experiment info.
    // Only print the first experiment data.
#if 0
    QRect experimentRect(frameRect.x(),
                         fileInfoRect.y() + fileInfoRect.height(),
                         1000,
                         frameRect.height() - imageRect.height() - fileInfoRect.height());
#endif
    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);

    // Phase info.
    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);
}



