#include "SingleCameraOperationWnd.h"
#include "ui_SingleCameraOperationWnd.h"
#include <QSettings>
#include <QCloseEvent>
#include <QVBoxLayout>
#include <QDebug>
#include <QTimer>
#include "CameraMaterialGroupWnd/CameraImage/CameraImageHandler.h"

SingleCameraOperationWnd::SingleCameraOperationWnd(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::SingleCameraOperationWnd), scaleFactor(1.0)
{
    ui->setupUi(this);
    isShow = true;
    initFrom();
}


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

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

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

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

    initSliders();
    initLineEdits();
    initProgressBar();
    // 连接 QSlider 的 valueChanged 信号到 QProgressBar 的 setValue 槽
    connect(ui->RedLightverticalSlider, &QSlider::valueChanged, ui->RedLightprogressBar, &QProgressBar::setValue);
    connect(ui->BlueLightverticalSlider, &QSlider::valueChanged, ui->BlueLightprogressBar, &QProgressBar::setValue);
    connect(ui->GreenLightverticalSlider, &QSlider::valueChanged, ui->GreenLightprogressBar, &QProgressBar::setValue);
    connect(ui->DotLightverticalSlider, &QSlider::valueChanged, ui->DotLightprogressBar, &QProgressBar::setValue);
    connectSliderAndLineEdit(ui->RedLightverticalSlider, ui->RedLightlineEdit);
    connectSliderAndLineEdit(ui->GreenLightverticalSlider, ui->GreenLightlineEdit);
    connectSliderAndLineEdit(ui->BlueLightverticalSlider, ui->BlueLightlineEdit);
    connectSliderAndLineEdit(ui->DotLightverticalSlider, ui->DotLightlineEdit);
	connect(ui->LiveButton,&QPushButton::clicked,this,&SingleCameraOperationWnd::loadLiveVedio);

    // 设置右上部分
    QWidget *viewport = ui->scrollArea->viewport();
    QWidget *container = new QWidget(viewport);
    QVBoxLayout *layout = new QVBoxLayout(container);

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

    QList<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8};

    QList<Group*> widgets;

    for (int i = 0; i < numbers.size(); ++i) {
        int num = numbers[i];
        CameraImageHandler* manager = new CameraImageHandler(num);
        Group* widget = manager->getGroup();
        connect(widget,&Group::send_button_Signal,this,&SingleCameraOperationWnd::showAndHideButton);
		connect(widget,&Group::send_ComboBox_singal,this,&SingleCameraOperationWnd::handleComBoxChange);
        if (widget != nullptr) {
            layout->addWidget(widget);
            widgets.append(widget);
			groupMap[num] = widget;
        }

        delete manager;
    }

    // 设置控件的最小高度和最大宽度
    int minHeight = 162;
    int maxWidth = 244;
    for (Group* w : widgets) {
        w->setMinimumHeight(minHeight);
        w->setMaximumWidth(maxWidth);
    }

    container->setLayout(layout);
    ui->scrollArea->setWidget(container);
    ui->scrollArea->resize(261, 700);

    ui->Operatewidget->setMouseTracking(true);
    connect(ui->Operatewidget,&ImageWidget::sendDoubleClicksignal,this,&SingleCameraOperationWnd::handleDoubleClick);
    connect(ui->DatacomboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SingleCameraOperationWnd::on_DatacomboBox_currentIndexChanged);

}

void SingleCameraOperationWnd::closeEvent(QCloseEvent *event) {
    // 保存滑块状态
    // saveSliderStates();

    // 确保调用基类的 closeEvent 处理其他关闭逻辑
    QMainWindow::closeEvent(event);
}

