#include "Group.h"
#include "ui_Group.h"
#include <QMouseEvent>
#include <QSettings>
#include <QVBoxLayout>
#include <QLabel>
#include <QTimer>

// 静态变量初始化
Group* Group::m_pCurrentlySelectedGroup = nullptr;
Group* Group::m_pPreviouslySelectedBlueGroup = nullptr;
Group* Group::m_pLastClickedGroup = nullptr;
int Group::m_stnLastClickedIndex = 0;
int Group::m_stnLastSavedIndex = 1;

Group::Group(int Id, const QString& imagePath1, int MaterialWindowType, const QStringList& textList, QWidget* parent)
    : QWidget(parent), ui(new Ui::Group), m_nGroupId(Id)
{
    ui->setupUi(this);

    QPixmap pixmap1(imagePath1);
    ui->Imagewidget_left->setPixmap(pixmap1);

    ui->DatacomboBox->addItems(textList);
    ui->GroupButton->setStyleSheet(
        "QPushButton:hover {"
        "   background-color: #45a049;"
        "}"
        "QPushButton:pressed {"
        "   background-color: #3e8e41;"
        "}"
        );

    ui->Imagewidget_left->setProperty("groupId", Id);
    ui->Imagewidget_right->setProperty("groupId", Id);

    if (MaterialWindowType == 1) 
    {
        m_pWafer = new Wafer(0, ui->Imagewidget_right);
        WaferWidget();
    } 
    else if (MaterialWindowType == 2) 
    {
        m_pWaffle = new Waffle(0, ui->Imagewidget_right);
        WaffleWidget();
    }
    else if (MaterialWindowType == 3) 
    {
        m_pMaterialbox = new MaterialBox(0, ui->Imagewidget_right);
        MaterialBoxWidget();
    }

    saveGroupSettings(Id, imagePath1, MaterialWindowType, textList);
    connect(ui->GroupButton, &QPushButton::clicked, this, &Group::onclickbutton);
    initForm();

    connect(this, &Group::SendGroupSelectedSignals, this, &Group::GetGroupSelectedSlots);
}

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

void Group::initForm()
{
    ui->Imagewidget_left->installEventFilter(this);
    ui->Imagewidget_right->installEventFilter(this);

    // MainWnd *mainWindow = new MainWnd();
    // connect(mainWindow,&MainWnd::styleChanged,this,&Group::Changedstyle);
    // QTimer *timer = new QTimer(this);
    // connect(timer, &QTimer::timeout, this, &Group::Changedstyle);
    // timer->start(100);
}

void Group::Changedstyle()
{
    QSettings settings("YourCompany", "YourApplication_style");
    int flag = settings.value("Flag_Style", 0).toInt();

    if (flag == 0) {
        ui->DatacomboBox->setStyleSheet("background-color: #FFFFFF;");
    } else {
        ui->DatacomboBox->setStyleSheet("background-color: #4C4FA6;");
    }
}

bool Group::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::MouseButtonDblClick) 
    {
        QMouseEvent* mouseEvent = static_cast<QMouseEvent*>(event);
        if (mouseEvent->button() == Qt::LeftButton)
        {
            int groupId = obj->property("groupId").toInt();
            QSettings settings("YourCompany", "YourApplication_");
            settings.setValue("GroupId", groupId);
            int index = 0;
            if (obj == this->ui->Imagewidget_left) 
            {
                index = 1;
                settings.setValue("Index", 1);
                check_selected(1);
            } 
            else if (obj == this->ui->Imagewidget_right)
            {
                index = 2;
                settings.setValue("Index", 2);
                check_selected(2);
            }
            emit SetCurrentSelectSig(groupId, index);
            emit SendGroupSelectedSignals(this, index);
            emit sendUpdateGroupState();
            return true;
        }
    }
    return QWidget::eventFilter(obj, event);
}

void Group::check_selected(int index)
{
    if (index == 1) 
    {
        ui->leftBackground->setStyleSheet("border: 2px solid red;");
    }
    else if (index == 2) 
    {
        ui->rightBackground->setStyleSheet("border: 2px solid red;");
    }
}

void Group::saveGroupSettings(int Id, const QString& imagePath1, int materialWndType, const QStringList& textList)
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(Id));
    settings.setValue("ImagePath1", imagePath1);
    settings.setValue("MaterialWndType", materialWndType);
    settings.setValue("TextList", textList);
    settings.endGroup();
}

void Group::WaferWidget()
{
    QVBoxLayout *layout2 = new QVBoxLayout(ui->Imagewidget_right);
    m_pWafer->paintInitFrom(ui->Imagewidget_right);

    QLabel* pixmapLabel = new QLabel();
    pixmapLabel->setPixmap(m_pWafer->getGlobalPixmap());

    ui->Imagewidget_right->setLayout(layout2);
    ui->Imagewidget_right->setFixedSize(110, 110);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout2->addWidget(pixmapLabel);
}

