package org.jeecg.modules.inventory.util;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Random;

public class BarcodeUtils {
    private static final String CHARSET = "utf-8";
    /**
     * 条形码宽度
     */
    private static final int WIDTH = 220;
    /**
     * 条形码高度
     */
    private static final int HEIGHT = 80;

    /**
     * 字体大小
     */
    private static final int FONT_SIZE = 14;

    /**
     * 加文字 条形码
     */
    private static final int WORD_HEIGHT = HEIGHT + FONT_SIZE+20;




    /**
     * 设置 条形码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<>(5);

    static {
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
    }

    /**
     * 生成 图片缓冲
     *
     * @param vaNumber VA 码
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage getBarCode(String vaNumber) {
        try {
            Code128Writer writer = new Code128Writer();
            // 编码内容, 编码类型, 宽度, 高度, 设置参数
            BitMatrix bitMatrix = writer.encode(vaNumber, BarcodeFormat.CODE_128, WIDTH, HEIGHT, hints);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把带logo的二维码下面加上文字
     *
     * @param image 条形码图片
     * @param words 文字
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage insertWords(BufferedImage image, String words) {
        // 新的图片，把带logo的二维码下面加上文字
        if (!StringUtils.isEmpty(words)) {
            BufferedImage outImage = new BufferedImage(WIDTH, WORD_HEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = outImage.createGraphics();
            // 抗锯齿
            setGraphics2D(g2d);
            // 设置白色
            setColorWhite(g2d);
            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            g2d.setColor(Color.BLACK);
            // 字体、字型、字号
            g2d.setFont(new Font("黑体", Font.PLAIN, FONT_SIZE));
            //设置条形码下面的文本的纵坐标
            int wordStartY = HEIGHT + 21;
            //-------------------------计算条形码的左边距，即左边空白的距离------------------------
            String content=words.substring(1,words.length()-1);
            int inputWidth = new Code128Writer().encode(content).length;
            int fullWidth = inputWidth + 1;
            int outputWidth = Math.max(WIDTH, fullWidth);
            int multiple = outputWidth / fullWidth;
            int leftPadding = (outputWidth - (inputWidth * multiple)) / 2;
            int x = leftPadding;
            //-----------------------计算条形码的左边距，即左边空白的距离----------------------

            String[] split = words.split("");
            int len = split.length;
            int step = new Long(Math.round(WIDTH - leftPadding * 2) / words.length()).intValue();
            for (int i = 0; i < len; i++) {
                g2d.drawString(split[i], x, wordStartY);
                x = x + step;
            }
            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.setColor(Color.BLACK);
    }







    public static void main(String[] args) throws Exception {
        // 条形码
        BufferedImage image = insertWords(getBarCode("16738566064729006090006"), "16738566064729006090006");
        ImageIO.write(image, "jpg", new File("D://barcode.jpg"));

    }
}


