package com.jsh.erp.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 com.jsh.erp.utils.OssUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成器
 */
@Component
public class QRCodeGenerator {

    @Value(value="${file.path}")
    private String filePath;

    OssUtils ossUtils;

    /**
     * 生成二维码图片
     * @param text 二维码内容
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param filePath 二维码数据文件路径
     * @throws Exception
     */
    public static void generateQRCodeImage(String text, int width, int height, String filePath) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置编码格式为UTF-8
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); // 输出图片格式为PNG
    }

    /**
     * 生成二维码图片
     * @param text 图片内容
     * @return
     */
    public String generateQRCodeImage(String text) throws Exception {
        int width = 300;
        int height = 300;
        String filePathContent = filePath + "/"+text+".png";
        generateQRCodeImage(text, width, height, filePathContent);
        File file = new File(filePathContent);
        return ossUtils.uploadFile(file);
    }

}
