#include "Demo001_2.h"
#include "ui_Demo001_2.h"
#include <QSettings>
#include <QCloseEvent>
#include "Group.h"
#include <QVBoxLayout>
#include <QTimer>

Demo001_2::Demo001_2(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Demo001_2)
{
    ui->setupUi(this);

    // initFrom();
}

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

void Demo001_2::initFrom()
{
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Demo001_2::checkSettings);
    timer->start(100);

    ui->Leftlabel_Percentage->setAlignment(Qt::AlignCenter);
    ui->Rightlabel_Percentage->setAlignment(Qt::AlignCenter);

    initSliders();
    initLineEdits();

    connectSliderAndLineEdit(ui->verticalSlider, ui->lineEdit);
    connectSliderAndLineEdit(ui->verticalSlider_2, ui->lineEdit_2);
    connectSliderAndLineEdit(ui->verticalSlider_3, ui->lineEdit_3);
    connectSliderAndLineEdit(ui->verticalSlider_4, ui->lineEdit_4);
    connectSliderAndLineEdit(ui->verticalSlider_7, ui->lineEdit_7);
    connectSliderAndLineEdit(ui->verticalSlider_8, ui->lineEdit_8);

    QWidget *viewport = ui->scrollArea->viewport();
    QWidget *container = new QWidget(viewport);

    // 创建水平布局
    QHBoxLayout *mainLayout = new QHBoxLayout(container);

    // 创建四个垂直布局，分别用于四个区域
    QVBoxLayout *vLayout1 = new QVBoxLayout();
    QVBoxLayout *vLayout2 = new QVBoxLayout();
    QVBoxLayout *vLayout3 = new QVBoxLayout();
    QVBoxLayout *vLayout4 = new QVBoxLayout();

    vLayout1->setSpacing(16);
    vLayout1->setMargin(0);
    vLayout2->setSpacing(16);
    vLayout2->setMargin(0);
    vLayout3->setSpacing(16);
    vLayout3->setMargin(0);
    vLayout4->setSpacing(16);
    vLayout4->setMargin(0);

    QStringList dispmodel1;
    dispmodel1 << "P die align" << "D device align";
    Group *widget1 = new Group(16, ":/images/test_image/image_1.png", ":/images/test_image/image_2.png", dispmodel1, this);

    QStringList dispmodel2;
    dispmodel2 << "D device align" << "P die align";
    Group *widget2 = new Group(17, ":/images/test_image/image_3.png", ":/images/test_image/image_4.png", dispmodel2, this);

    QStringList dispmodel3;
    dispmodel3 << "B device align" << "P die align";
    Group *widget3 = new Group(18, ":/images/test_image/image_5.png", ":/images/test_image/image_6.png", dispmodel3, this);

    QStringList dispmodel4;
    dispmodel4 << "U die align" << "D device align";
    Group *widget4 = new Group(19, ":/images/test_image/image_7.png", ":/images/test_image/image_8.png", dispmodel4, this);

    QStringList dispmodel5;
    dispmodel5 << "P die align" << "D device align";
    Group *widget5 = new Group(20, ":/images/test_image/image_1.png", ":/images/test_image/image_2.png", dispmodel1, this);

    QStringList dispmodel6;
    dispmodel6 << "D device align" << "P die align";
    Group *widget6 = new Group(21, ":/images/test_image/image_3.png", ":/images/test_image/image_4.png", dispmodel2, this);

    QStringList dispmodel7;
    dispmodel7 << "B device align" << "P die align";
    Group *widget7 = new Group(22, ":/images/test_image/image_5.png", ":/images/test_image/image_6.png", dispmodel3, this);

    QStringList dispmodel8;
    dispmodel8 << "U die align" << "D device align";
    Group *widget8 = new Group(23, ":/images/test_image/image_7.png", ":/images/test_image/image_8.png", dispmodel4, this);

    vLayout1->addWidget(widget1);
    vLayout1->addWidget(widget8);
    vLayout2->addWidget(widget7);
    vLayout2->addWidget(widget2);
    vLayout3->addWidget(widget3);
    vLayout3->addWidget(widget6);
    vLayout4->addWidget(widget5);
    vLayout4->addWidget(widget4);

    int minHeight = 162;
    int maxWidth = 244;
    QWidgetList widgets = {widget1, widget2, widget3, widget4, widget5, widget6, widget7, widget8};
    for (QWidget *w : widgets) {
        w->setMinimumHeight(minHeight);
        w->setMaximumWidth(maxWidth);
    }

    mainLayout->addLayout(vLayout1);
    mainLayout->addSpacing(8); // 第一个和第二个之间的间距
    mainLayout->addLayout(vLayout2);
    mainLayout->addSpacing(52); // 第二个和第三个之间的间距
    mainLayout->addLayout(vLayout3);
    mainLayout->addSpacing(8); // 第三个和第四个之间的间距
    mainLayout->addLayout(vLayout4);

    mainLayout->setContentsMargins(0, 0, 8, 0);

    container->setLayout(mainLayout);
    ui->scrollArea->setWidget(container);
    ui->scrollArea->resize(1083, 162);

    ui->LeftOperatewidget->setMouseTracking(true);
    ui->RightOperatewidget->setMouseTracking(true);
}

