package cn.pluss.platform.util;

import cn.hutool.core.codec.Base64;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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


/**
 * 二维码背景图片合成类
 */
public class QRCodeMaxUtil {

    private static Logger log = LoggerFactory.getLogger(QRCodeMaxUtil.class);
    //生成的二维码的路径
    private static final String QR_CODE_IMAGE_PATH = "D:\\temp\\MyQRCode.png";

    //文字显示
    private static final int QRCOLOR = 0x201f1f; // 二维码颜色:黑色
    private static final int BGWHITE = 0xFFFFFF; //二维码背景颜色:白色

    private static final int BLACK = 0xFF000000;

    private static final int WHITE = 0xFFFFFFFF;

    // 设置QR二维码参数信息
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);// 设置QR二维码的纠错级别(H为最高级别)
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);// 白边
        }
    };

    /**
     * 生成二维码图片+背景+文字描述
     * @param bgImgFile 背景图地址
     * @param WIDTH 二维码宽度
     * @param HEIGHT 二维码高度
     * @param qrUrl 二维码识别地址
     * @param note  文字描述1
     * @param tui   文字描述2
     * @param size 文字大小
     * @param imagesX 二维码x轴方向
     * @param imagesY 二维码y轴方向
     * @param text1X 文字描述1x轴方向
     * @param text1Y 文字描述1y轴方向
     * @param text2X 文字描述2x轴方向
     * @param text2Y 文字描述2y轴方向
     */
    public static String CreatQRCode(File bgImgFile, Integer WIDTH, Integer HEIGHT, String qrUrl,
                                   String note, String tui, Integer size, Integer imagesX, Integer imagesY, Integer text1X, Integer text1Y
            , Integer text2X, Integer text2Y) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为: 编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 开始利用二维码数据创建Bitmap图片，分别设为黑(0xFFFFFFFF) 白(0xFF000000)两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
                }
            }

            /*
             *     添加背景图片
             */
            BufferedImage backgroundImage = ImageIO.read(bgImgFile);
            int bgWidth = backgroundImage.getWidth();
            int qrWidth=image.getWidth();
            //距离背景图片x边的距离，居中显示
            int disx=(bgWidth-qrWidth)-imagesX;
            //距离y边距离 * * * *
            int disy=imagesY;
            Graphics2D rng=backgroundImage.createGraphics();
            rng.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP));
            rng.drawImage(image,disx,disy,WIDTH,HEIGHT,null);

            /*
             *     文字描述参数设置
             */

            Color textColor=Color.white;
            rng.setColor(textColor);
            rng.drawImage(backgroundImage,0,0,null);
            //设置字体类型和大小(BOLD加粗/ PLAIN平常)
            rng.setFont(new Font("微软雅黑,Arial",Font.BOLD,size));
            //设置字体颜色
            rng.setColor(Color.black);
            int strWidth=rng.getFontMetrics().stringWidth(note);

            //文字1显示位置 //左右 //上下
            int disx1=(bgWidth-strWidth)-text1X;
            rng.drawString(note,disx1,text1Y);

            //文字2显示位置 //左右 //上下
            int disx2=(bgWidth-strWidth)-text2X;
            rng.drawString(tui,disx2,text2Y);

            rng.dispose();
            image = backgroundImage;
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            String base64 = Base64.encode(stream.toByteArray());
            String newBase64 = "data:image/png;base64,"+Base64Util.compressPic(base64, 500);
            return newBase64;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static File createQrCode(String url, String path,String suffix,int width,int height) {
        try {
            Map<EncodeHintType, String> hints = Maps.newHashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
            File file = new File(path, StringUtil.genUuid() + "."+ suffix);
            writeToFile(bitMatrix, suffix, file);
            return file;
        } catch (Exception e) {
            log.error("二维码图片生成失败");
            return null;
        }
    }

    private static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
        BufferedImage image = toBufferedImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("Could not write an image of format " + format + " to " + file);
        }
    }

    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.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, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
}
