package com.campus.activity.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QrCodeUtil {

    public static String generateQrCodeContent(Long activityId) {
        long timestamp = System.currentTimeMillis();
        return "CHECKIN:" + activityId + ":" + timestamp;
    }

    public static byte[] generateQrCodeImage(String content) throws IOException {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);

            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);

            return outputStream.toByteArray();
        } catch (com.google.zxing.WriterException e) {
            throw new RuntimeException("生成二维码失败", e);
        }
    }

    public static Long parseActivityIdFromQrCode(String qrCodeContent) {
        try {
            String[] parts = qrCodeContent.split(":");
            if (parts.length >= 2 && "CHECKIN".equals(parts[0])) {
                return Long.parseLong(parts[1]);
            }
        } catch (Exception e) {
            return null;
        }
        return null;
    }
}