package com.yifu.cloud.plus.v1.yifu.archives.utils;

import cn.hutool.core.net.multipart.MultipartRequestInputStream;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.yifu.cloud.plus.v1.yifu.archives.entity.TAttaInfo;
import com.yifu.cloud.plus.v1.yifu.common.core.util.OSSUtil;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author fxj
 * @Date 2024/6/13
 * @Description
 * @Version 1.0
 */
@Slf4j
@Component
public class QrCodeUtil {

	public  InputStream createPng(String qrCodeContent){
		try {
		// 定义二维码的配置参数
		Map<EncodeHintType, Object> hints = new HashMap<>();
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 设置纠错级别（L、M、Q、H，从低到高）
		hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符集

		// 创建二维码编码器
		QRCodeWriter qrCodeWriter = new QRCodeWriter();

		// 生成二维码矩阵
		BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, 250, 250, hints);

		// 将BitMatrix转换为BufferedImage
		int width = bitMatrix.getWidth();
		int height = bitMatrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); // 黑白二值化
			}
		}

		// 保存为PNG图片
		File file = new File("output_qrcode.png");
		ImageIO.write(image, "PNG", file);
		InputStream in = new FileInputStream(file);
		file.deleteOnExit();
		return  in;
		} catch (IOException e) {
			log.error("failed:生成二维码失败",e.getMessage());
		} catch (WriterException e) {
			log.error("failed:生成二维码失败",e.getMessage());
		}
		return null;
	}
}
