#include "Waffle.h"
#include <QPainter>
#include <QPaintEvent>

Waffle::Waffle(int flag, QWidget *parent) : QWidget(parent) {
    // 根据不同窗口设置不同大小 0：小 1：中 2：大
    if (flag == 0) {
        // 华夫台的参数
        gridSize = 5;  // 每个格子的大小
        gap = 3;        // 格子之间的间隙
        boxGap = 6;    // 华夫台之间的间隙
    } else if (flag == 1) {
        // 华夫台的参数
        gridSize = 20;  // 每个格子的大小
        gap = 6;        // 格子之间的间隙
        boxGap = 12;    // 华夫台之间的间隙
    } else if (flag == 2) {
        // 华夫台的参数
        gridSize = 50;  // 每个格子的大小
        gap = 6;        // 格子之间的间隙
        boxGap = 12;    // 华夫台之间的间隙
    }
}

void Waffle::paintEvent(QPaintEvent *event) {
    QPainter painter(this);

    // 设置抗锯齿，使绘图更平滑
    painter.setRenderHint(QPainter::Antialiasing);

    // 绘制背景
    painter.fillRect(this->rect(), Qt::white);


    // 计算每个华夫台的总宽度和高度
    int totalWidth = cols * gridSize + (cols - 1) * gap;
    int totalHeight = rows * gridSize + (rows - 1) * gap;

    // 计算华夫盒的总宽度和高度
    int boxTotalWidth = boxCols * totalWidth + (boxCols - 1) * boxGap;
    int boxTotalHeight = boxRows * totalHeight + (boxRows - 1) * boxGap;

    // 确定华夫盒的起始位置，使其居中
    int boxStartX = (width() - boxTotalWidth) / 2;
    int boxStartY = (height() - boxTotalHeight) / 2;

    // 绘制多个华夫台
    for (int i = 0; i < boxRows; ++i) {
        for (int j = 0; j < boxCols; ++j) {
            // 计算每个华夫台的起始位置
            int startX = boxStartX + j * (totalWidth + boxGap);
            int startY = boxStartY + i * (totalHeight + boxGap);

            // 绘制单个华夫台
            drawWaffle(painter, startX, startY, rows, cols, gridSize, gap);
        }
    }
}

void Waffle::drawWaffle(QPainter &painter, int startX, int startY, int rows, int cols, int gridSize, int gap) {
    // 绘制网格
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            // 计算每个格子的坐标
            int x = startX + j * (gridSize + gap);
            int y = startY + i * (gridSize + gap);
            QRect cellRect(x, y, gridSize, gridSize);

            // 填充颜色
            painter.fillRect(cellRect, Qt::yellow);

            // 绘制边框
            painter.setPen(Qt::black);
            painter.drawRect(cellRect);
        }
    }
}
