package com.younike.common.utils.qrcode;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.younike.common.utils.sign.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author chenpengfei
 */
@Slf4j
public class QRCodeGenerator {


    public static byte[] getQRCodeImage(String text, int width, int height) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        return pngOutputStream.toByteArray();
    }

    /**
     * 生成二维码并转成文件
     *
     * @param text
     * @param width
     * @param height
     * @param formatName
     * @param name
     * @param originalFileName
     * @return
     * @throws WriterException
     * @throws IOException
     */
    public static MultipartFile getQRCodeImageFile(String text, int width, int height, String formatName, String name, String originalFileName) throws IOException {
        BufferedImage bufferedImage = QrCodeUtil.generate(text, width, height);
        // 创建输出流
        ByteArrayOutputStream bos =new ByteArrayOutputStream();
        // 将图像输出到输出流中
        ImageIO.write(bufferedImage, formatName, bos);

        return new MockMultipartFile(name, originalFileName,"", bos.toByteArray());
    }

    public static void main(String[] args) {
        try {
            System.out.println(Base64.encode(getQRCodeImage("https://elev.uxianxin.com/code/f406c4340a6bd9", 350, 350)));;
        } catch (WriterException e) {
            System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
        }

    }

}
