#include "CameraDataHandleAndShow.h"
void ImageGrabber::stop() {
    m_running = false;
};

// long ImageGrabber::GrabImagetest(int iCameraId, ImageInfo& image){
//     static QMutex mutex;
//     QMutexLocker locker(&mutex);

//     // 生成测试图像数据
//     static int counter = 0;
//     int width = 640;
//     int height = 480;

//     image.width = width;
//     image.height = height;
//     image.format = RGB888;
//     image.channel = 3;

//     static QByteArray buffer(width * height * 3, 0);
//     unsigned char *ptr = reinterpret_cast<unsigned char*>(buffer.data());

//     // 生成渐变测试图
//     for(int y=0; y<height; ++y) {
//         for(int x=0; x<width; ++x) {
//             int offset = (y*width + x)*3;
//             ptr[offset]   = x*255/width;            // R
//             ptr[offset+1] = (x+y)*255/(width+height); // G
//             ptr[offset+2] = y*255/height;           // B
//         }
//     }

//     image.data = ptr;
//     return 0;
// }
long ImageGrabber::GrabImagetest(int iCameraId, ImageInfo& image) {
    static QMutex mutex;
    QMutexLocker locker(&mutex);

    // 动态控制变量（每次调用自增）
    static int counter = 0;
    counter = (counter + 1) % 1000;  // 防止溢出

    const int width = 640;
    const int height = 480;

    // 生成动态测试图案（示例包含三种动态模式）
    static QByteArray buffer(width * height * 3, 0);
    unsigned char* ptr = reinterpret_cast<unsigned char*>(buffer.data());

    for(int y = 0; y < height; ++y) {
        for(int x = 0; x < width; ++x) {
            int offset = (y * width + x) * 3;

            // 模式1：水平移动的色带
            int modulatedX = (x + counter) % width;

            // 模式2：脉动中心圆
            float dist = sqrt(pow(x-width/2,2) + pow(y-height/2,2));
            float pulse = (sin(counter*0.1) + 1) * 50;

            // 模式3：动态噪点
            float noise = (rand() % 100)/100.0 * 50 * sin(counter*0.05);
            // 强制类型转换解决浮点取模问题
            ptr[offset]   = static_cast<int>(modulatedX*255/width + pulse + noise) % 256;  // R
            ptr[offset+1] = static_cast<int>((x+y+counter)*255/(width+height) + noise) % 256; // G
            ptr[offset+2] = static_cast<int>(y*255/height + pulse) % 256; // B

        }
    }

    // 返回图像参数
    image.width = width;
    image.height = height;
    image.format = RGB888;
    image.channel = 3;
    image.data = ptr;

    return 0;
}
void ImageGrabber::run(){
    while(m_running) {
        ImageInfo imgInfo;
        if(GrabImagetest(1, imgInfo) == 0) {
            QImage image = convertImage(imgInfo);
            emit imageGrabbed(image);
        }
        msleep(1000);
    }
}

QImage ImageGrabber::convertImage(const ImageInfo &info) {
    QImage::Format format = QImage::Format_Invalid;
    switch(info.format) {
    case GRAY8:   format = QImage::Format_Grayscale8; break;
    case RGB888:  format = QImage::Format_RGB888; break;
    case ARGB8888:format = QImage::Format_ARGB32; break;
    case RGB32:   format = QImage::Format_RGB32; break;
    case YUV422:  return convertYUV422ToRGB(info);
    default:      return QImage();
    }

    return QImage(info.data, info.width, info.height,
                  info.width * info.channel, format).copy();
}

QImage ImageGrabber::convertYUV422ToRGB(const ImageInfo &info) {
    // 分配RGB数据的内存
    QVector<unsigned char> rgbData(info.width * info.height * 3);
    for (int y = 0; y < info.height; ++y) {
        for (int x = 0; x < info.width; x += 2) {
            // 计算YUV数据索引（每4字节处理2个像素）
            int yuvIndex = y * info.width * 2 + x * 2;

            // 提取YUV分量
            unsigned char Y0 = info.data[yuvIndex];
            unsigned char U  = info.data[yuvIndex + 1];
            unsigned char Y1 = info.data[yuvIndex + 2];
            unsigned char V  = info.data[yuvIndex + 3];

            // 将U/V转换为有符号（-128~127）
            float u = (float)U - 128.0f;
            float v = (float)V - 128.0f;

            // 处理第一个像素（Y0）
            float yScaled = (Y0 - 16) * 1.164f; // Y分量归一化
            int r = (int)(yScaled + 1.596f * v);
            int g = (int)(yScaled - 0.391f * u - 0.813f * v);
            int b = (int)(yScaled + 2.018f * u);

            // 钳位并存储第一个像素
            int rgbIndex = (y * info.width + x) * 3;
            rgbData[rgbIndex]     = (unsigned char)(r < 0 ? 0 : r > 255 ? 255 : r);
            rgbData[rgbIndex + 1] = (unsigned char)(g < 0 ? 0 : g > 255 ? 255 : g);
            rgbData[rgbIndex + 2] = (unsigned char)(b < 0 ? 0 : b > 255 ? 255 : b);

            // 处理第二个像素（Y1）
            yScaled = (Y1 - 16) * 1.164f;
            r = (int)(yScaled + 1.596f * v);
            g = (int)(yScaled - 0.391f * u - 0.813f * v);
            b = (int)(yScaled + 2.018f * u);

            // 钳位并存储第二个像素
            rgbIndex += 3; // 移动到下一个像素位置
            if (x + 1 < info.width) { // 确保不越界
                rgbData[rgbIndex]     = (unsigned char)(r < 0 ? 0 : r > 255 ? 255 : r);
                rgbData[rgbIndex + 1] = (unsigned char)(g < 0 ? 0 : g > 255 ? 255 : g);
                rgbData[rgbIndex + 2] = (unsigned char)(b < 0 ? 0 : b > 255 ? 255 : b);
            }
        }
    }
    // 创建QImage对象
    QImage image(rgbData.data(), info.width, info.height, QImage::Format_RGB888);
    return image;
}