void Group::WaffleWidget()
{
    QVBoxLayout *layout2 = new QVBoxLayout(ui->Imagewidget_right);
    m_pWaffle->paintInitFrom(ui->Imagewidget_right);

    QLabel* pixmapLabel = new QLabel();
    pixmapLabel->setPixmap(m_pWaffle->getGlobalPixmap());

    ui->Imagewidget_right->setLayout(layout2);
    ui->Imagewidget_right->setFixedSize(110, 110);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout2->addWidget(pixmapLabel);
}

void Group::MaterialBoxWidget()
{
    QVBoxLayout* layout2 = new QVBoxLayout(ui->Imagewidget_right);
    m_pMaterialbox->paintInitFrom(ui->Imagewidget_right);

    QLabel* pixmapLabel = new QLabel();
    pixmapLabel->setPixmap(m_pMaterialbox->getGlobalPixmap());

    ui->Imagewidget_right->setLayout(layout2);
    ui->Imagewidget_right->setFixedSize(110, 110);
    layout2->setContentsMargins(0, 0, 0, 0);
    layout2->addWidget(pixmapLabel);
}

void Group::onclickbutton(){
    QSettings settings("YourCompany", "YourApplication_Button");
    settings.setValue("GroupId_button", m_nGroupId);

    emit send_button_Signal();
}

void Group::setDatacomboBox(int index){
    ui->DatacomboBox->setCurrentIndex(index);
}

void Group::on_DatacomboBox_currentIndexChanged(int index){
    send_ComboBox_singal(m_nCurrentGroupId,index);
}



void Group::UpDataImageShowSlots(const QPixmap& imageData)
{
    ui->Imagewidget_left->setGeometry(ui->Imagewidget_left->pos().x(),
        ui->Imagewidget_left->pos().y(),
        ui->Imagewidget_left->width(),
        ui->Imagewidget_left->height());
    ui->Imagewidget_left->setPixmap(imageData);

    emit SetUpDataImageShowSig(imageData);
}

void Group::showEvent(QShowEvent *event) {
    QWidget::showEvent(event);
    loadBorderSettings();
}

void Group::hideEvent(QHideEvent *event) {
    QWidget::hideEvent(event);
    saveBorderSettings();  // 保存边框颜色信息
}

void Group::saveBorderSettings()
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(m_nGroupId));

    QString leftStyle = ui->leftBackground->styleSheet();
    QString rightStyle = ui->rightBackground->styleSheet();

    if (leftStyle.contains("blue", Qt::CaseInsensitive)) {
        leftStyle = ""; // 清除样式
        // 记录该边框信息
        recordBorderInfo(m_nGroupId, "Left");
    }

    if (rightStyle.contains("blue", Qt::CaseInsensitive)) {
        rightStyle = ""; // 清除样式
        // 记录该边框信息
        recordBorderInfo(m_nGroupId, "Right");
    }


    settings.setValue("LeftBorderStyle", leftStyle);
    settings.setValue("RightBorderStyle", rightStyle);

    settings.setValue("LastClickedIndex", m_stnLastClickedIndex);
    settings.setValue("LastSavedIndex", m_stnLastSavedIndex);

    if (m_pCurrentlySelectedGroup == this) {
        settings.setValue("IsCurrentlySelected", true);
    }
    else {
        settings.setValue("IsCurrentlySelected", false);
    }

    settings.endGroup();
}

void Group::recordBorderInfo(int groupId, const QString& side)
{
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup("ModifiedBorders");
    QString key = QString("%1_%2").arg(groupId).arg(side);
    settings.setValue(key, true);
    settings.endGroup();
}

