package com.qmth.distributed.print.business.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.util.Base64Util;
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.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 条形码生成
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/4/27
 */
public class GoogleBarCodeUtil {
    private final static Logger log = LoggerFactory.getLogger(GoogleBarCodeUtil.class);

    /**
     * 条形码宽度
     */
    private static final int WIDTH = 300;

    /**
     * 条形码高度
     */
    private static final int HEIGHT = 50;

    /**
     * 加文字 条形码
     */
    private static final int WORDHEIGHT = 85;
    /**
     * 设置 条形码参数
     */
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            // 设置编码方式
            put(EncodeHintType.CHARACTER_SET, "utf-8");
//            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * 生成 图片缓冲
     *
     * @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 (WriterException e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
        return null;
    }

    /**
     * 把带logo的二维码下面加上文字
     *
     * @param image 条形码图片
     * @param words 文字
     * @param word
     * @return 返回BufferedImage
     * @author fxbin
     */
    public static BufferedImage insertWords(BufferedImage image, String words, boolean word) {
        // 新的图片，把带logo的二维码下面加上文字
        BufferedImage outImage = new BufferedImage(WIDTH, WORDHEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = outImage.createGraphics();
        // 抗锯齿
        setGraphics2D(g2d);
        // 设置白色
        setColorWhite(g2d);
        // 画条形码到新的面板
//        g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);//画字用
        g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
        if (Objects.nonNull(words) && word) {
            // 画文字到新的面板
            Color color = new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  （居中显示）
            int wordStartX = (WIDTH - strWidth) / 2;
            //height + (outImage.getHeight() - height) / 2 + 12
            int wordStartY = HEIGHT + 30;
            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
//            outImage.flush();
//            return outImage;
        }
        outImage.flush();
        return outImage;
    }

    /**
     * 设置 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 IOException {
//        BufferedImage image = getBarCode("202004270001");
//        ImageIO.write(image, "jpg", new File("/Users/king/Downloads/3.png"));
//
//        StringJoiner result = new StringJoiner("");
//        try {
//            BufferedReader br = new BufferedReader(new FileReader("/Users/king/Downloads/线下测试学校_1_阶梯教室_签到表和卷袋贴.html"));//构造一个BufferedReader类来读取文件
//            String s = null;
//            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
//                result.add(System.lineSeparator() + s);
//            }
//            br.close();
//        } catch (Exception e) {
//        }
//        String s = result.toString();
//        s = s.replaceAll("\\$\\{examNumber\\}", createBarCode("202007080001", true));
//        //随机生成学生试卷条码并将图片转成base64
//        s = s.replaceAll("\\$\\{paperType\\}", createBarCode(SystemConstant.convertPaperType("A"), false));
//        System.out.println(s);
//    }

    /**
     * 创建条码
     *
     * @param contennt
     * @param word
     * @return
     * @throws IOException
     */
    public static String createBarCode(String contennt, boolean word) throws IOException {
        BufferedImage image = GoogleBarCodeUtil.getBarCode(contennt);
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        String imageBase64 = Base64Util.encode(os.toByteArray());
        os.flush();
        os.close();
        return imageBase64;
    }
}