void Demo001_2::initSliders() {
    QList<QSlider*> sliders = {
        ui->verticalSlider, ui->verticalSlider_2, ui->verticalSlider_3,
        ui->verticalSlider_4, ui->verticalSlider_7, ui->verticalSlider_8
    };
    QList<int> initialValues = {11, 22, 9, 11, 0, 0};

    for (int i = 0; i < sliders.size(); ++i) {
        sliders[i]->setMinimum(0);
        sliders[i]->setMaximum(100);
        sliders[i]->setValue(initialValues[i]);
    }
}

void Demo001_2::initLineEdits() {
    QList<QLineEdit*> lineEdits = {
        ui->lineEdit, ui->lineEdit_2, ui->lineEdit_3,
        ui->lineEdit_4, ui->lineEdit_7, ui->lineEdit_8
    };

    for (QLineEdit* lineEdit : lineEdits) {
        lineEdit->setAlignment(Qt::AlignCenter);
    }
}

void Demo001_2::connectSliderAndLineEdit(QSlider* slider, QLineEdit* lineEdit)
{
    QIntValidator* validator = new QIntValidator(slider->minimum(), slider->maximum(), lineEdit);
    lineEdit->setValidator(validator);

    connect(slider, &QSlider::valueChanged, [lineEdit](int value) {
        lineEdit->setText(QString::number(value));
    });

    connect(lineEdit, &QLineEdit::textChanged, [slider](const QString &text) {
        bool ok;
        int value = text.toInt(&ok);
        if (ok && value >= slider->minimum() && value <= slider->maximum()) {
            slider->setValue(value);
        } else if (!text.isEmpty()) {
            int closestValue = qMin(qMax(text.toInt(&ok), slider->minimum()), slider->maximum());
            slider->setValue(closestValue);
        }
    });
}

void Demo001_2::checkSettings() {
    static int lastGroupId = -1;
    static int lastIndex = -1;

    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();

    if (groupId != lastGroupId || index != lastIndex) {
        lastGroupId = groupId;
        lastIndex = index;
        loadSettings();
    }
}

void Demo001_2::loadSettings()
{
    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();
    loadGroupSettings(groupId, index);
}