void SingleCameraOperationWnd::initSliders() {
    QList<QSlider*> sliders = {
        ui->RedLightverticalSlider, ui->GreenLightverticalSlider,
        ui->BlueLightverticalSlider, ui->DotLightverticalSlider
    };
    QList<int> initialValues = {22, 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 SingleCameraOperationWnd::initLineEdits() {
    QList<QLineEdit*> lineEdits = {
        ui->RedLightlineEdit, ui->GreenLightlineEdit,
        ui->BlueLightlineEdit, ui->DotLightlineEdit,
    };

    for (QLineEdit* lineEdit : lineEdits) {
        lineEdit->setAlignment(Qt::AlignCenter);
    }
}
void SingleCameraOperationWnd::initProgressBar(){
    QList<int> initialValues = {22, 11, 0, 0};
    QList<QProgressBar*> progressBar = {
        ui->RedLightprogressBar,ui->GreenLightprogressBar,
        ui->BlueLightprogressBar,ui->DotLightprogressBar
    };
    for (int i = 0; i < progressBar.size(); ++i) {
        progressBar[i]->setMinimum(0);
        progressBar[i]->setMaximum(100);
        progressBar[i]->setValue(initialValues[i]);
    }
}

// void SingleCameraOperationWnd::saveSliderStates() {
//     QSettings settings("YourCompany", "YourApp");
//     settings.beginGroup("SliderStates");
//     settings.setValue("verticalSlider", ui->verticalSlider->value());
//     settings.setValue("verticalSlider_2", ui->verticalSlider_2->value());
//     settings.setValue("verticalSlider_3", ui->verticalSlider_3->value());
//     settings.setValue("verticalSlider_4", ui->verticalSlider_4->value());
//     settings.setValue("verticalSlider_5", ui->verticalSlider_5->value());
//     settings.setValue("verticalSlider_6", ui->verticalSlider_6->value());
//     settings.endGroup();
// }

// void SingleCameraOperationWnd::loadSliderStates() {
//     QSettings settings("YourCompany", "YourApp");
//     settings.beginGroup("SliderStates");
//     ui->verticalSlider->setValue(settings.value("verticalSlider", 11).toInt());
//     ui->verticalSlider_2->setValue(settings.value("verticalSlider_2", 22).toInt());
//     ui->verticalSlider_3->setValue(settings.value("verticalSlider_3", 9).toInt());
//     ui->verticalSlider_4->setValue(settings.value("verticalSlider_4", 11).toInt());
//     ui->verticalSlider_5->setValue(settings.value("verticalSlider_5", 0).toInt());
//     ui->verticalSlider_6->setValue(settings.value("verticalSlider_6", 0).toInt());
//     settings.endGroup();
// }

// QSlider 和 QLineEdit 的联动
void SingleCameraOperationWnd::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 SingleCameraOperationWnd::checkSettings() {
    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 SingleCameraOperationWnd::loadSettings()
{
    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    int index = settings.value("Index", 0).toInt();
    loadGroupSettings(groupId, index);
}

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

    QSize size = ui->Operatewidget->size();

    QPixmap newPixmap;
    // 判断是实时图片还是物料窗口
    if (Index == 1) {
        newPixmap = QPixmap(imagePath1);
        clearLayout();
    } else if (Index == 2) {
        if (materialWndType == 1) {
            clearLayout();
            WaferWidget();
        } else if (materialWndType == 2) {
            clearLayout();
            WaffleWidget();
        } else if (materialWndType == 3) {
            clearLayout();
            MaterialBoxWidget();
        }
    }

    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);
    // qDebug() << "ComboBox items added:" << ui->DatacomboBox->count();
    // connect(ui->DatacomboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(SingleCameraOperationWnd::onComboBoxIndexChanged(int)));
}

// 清除大窗口上当前的布局
void SingleCameraOperationWnd::clearLayout() {
    // 获取当前布局
    QLayout* layout = ui->Operatewidget->layout();
    if (layout) {
        QLayoutItem *child;
        while ((child = layout->takeAt(0)) != nullptr) {
            if (child->widget() != nullptr) {
                delete child->widget();  // 删除控件
            }
            delete child;  // 删除布局项
        }
        delete layout;  // 删除布局本身
    }
}

// 圆晶
void SingleCameraOperationWnd::WaferWidget() {
    // QGridLayout *layout = new QGridLayout(ui->Operatewidget);
    // wafer = new Wafer(2, ui->Operatewidget);
    // wafer->initFrom(ui->Operatewidget);

    // layout->setContentsMargins(0, 0, 0, 0);
    // layout->addWidget(wafer->globalWidget);
    // ui->Operatewidget->setLayout(layout);
    // ui->Operatewidget->setFixedSize(786, 786);
}

// 华夫盒
void SingleCameraOperationWnd::WaffleWidget() {
    QVBoxLayout *layout = new QVBoxLayout(ui->Operatewidget);
    waffle = new Waffle(2, ui->Operatewidget);

    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(waffle);
    ui->Operatewidget->setLayout(layout);
    ui->Operatewidget->setFixedSize(786, 786);
}

// 料盒
void SingleCameraOperationWnd::MaterialBoxWidget() {
    QVBoxLayout *layout = new QVBoxLayout(ui->Operatewidget);
    materialbox = new MaterialBox(2, ui->Operatewidget);

    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(materialbox);
    ui->Operatewidget->setLayout(layout);
    ui->Operatewidget->setFixedSize(786, 786);
}

void SingleCameraOperationWnd::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 SingleCameraOperationWnd::on_ZoomOutButton_clicked() {
    double newScaleFactor = scaleFactor * 0.9;

    if (newScaleFactor >= 1.0) {
        scaleFactor = newScaleFactor;
    } else {
        scaleFactor = 1.0;
    }

    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 SingleCameraOperationWnd::wheelEvent(QWheelEvent *event) {
//     // 检查鼠标事件是否发生在 Operatewidget 上
//     if (ui->Operatewidget->rect().contains(ui->Operatewidget->mapFromGlobal(event->globalPos()))) {
//         if (event->angleDelta().y() > 0) {
//             scaleFactor *= 1.1;
//         } else {
//             double newScaleFactor = scaleFactor * 0.9;

//             // 确保新的缩放因子不小于1.0（即图片的原始大小）
//             if (newScaleFactor >= 1.0) {
//                 scaleFactor = newScaleFactor;
//             } else {
//                 scaleFactor = 1.0;  // 如果新的缩放因子小于1.0，则直接设置为1.0
//             }
//         }

//         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 SingleCameraOperationWnd::wheelEvent(QWheelEvent *event) {
        // 检查鼠标事件是否发生在 Operatewidget 上
        if (ui->Operatewidget->rect().contains(ui->Operatewidget->mapFromGlobal(event->globalPos()))) {
            if (event->angleDelta().y() > 0) {
                scaleFactor *= 1.1;
            } else {
                double newScaleFactor = scaleFactor * 0.9;

                // 确保新的缩放因子不小于1.0（即图片的原始大小）
                if (newScaleFactor >= 1.0) {
                    scaleFactor = newScaleFactor;
                } else {
                    scaleFactor = 1.0;  // 如果新的缩放因子小于1.0，则直接设置为1.0
                }
            }

            int newWidth = currentPixmap.width() * scaleFactor;
            int newHeight = currentPixmap.height() * scaleFactor;
            qDebug()<<"11111"<<newWidth<<newHeight;
            QPixmap scaledImage = currentPixmap.scaled(newWidth, newHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);
            // ui->Operatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片
            // ui->Operatewidget->setPixmapAndPoint(scaledImage);



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

        QMainWindow::wheelEvent(event);
}

void SingleCameraOperationWnd::onComboBoxIndexChanged(int index) {
    // 根据index获取图片路径
    QString imagePath = getImagePathFromIndex(index);
    if (!imagePath.isEmpty()) {
        QPixmap newPixmap(imagePath);
        QPixmap scaledPixmap = newPixmap.scaled(ui->Operatewidget->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        ui->Operatewidget->setPixmap(scaledPixmap);
        // 更新当前图片的成员变量
        currentPixmap = scaledPixmap;
        scaleFactor = 1.0;
        ui->label_Percentage->setText("100%");
    }
}

QString SingleCameraOperationWnd::getImagePathFromIndex(int index) {
    QStringList imagePaths = {
        ":/images/test_image/image.png",
        ":/images/test_image/image_2.png",
    };
    if (index >= 0 && index < imagePaths.size()) {
        return imagePaths[index];
    }
    return ":/images/test_image/image.png";
}

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

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

void SingleCameraOperationWnd::handleDoubleClick(){
    QPixmap scaledImage = currentPixmap.scaled(currentPixmap.width(), currentPixmap.height(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->Operatewidget->setPixmap(scaledImage); // 这里传递缩放后的图片
    scaleFactor = 1.0;
    ui->label_Percentage->setText("100%");
}

void SingleCameraOperationWnd::showAndHideButton(){
    if(isShow == true){
        isShow = false;
    }else{
        isShow = true;
    }
    QList<QLineEdit*> lineEdits = {
        ui->RedLightlineEdit, ui->GreenLightlineEdit,
        ui->BlueLightlineEdit, ui->DotLightlineEdit,
    };
    QList<QSlider*> sliders = {
        ui->RedLightverticalSlider, ui->GreenLightverticalSlider,
        ui->BlueLightverticalSlider, ui->DotLightverticalSlider
    };
    QList<QProgressBar*> progressBar = {
        ui->RedLightprogressBar,ui->GreenLightprogressBar,
        ui->BlueLightprogressBar,ui->DotLightprogressBar
    };
    if(isShow == true){
        for (QLineEdit* lineEdit : lineEdits) {
            lineEdit->show();
        }
        for (int i = 0; i < sliders.size(); ++i) {
            sliders[i]->show();
        }
        for (int i = 0; i < progressBar.size(); ++i) {
            progressBar[i]->show();
        }
        ui->BlueLight->show();
        ui->RedLight->show();
        ui->DotLight->show();
        ui->GreenLight->show();
        ui->BlueLightlabel->show();
        ui->RedLightlabel->show();
        ui->DotLightlabel->show();
        ui->GreenLightlabel->show();
    }else{
        for (QLineEdit* lineEdit : lineEdits) {
            lineEdit->hide();
        }
        for (int i = 0; i < sliders.size(); ++i) {
            sliders[i]->hide();
        }
        for (int i = 0; i < progressBar.size(); ++i) {
            progressBar[i]->hide();
        }
        ui->BlueLight->hide();
        ui->RedLight->hide();
        ui->DotLight->hide();
        ui->GreenLight->hide();
        ui->BlueLightlabel->hide();
        ui->RedLightlabel->hide();
        ui->DotLightlabel->hide();
        ui->GreenLightlabel->hide();
    }
}

void SingleCameraOperationWnd::startCamera(int cameraId) {
    m_grabber = new ImageGrabber(cameraId);
    connect(m_grabber, &ImageGrabber::imageGrabbed,
            this, &SingleCameraOperationWnd::updateImage);
    m_grabber->start();
}

void SingleCameraOperationWnd::on_DatacomboBox_currentIndexChanged(int index){
    QSettings settings("YourCompany", "YourApplication_");
    int groupId = settings.value("GroupId", 0).toInt();
    if (groupMap.contains(groupId)) {
        Group* group = groupMap[groupId];
        // 修改属性

        group->setDatacomboBox(index);
    } else {
        qDebug() << "Group with id" << groupId << "not found.";
    }

}
void SingleCameraOperationWnd::handleComBoxChange(int groupId,int index){
    QSettings settings("YourCompany", "YourApplication_");
    int currentGroupId = settings.value("GroupId", 0).toInt();
    if(currentGroupId == groupId){
        ui->DatacomboBox->setCurrentIndex(index);
    }
}

void SingleCameraOperationWnd::updateImage(const QImage&image){
    QPixmap pixmap = QPixmap::fromImage(image);
    QSize size = ui->Operatewidget->size();
    // QPixmap scaledPixmap = pixmap.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QPixmap scaledPixmap = pixmap.scaled(size, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->Operatewidget->setPixmap(scaledPixmap);

}

void SingleCameraOperationWnd::loadLiveVedio(){
    startCamera(0);
}
