#include "Demo001_1.h"
#include "ui_Demo001_1.h"
#include <QSettings>
#include <QCloseEvent>
#include "Group.h"
#include <QVBoxLayout>
#include <QTimer>

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

    // initFrom();
}

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

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

    ui->label_Percentage->setAlignment(Qt::AlignCenter);

    // 设置右下部分
    // loadSliderStates();

    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 *leftLayout = new QVBoxLayout();
    QVBoxLayout *rightLayout = new QVBoxLayout();

    leftLayout->setSpacing(16); // 设置Group之间的间隔距离
    leftLayout->setMargin(0);
    rightLayout->setSpacing(16); // 设置Group之间的间隔距离
    rightLayout->setMargin(0);

    // 添加控件到左侧布局
    QStringList dispmodel;
    dispmodel << "P die align" << "D device align";
    Group *widget = new Group(6, ":/images/test_image/image_1.png", ":/images/test_image/image_2.png", dispmodel, this);
    leftLayout->addWidget(widget);

    QStringList dispmodel1;
    dispmodel1 << "D device align" << "P die align";
    Group *widget_1 = new Group(7, ":/images/test_image/image_3.png", ":/images/test_image/image_4.png", dispmodel1, this);
    leftLayout->addWidget(widget_1);

    // 添加控件到右侧布局
    QStringList dispmodel2;
    dispmodel2 << "B device align" << "P die align";
    Group *widget_2 = new Group(8, ":/images/test_image/image_5.png", ":/images/test_image/image_6.png", dispmodel2, this);
    rightLayout->addWidget(widget_2);

    QStringList dispmodel3;
    dispmodel3 << "U die align" << "D device align";
    Group *widget_3 = new Group(9, ":/images/test_image/image_7.png", ":/images/test_image/image_8.png", dispmodel3, this);
    rightLayout->addWidget(widget_3);

    // 添加最后一个控件到左侧布局
    // Group *widget_4 = new Group(5, ":/images/test_image/image.png", ":/images/test_image/image_2.png", dispmodel, this);
    // leftLayout->addWidget(widget_4);

    // 设置控件的最小高度和最大宽度
    int minHeight = 162;
    int maxWidth = 244;
    QWidgetList widgets = {widget, widget_1, widget_2, widget_3, /*widget_4*/};
    for (QWidget *w : widgets) {
        w->setMinimumHeight(minHeight);
        w->setMaximumWidth(maxWidth);
    }

    mainLayout->addLayout(leftLayout);
    mainLayout->addSpacing(8);
    mainLayout->addLayout(rightLayout);

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

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

    ui->Operatewidget->setMouseTracking(true);
}

void Demo001_1::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_1::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_1::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_1::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_1::loadSettings()
{
    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();
    loadGroupSettings(groupId, index);
}

void Demo001_1::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 = ui->Operatewidget->size();

    QPixmap newPixmap;
    if (Index == 1) {
        newPixmap = QPixmap(imagePath1);
    } else if (Index == 2) {
        newPixmap = QPixmap(imagePath2);
    } else {
        newPixmap = QPixmap(":/images/test_image/image.png");
    }

    QPixmap scaledPixmap = newPixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->Operatewidget->setPixmap(scaledPixmap);

    // 更新当前图片的成员变量
    currentPixmap = scaledPixmap;
    scaleFactor = 1.0;
    ui->label_Percentage->setText("100%");

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

void Demo001_1::on_ZoomUpButton_clicked()
{
    scaleFactor *= 1.1;

    int newWidth = currentPixmap.width() * scaleFactor;
    int newHeight = currentPixmap.height() * scaleFactor;

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

    ui->Operatewidget->setPixmap(scaledImage);

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


void Demo001_1::on_ZoomOutButton_clicked()
{
    scaleFactor *= 0.9;

    int newWidth = currentPixmap.width() * scaleFactor;
    int newHeight = currentPixmap.height() * scaleFactor;

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

    ui->Operatewidget->setPixmap(scaledImage);

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

void Demo001_1::wheelEvent(QWheelEvent *event)
{
    if (ui->Operatewidget->rect().contains(ui->Operatewidget->mapFromGlobal(event->globalPos()))) {
        if (event->angleDelta().y() > 0) {
            scaleFactor *= 1.1;
        } else {
            scaleFactor *= 0.9;
        }

        int newWidth = currentPixmap.width() * scaleFactor;
        int newHeight = currentPixmap.height() * scaleFactor;

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

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

    QMainWindow::wheelEvent(event);
}

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

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