void Demo001_2::loadGroupSettings(int Id, int Index) {
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(Id));
    QString imagePath1 = settings.value("ImagePath1").toString();
    QString imagePath2 = settings.value("ImagePath2").toString();
    QStringList textList = settings.value("TextList").toStringList();
    settings.endGroup();

    QSize size_left = ui->LeftOperatewidget->size();
    QSize size_right = ui->RightOperatewidget->size();

    QPixmap LeftPixmap = QPixmap(imagePath2);
    QPixmap RightPixmap = QPixmap(imagePath1);

    QPixmap scaledPixmap_left = LeftPixmap.scaled(size_left, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->LeftOperatewidget->setPixmap(scaledPixmap_left);

    QPixmap scaledPixmap_right = RightPixmap.scaled(size_right, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->RightOperatewidget->setPixmap(scaledPixmap_right);

    // 更新当前图片的成员变量
    Left_currentPixmap = scaledPixmap_left;
    Left_scaleFactor = 1.0;
    Right_currentPixmap = scaledPixmap_right;
    Left_scaleFactor = 1.0;
    ui->Leftlabel_Percentage->setText("100%");
    ui->Rightlabel_Percentage->setText("100%");

    ui->LeftDataSources->clear();
    ui->LeftDataSources->addItems(textList);
    ui->RightDataSources->clear();
    ui->RightDataSources->addItems(textList);
    // connect(ui->DatacomboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(Demo001_3::onComboBoxIndexChanged(int)));
}


void Demo001_2::on_LeftZoomUpButton_clicked()
{
    Left_scaleFactor *= 1.1;

    int newWidth = Left_currentPixmap.width() * Left_scaleFactor;
    int newHeight = Left_currentPixmap.height() * Left_scaleFactor;

    QPixmap scaledImage = Left_currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    ui->LeftOperatewidget->setPixmap(scaledImage);

    double percentage = (Left_scaleFactor * 100);
    QString percentageStr = QString::number((int)percentage);
    ui->Leftlabel_Percentage->setText(QString("%1%").arg(percentageStr));
}


void Demo001_2::on_RightZoomUpButton_clicked()
{
    Right_scaleFactor *= 1.1;

    int newWidth = Right_currentPixmap.width() * Right_scaleFactor;
    int newHeight = Right_currentPixmap.height() * Right_scaleFactor;

    QPixmap scaledImage = Right_currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    ui->RightOperatewidget->setPixmap(scaledImage);

    double percentage = (Right_scaleFactor * 100);
    QString percentageStr = QString::number((int)percentage);
    ui->Rightlabel_Percentage->setText(QString("%1%").arg(percentageStr));
}


void Demo001_2::on_LeftZoomOutButton_clicked()
{
    Left_scaleFactor *= 0.9;

    int newWidth = Left_currentPixmap.width() * Left_scaleFactor;
    int newHeight = Left_currentPixmap.height() * Left_scaleFactor;

    QPixmap scaledImage = Left_currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    ui->LeftOperatewidget->setPixmap(scaledImage);

    double percentage = (Left_scaleFactor * 100);
    QString percentageStr = QString::number((int)percentage);
    ui->Leftlabel_Percentage->setText(QString("%1%").arg(percentageStr));
}


void Demo001_2::on_RightZoomOutButton_clicked()
{
    Right_scaleFactor *= 0.9;

    int newWidth = Right_currentPixmap.width() * Right_scaleFactor;
    int newHeight = Right_currentPixmap.height() * Right_scaleFactor;

    QPixmap scaledImage = Right_currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    ui->RightOperatewidget->setPixmap(scaledImage);

    double percentage = (Right_scaleFactor * 100);
    QString percentageStr = QString::number((int)percentage);
    ui->Rightlabel_Percentage->setText(QString("%1%").arg(percentageStr));
}

void Demo001_2::wheelEvent(QWheelEvent *event)
{
    if (ui->LeftOperatewidget->rect().contains(ui->LeftOperatewidget->mapFromGlobal(event->globalPosition().toPoint()))) {
        if (event->angleDelta().y() > 0) {
            Left_scaleFactor *= 1.1;
        } else {
            Left_scaleFactor *= 0.9;
        }

        int newWidth_left = Left_currentPixmap.width() * Left_scaleFactor;
        int newHeight_left = Left_currentPixmap.height() * Left_scaleFactor;

        QPixmap scaledImage_left = Left_currentPixmap.scaled(newWidth_left, newHeight_left, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->LeftOperatewidget->setPixmap(scaledImage_left);

        double percentage_left = Left_scaleFactor * 100;
        QString percentageStr_left = QString::number((int)percentage_left);
        ui->Leftlabel_Percentage->setText(QString("%1%").arg(percentageStr_left));
    }

    if (ui->RightOperatewidget->rect().contains(ui->RightOperatewidget->mapFromGlobal(event->globalPosition().toPoint()))) {
        if (event->angleDelta().y() > 0) {
            Right_scaleFactor *= 1.1;
        } else {
            Right_scaleFactor *= 0.9;
        }

        int newWidth = Right_currentPixmap.width() * Right_scaleFactor;
        int newHeight = Right_currentPixmap.height() * Right_scaleFactor;

        QPixmap scaledImage = Right_currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->RightOperatewidget->setPixmap(scaledImage);

        double percentage = Right_scaleFactor * 100;
        QString percentageStr = QString::number((int)percentage);
        ui->Rightlabel_Percentage->setText(QString("%1%").arg(percentageStr));
    }

    QMainWindow::wheelEvent(event);
}

void Demo001_2::showEvent(QShowEvent *event) {
    QMainWindow::showEvent(event);
    loadSettings();
    initFrom();
}

void Demo001_2::hideEvent(QHideEvent *event) {
    QMainWindow::hideEvent(event);
}

