#include <QFileDialog>

#include "coefficientselectionform.h"
#include "ui_coefficientselectionform.h"
#include "confighandler.h"
#include "logger.h"
#include "global.h"

CoefficientSelectionForm::CoefficientSelectionForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CoefficientSelectionForm)
  ,_instrumentCoefficient(ConfigHandler::ConInstrumentCoefficientDefaultValue)
{
    ui->setupUi(this);

    setWindowTitle("热焓校正系数选择");

#if 1
    ui->LineEditCoefficient->setText(
                QString::number(
                    ConfigHandler::_configMap[ConfigHandler::ConInstrumentCoefficientStr].toFloat(),
                    'f',3));
#endif

    ui->radioButtonSinglePointCoefficient->setChecked(true);
    ui->radioButtonSinglePointCoefficient->setChecked(false);

    on_radioButtonSinglePointCoefficient_toggled(true);
    on_radioButtonMultiPointCoefficient_toggled(false);

    ui->textEditFileContent->setReadOnly(true);
}

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

void CoefficientSelectionForm::showEvent(QShowEvent *event)
{

}

void CoefficientSelectionForm::on_pushButtonCalculate_clicked()
{
    bool ok;
    float theory = ui->LineEditTheory->text().toFloat(&ok);
    if(!ok){
        theory = 1.0;
    }

    float measure = ui->LineEditActualMeasurement->text().toFloat(&ok);
    if(!ok){
        measure = 1.0;
    }

    _instrumentCoefficient = theory/measure;
    ui->LineEditCoefficient->setText(QString::number(_instrumentCoefficient,'f',3));
}

void CoefficientSelectionForm::on_pushButtonConfirm_clicked()
{
    if(ui->radioButtonSinglePointCoefficient->isChecked()){
        ConfigHandler::_configMap[ConfigHandler::ConInstrumentCoefficientStr] = _instrumentCoefficient;
        ConfigHandler::writer();

        Global::_enthalpyCoefficientEnableFlag = false;
    }else{
        QJsonDocument doc = QJsonDocument::fromJson(_jsonStr.toUtf8());
        if (doc.isNull()) {
            logde << "Failed to parse JSON data";
            return;
        }
        if (!doc.isObject()) {
            logde << "JSON data is not an object";
            return ;
        }

        QJsonObject majorObj = doc.object();
        {
            QJsonObject subObj = majorObj[Global::AtomsphereData].toObject();

            double temperature = subObj[Global::Atmosphere].toDouble();
            double heatingRate = subObj[Global::HeatingRate].toDouble();

            logde<<"temperatur:"<<temperature;
            logde<<"heatingRate:"<<heatingRate;
        }

        QJsonArray jsonArray = majorObj[Global::SampleData].toArray();

        QVector<double> xVtr,yVtr;
        for (const QJsonValue &value : jsonArray) {
            QJsonObject jsonObj = value.toObject();
            xVtr<<jsonObj[Global::TemperatureStr].toDouble();
            yVtr<<jsonObj[Global::RateStr].toDouble();
        }

        double coeff[3] = {0};
        Global::quadraticLeastSquaresFit(xVtr.data(),yVtr.data(),xVtr.size(),coeff);

#if 0
        std::cout << "Fitted quadratic polynomial: y = "
                  << coeff[0] << "x^2 + "
                  << coeff[1] << "x + "
                  << coeff[2] << std::endl;
#endif

        logde<<"y:"<<coeff[0]<<"x2,"
            <<coeff[1]<<"x,"
           <<coeff[2];

        Global::_enthalpyCoefficientEnableFlag = true;

        Global::_enthalpyCoefficientVtr.clear();
        Global::_enthalpyCoefficientVtr.push_back(coeff[0]);
        Global::_enthalpyCoefficientVtr.push_back(coeff[1]);
        Global::_enthalpyCoefficientVtr.push_back(coeff[2]);
    }

    hide();
}

void CoefficientSelectionForm::on_pushButtonExit_clicked()
{
#if 0
    ui->LineEditTheory->clear();
    ui->LineEditCoefficient->clear();

    ui->labelFilePath->clear();
    ui->textEditFileContent->clear();

    _jsonStr.clear();
#endif

    hide();
}


void CoefficientSelectionForm::on_pushButtonSelectFile_clicked()
{
    QString filePath = QFileDialog::getOpenFileName(
                nullptr, "选择 JSON 文件", "", "JSON 文件 (*.json);;所有文件 (*.*)");

    if (!filePath.isEmpty()) {
        QFile file(filePath);
        if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QTextStream in(&file);
            _jsonStr = in.readAll();
            file.close();

        } else {
            qDebug() << "无法打开文件：" << filePath;
            return;
        }
    } else {
        qDebug() << "未选择文件";
        return;
    }

    //
    ui->labelFilePath->setText(filePath);
    ui->labelFilePath->setToolTip(filePath);

    ui->textEditFileContent->setText(_jsonStr);

    _instrumentCoefficient = ConfigHandler::ConInstrumentCoefficientDefaultValue;
}

void CoefficientSelectionForm::on_radioButtonSinglePointCoefficient_toggled(bool checked)
{
    ui->LineEditTheory->setEnabled(checked);
    ui->LineEditCoefficient->setEnabled(checked);
    ui->LineEditActualMeasurement->setEnabled(checked);

    ui->pushButtonCalculate->setEnabled(checked);
#if 0
    if(checked){
        ui->LineEditTheory->setEnabled(true);
        ui->LineEditCoefficient->setEnabled(true);
        ui->LineEditActualMeasurement->setEnabled(true);

        ui->pushButtonCalculate->setEnabled(true);
    }else{

        ui->LineEditTheory->setEnabled(false);
        ui->LineEditCoefficient->setEnabled(false);
        ui->LineEditActualMeasurement->setEnabled(false);

        ui->pushButtonCalculate->setEnabled(false);
    }
#endif
}

void CoefficientSelectionForm::on_radioButtonMultiPointCoefficient_toggled(bool checked)
{
    ui->pushButtonSelectFile->setEnabled(checked);
    ui->textEditFileContent->setEnabled(checked);
#if 0
    if(checked){
        ui->pushButtonSelectFile->setEnabled(true);
        ui->textEditFileContent->setEnabled(true);
    }else{
        ui->pushButtonSelectFile->setEnabled(false);
        ui->textEditFileContent->setEnabled(false);
    }
#endif
}