void Group::loadBorderSettings()
{
  
    QSettings settings("YourOrganization", "YourApplication");
    settings.beginGroup(QString::number(m_nGroupId));

    QString leftStyle = settings.value("LeftBorderStyle", "").toString();
    QString rightStyle = settings.value("RightBorderStyle", "").toString();
    m_stnLastClickedIndex = settings.value("LastClickedIndex", 0).toInt();
    m_stnLastSavedIndex = settings.value("LastSavedIndex", 1).toInt();
    bool isCurrentlySelected = settings.value("IsCurrentlySelected", false).toBool();

    QSettings settings2("OrganizationName__", "ApplicationName__");
    int Index = settings2.value("lastIndex", 1).toInt();

    if (Index == 2) {
        QSettings borderInfoSettings("YourOrganization", "YourApplication");
        borderInfoSettings.beginGroup("ModifiedBorders");
        QString leftKey = QString("%1_Left").arg(m_nGroupId);
        QString rightKey = QString("%1_Right").arg(m_nGroupId);

        // 检查左边框是否需要还原
        if (borderInfoSettings.contains(leftKey)) {
            leftStyle = getBlueBorderStyle();
            borderInfoSettings.remove(leftKey); // 移除记录,避免下次重复处理
            qDebug() << "Left border of group" << m_nGroupId << "restored to blue.";
            m_pPreviouslySelectedBlueGroup = this;
            // lastClickedGroup =this;
        }
        // 检查右边框是否需要还原
        if (borderInfoSettings.contains(rightKey)) {
            rightStyle = getBlueBorderStyle();
            borderInfoSettings.remove(rightKey);
            qDebug() << "Right border of group" << m_nGroupId << "restored to blue.";
            m_pPreviouslySelectedBlueGroup = this;
            // lastClickedGroup =this;
        }
        borderInfoSettings.endGroup();
    }

    ui->leftBackground->setStyleSheet(leftStyle);
    ui->rightBackground->setStyleSheet(rightStyle);

    if (isCurrentlySelected) {
        m_pCurrentlySelectedGroup = this;
        m_pLastClickedGroup = this;
        if (leftStyle.contains("red")) {
            m_stnLastClickedIndex = 1;
            qDebug() << "Left border of group" << m_nGroupId << "is red.";
        }
        else if (rightStyle.contains("red")) {
            m_stnLastClickedIndex = 2;
            qDebug() << "Right border of group" << m_nGroupId << "is red.";
        }
    }

    settings.endGroup();
}

QString Group::getBlueBorderStyle()
{
    static const QString blueBorderStyle = "border: 2px solid blue;";
    return blueBorderStyle;
}

QString Group::getRedBorderStyle()
{
    static const QString blueBorderStyle = "";
    return blueBorderStyle;
}

void Group::GetGroupSelectedSlots(Group* group, int index) {
    QSettings settings("OrganizationName__", "ApplicationName__");
    int currentLastSavedIndex = settings.value("lastIndex", 1).toInt();

    // 检查是否是同一个组的同一个索引被点击
    if (m_pLastClickedGroup == group && m_stnLastClickedIndex == index) {
        // 如果是同一个组的同一个索引被点击,则不更新边框
        return;
    }

    // 清除当前红色边框
    if (m_pCurrentlySelectedGroup != nullptr) {
        m_pCurrentlySelectedGroup->ui->leftBackground->setStyleSheet("");
        m_pCurrentlySelectedGroup->ui->rightBackground->setStyleSheet("");
    }

    // 清除当前蓝色边框
    if (m_pPreviouslySelectedBlueGroup != nullptr) {
        m_pPreviouslySelectedBlueGroup->ui->leftBackground->setStyleSheet("");
        m_pPreviouslySelectedBlueGroup->ui->rightBackground->setStyleSheet("");
    }

    if (currentLastSavedIndex == 1 || currentLastSavedIndex == 3) {
        // 仅当前选中设为红色,蓝色边框清空

        m_pPreviouslySelectedBlueGroup = nullptr;
    }
    else if (currentLastSavedIndex == 2) {
        // 当前选中设为红色,上一个选中设为蓝色
        if (m_pLastClickedGroup != nullptr) {
            QString blueBorderStyle = "border: 2px solid blue;";
            // 即使是同一个实例,只要索引不同就设置蓝色边框
            if (m_pLastClickedGroup == group && m_stnLastClickedIndex != index) {
                if (m_stnLastClickedIndex == 1) {
                    m_pLastClickedGroup->ui->leftBackground->setStyleSheet(blueBorderStyle);
                }
                else if (m_stnLastClickedIndex == 2) {
                    m_pLastClickedGroup->ui->rightBackground->setStyleSheet(blueBorderStyle);
                }
                m_pPreviouslySelectedBlueGroup = m_pLastClickedGroup;
            }
            else if (m_pLastClickedGroup != group) {
                if (m_stnLastClickedIndex == 1) {
                    m_pLastClickedGroup->ui->leftBackground->setStyleSheet(blueBorderStyle);
                }
                else if (m_stnLastClickedIndex == 2) {
                    m_pLastClickedGroup->ui->rightBackground->setStyleSheet(blueBorderStyle);
                }
                m_pPreviouslySelectedBlueGroup = m_pLastClickedGroup;
            }
        }
    }

    // 更新当前选中的 Group 实例
    m_pCurrentlySelectedGroup = group;
    // 将当前选中的边框设为红色
    group->check_selected(index);

    // 更新上一次点击的记录
    m_pLastClickedGroup = group;
    m_stnLastClickedIndex = index;
}

void Group::setEnableControls(bool enable) {
    ui->GroupButton->setEnabled(enable);
    ui->DatacomboBox->setEnabled(enable);
    if (enable == true) {
        ui->GroupButton->setStyleSheet(
            "QPushButton:hover {"
            "   background-color: #45a049;"
            "}"
            "QPushButton:pressed {"
            "   background-color: #3e8e41;"
            "}"
        );
    }
    else {
        ui->GroupButton->setStyleSheet("background-color: lightgray;");
    }
}