package com.jeequan.jeepay.bizcommons.manage.qrshell;

import com.alibaba.fastjson.JSON;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
* 仅二维码图片生成器
*
* @author terrfly
* @date 2022/1/17 17:36
*/
@Data
@Service
public class ShellQRGenerator extends AbstractGenerator {

    /** 生成二维码图片的 buffer缓冲值 **/
    @Override
    public BufferedImage genQrImgBuffer(String configModelStr, String qrUrlContent, Long qrcId, String mchStoreName, boolean isViewFlag) throws IOException, WriterException {

        String qrId = qrcId.toString();

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(qrUrlContent, BarcodeFormat.QR_CODE, 570, 570, hints);// 生成矩阵
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);


        CommonConfigModel configModel = StringUtils.isNotBlank(configModelStr) ? JSON.parseObject(configModelStr, CommonConfigModel.class) : null;

        // 默认全部显示 二维码ID ， 除非明确不显示
        boolean isShowIdFlag = true;
        if(configModel != null){
            isShowIdFlag = configModel.showIdFlag;
        }

        if(isShowIdFlag){

            Graphics2D graphic = bufferedImage.createGraphics();
            graphic.setColor(Color.black);//黑色
            //设置：二维码编号
            graphic = bufferedImage.createGraphics();
            graphic.setColor(Color.black);//背景设置为白色

            Font qrIdFont = new Font(AbstractGenerator.DEFAULT_FONT, Font.PLAIN, 19);
            FontMetrics metrics = graphic.getFontMetrics(qrIdFont);
            int x =  (bufferedImage.getWidth() - metrics.stringWidth(qrcId + "")) / 2;

            graphic.setFont(qrIdFont); //字体、字型、字号
            graphic.drawString(qrId , x, 550); //画文字
            graphic.drawRenderedImage(bufferedImage, null);
            graphic.dispose();
        }

        return bufferedImage;
    }

}
