package com.hzs.common.core.utils;

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 lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * sui q
 */
@Slf4j
public class BarCodeUtils {

    /**
     * 创建0元注册二维码
     *
     * @param contents 二维码内容
     * @return
     */
    public static String createZeroQRCode(String contents) {
        String filePath = "";
        try {
            String ext = "png";

            Map<EncodeHintType, Object> hints = new HashMap<>();
            // 生成二维码时，白边框间隔距离
            hints.put(EncodeHintType.MARGIN, 1);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, 320, 320, hints);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            MatrixToImageWriter.writeToStream(bitMatrix, ext, byteArrayOutputStream);
            final InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

            // 上传OSS
            filePath = OssUtil.uploadFileForStream(inputStream, ext, "shareCode", null);
        } catch (Exception e) {
            log.error("createZeroQRCode error! contents: {}", contents, e);
        }
        return filePath;
    }

}

