package com.mortals.xhx.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.mortals.framework.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:
 * @date: 2022/12/27 20:26
 */
@Slf4j
public class QrCodeUtil {

    /**
     * 默认宽度
     */

    private static final int WIDTH = 300;
    /**
     * 默认高度
     */

    private static final int HEIGHT = 300;
    /**
     * 默认文件格式
     */

    private static final String FORMAT = "png";

    /**
     * 条形码宽度
     */
    private static final int QR_WIDTH = 106;

    /**
     * 条形码高度
     */
    private static final int QR_HEIGHT = 75;

    /**
     * 加文字 条形码
     */
    private static final int WORDHEIGHT = 240;

    /**
     * 一些默认参数
     */
    private static final Map<EncodeHintType, Object> HINTS = new HashMap();

    static {
        // 字符编码
        HINTS.put(EncodeHintType.CHARACTER_SET, "utf-8");
        // 容错等级 L、M、Q、H 其中 L 为最低, H 为最高
        HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        // 二维码与图片边距
        HINTS.put(EncodeHintType.MARGIN, 2);
    }


    /**
     * 生成 图片缓冲
     *
     * @param vaNumber VA 码
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage getBarCode(String vaNumber) {
        Code128Writer writer = new Code128Writer();
        //为了无边距，需设置宽度为条码自动生成规则的宽度
        int width = writer.encode(vaNumber).length;
        //条码放大倍数
        int codeMultiples = 1;
        //获取条码内容的宽，不含两边距，当EncodeHintType.MARGIN为0时即为条码宽度
        int codeWidth = width * codeMultiples;
        int height = (int) (width * 0.7);
        try {
            // 编码内容, 编码类型, 宽度, 高度, 设置参数
            BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, codeWidth, height, HINTS);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成图片的条形码
     *
     * @param content 内容
     * @param paths   路径
     */
    public static void generateBarCodeFile(String content, String paths) {
        Code128Writer writer = new Code128Writer();
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, QR_HEIGHT, HINTS);
        Path path = Paths.get(paths);
        if (!StrUtil.isEmpty(content)) {
            try {
                MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
            } catch (IOException e) {
                log.error("生成条形码失败：{}", e.getMessage());
            }
        }
    }


    /**
     * 生成文件流的条形码
     *
     * @param content  内容
     * @param response 响应体
     * @return 流
     */
    public static OutputStream generateBarCodeStream(String content, HttpServletResponse response) {
        Code128Writer writer = new Code128Writer();
        OutputStream outputStream = null;
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, QR_HEIGHT, HINTS);
        if (!StrUtil.isEmpty(content)) {
            try {
                // 字节输出流
                outputStream = response.getOutputStream();
                MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
                return outputStream;
            } catch (IOException e) {
                log.error("生成条形码失败：{}", e.getMessage());
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.error("流关闭失败：{}", e.getMessage());
                    }
                }
            }
        }
        return null;
    }


    /**
     * 把带logo的二维码下面加上文字
     *
     * @param image 条形码图片
     * @param words 文字
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage insertWords(BufferedImage image, String words) {
        // 新的图片，把带logo的二维码下面加上文字
        if (StringUtils.isNotEmpty(words)) {
            int width=image.getWidth();
            int height = (int) (width * 0.7);
            Map<TextAttribute, Object> hm = new HashMap<>();
            hm.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD); // 定义加粗
            hm.put(TextAttribute.SIZE, 12); // 定义字号
            hm.put(TextAttribute.FAMILY, "微软雅黑"); // 定义字体名
            Font font = new Font(hm);

            Graphics2D graphics = image.createGraphics();
            graphics.setFont(font);
            int fontHeight = graphics.getFontMetrics().getHeight();
            int totalHeight=height+fontHeight;
            graphics.dispose();

            BufferedImage outImage = new BufferedImage(width, totalHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = outImage.createGraphics();
            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);
            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color = new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(font);

            //todo 文字换行显示，需要重新计算高度
          /*  FontMetrics fontMetrics = g2d.getFontMetrics();
            int strWidth = fontMetrics.stringWidth(words);

            //测量是否需要换行
            StringBuilder sb = new StringBuilder();
            int textLength = words.length();

            int totalWidth = fontMetrics.stringWidth(words); //文本的总长度，用于判断是否超出了范围
            if (totalWidth > width) {
                int nowWidth = 0; //目前一行写的长度
                //遍历当前文本行
                for (int i = 0; i < textLength; i++) {
                    sb.append(words.charAt(i));
                    int oneWordWidth = fontMetrics.charWidth(words.charAt(i)); //获取单个字符的长度
                    int tempWidth = oneWordWidth + nowWidth; //判断目前的一行加上这个字符的长度是否超出了总长度
                    if (tempWidth > width) {
                        //如果超出了一行的总长度，则要换成下一行 并画当前行
                        //int writeY = y + alreadyWriteLine * (textHeight + heightSpace);
                        y = drawAlignString(graphics2D, sb.toString(), align, x, y, lineWidth, lineHeight, tempWidth);
                        sb = new StringBuilder();
                        nowWidth = 0;
                    } else {
                        nowWidth = tempWidth;
                    }
                }
            }*/

            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  （居中显示）
            int wordStartX = (width - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY = height + 15;
            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    /**
     * 设置 Graphics2D 属性  （抗锯齿）
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setGraphics2D(Graphics2D g2d) {
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
        Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER);
        g2d.setStroke(s);
    }

    /**
     * 设置背景为白色
     *
     * @param g2d Graphics2D提供对几何形状、坐标转换、颜色管理和文本布局更为复杂的控制
     */
    private static void setColorWhite(Graphics2D g2d) {
        g2d.setColor(Color.white);
        g2d.fillRect(0,0,600,600);
        //g2d.setBackground(new Color(255, 255, 255));
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }

    /**
     * 生成base64的二维码
     *
     * @param content 内容
     * @return base64二维码
     */
    public static String generateBarCodeBase64(String content) {
        String base64;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Code128Writer writer = new Code128Writer();
        BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.CODE_128, WIDTH, HEIGHT, HINTS);
        if (!StrUtil.isEmpty(content)) {
            try {
                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, FORMAT, os);
                base64 = Base64.encode(os.toByteArray());
                return base64;
            } catch (Exception e) {
                log.error("生成二维码失败：{}", e.getMessage());
            } finally {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("流关闭失败：{}", e.getMessage());
                }

            }
        }
        return null;
    }


    /**
     * 生成图片的二维码
     *
     * @param content 内容
     */
    public static BufferedImage generateQrCode(String content, int width) {
        MultiFormatWriter writer = new MultiFormatWriter();
        if (!StrUtil.isEmpty(content)) {
            try {
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, width, HINTS);
                return MatrixToImageWriter.toBufferedImage(bitMatrix);
            } catch (Exception e) {
                log.error("生成二维码失败：{}", e.getMessage());
            }
        }
        return null;
    }


    /**
     * 生成图片的二维码
     *
     * @param content 内容
     * @param paths   路径
     */
    public static void generateQrCodeFile(String content, String paths) {
        MultiFormatWriter writer = new MultiFormatWriter();
        if (!StrUtil.isEmpty(content)) {
            try {
                // 字节输出流
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
                Path path = Paths.get(paths);
                MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
            } catch (Exception e) {
                log.error("生成二维码失败：{}", e.getMessage());
            }
        }

    }


    /**
     * 生成文件流的二维码
     *
     * @param content  内容
     * @param response 响应体
     * @return 流
     */
    public static OutputStream generateQrCodeStream(String content, HttpServletResponse response) {
        MultiFormatWriter writer = new MultiFormatWriter();
        OutputStream outputStream = null;
        if (!StrUtil.isEmpty(content)) {
            try {
                // 字节输出流
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
                outputStream = response.getOutputStream();
                MatrixToImageWriter.writeToStream(bitMatrix, FORMAT, outputStream);
                return outputStream;
            } catch (Exception e) {
                log.error("生成二维码失败：{}", e.getMessage());
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        log.error("流关闭失败：{}", e.getMessage());
                    }
                }
            }
        }
        return null;
    }


    /**
     * 生成base64的二维码
     *
     * @param content 内容
     * @return base64二维码
     */
    public static String generateQrCodeBase64(String content) {
        String base64;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        if (!StrUtil.isEmpty(content)) {
            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, HINTS);
                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ImageIO.write(bufferedImage, FORMAT, os);
                base64 = Base64.encode(os.toByteArray());
                return base64;
            } catch (Exception e) {
                log.error("生成二维码失败：{}", e.getMessage());
            } finally {
                try {
                    os.flush();
                    os.close();
                } catch (IOException e) {
                    log.error("流关闭失败：{}", e.getMessage());
                }

            }
        }
        return null;
    }


    public static void main(String[] args) throws IOException {
        //QrCodeUtil.generateBarCodeFile("2004171839281004aadddfffffddffgfggf", "E:\\pic\\jpg\\1.png");

        BufferedImage barCode = QrCodeUtil.getBarCode("123456789123456789");
        BufferedImage bufferedImage = QrCodeUtil.insertWords(barCode, "123456789123456789");
        ImageIO.write(bufferedImage,"png",new File("E:\\pic\\jpg\\test.png"));

    }


}