package com.sunda.spmsweb.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.apache.commons.lang.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: spms
 * @description: Matrix code for storage number generate
 * @author: Wayne Wu
 * @create: 2021-06-30 10:58
 **/

public class MatrixCodeBoxNoteUtil {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    private MatrixCodeBoxNoteUtil() {
    }

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

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

    public 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;
    }

    public static BufferedImage generateMatrixCode(String boxNote) {
        try {
            String content = boxNote;
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 600, 600, hints);
            return toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedImage insertWords(BufferedImage image, String boxNote, String dn){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotEmpty(boxNote)) {
            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);
            // 画文字到新的面板
            Color color=new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("Arial", Font.PLAIN, 50));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(boxNote);
            //总长度减去文字长度的一半  （居中显示）
            int wordStartX= (WIDTH - strWidth) / 2;
            // 画文字
            g2d.drawString(boxNote, wordStartX, 600);

            if (StringUtils.isNotEmpty(dn)){
                g2d.setFont(new Font("Arial", Font.PLAIN, 50));
                g2d.drawString(dn, (WIDTH - g2d.getFontMetrics().stringWidth(dn)) / 2, 680);
            }

            g2d.setFont(new Font("Arial", Font.PLAIN, 30));
            g2d.drawString(sdf.format(new Date()), (WIDTH - g2d.getFontMetrics().stringWidth(sdf.format(new Date()))) / 2, 760);
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    public static BufferedImage insertImage(BufferedImage bufferedImage, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在！");
            return null;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > 600) {
                height = 600;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = bufferedImage.createGraphics();
        int x = (600 - width) / 2;
        int y = (600 - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
        return bufferedImage;
    }

    /**
     * 设置 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,WIDTH, WORDHEIGHT);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }


    public static BufferedImage rotateImage(final BufferedImage bufferedimage,
                                            final int angle){
        int width = bufferedimage.getWidth();
        int height = bufferedimage.getHeight();

        BufferedImage dstImage = null;
        AffineTransform affineTransform = new AffineTransform();

        if (angle == 180) {
            affineTransform.translate(width, height);
            dstImage = new BufferedImage(width, height, bufferedimage.getType());
        } else if (angle == 90) {
            affineTransform.translate(height, 0);
            dstImage = new BufferedImage(height, width, bufferedimage.getType());
        } else if (angle == 270) {
            affineTransform.translate(0, width);
            dstImage = new BufferedImage(height, width, bufferedimage.getType());
        }

        affineTransform.rotate(java.lang.Math.toRadians(angle));
        AffineTransformOp affineTransformOp = new AffineTransformOp(
                affineTransform,
                AffineTransformOp.TYPE_NEAREST_NEIGHBOR);

        return affineTransformOp.filter(bufferedimage, dstImage);
    }

    public static void main(String[] args) throws Exception {
        String boxNote = "ZX-10215700001-0202";
        String dn = "1180066383";
        /** 二维码中不带额外图片生成二维码 */
        //BufferedImage image = insertWords(generateMatrixCode(boxNote), boxNote, dn);

        /** 二维码中带额外图片生成二维码 */
        BufferedImage image = rotateImage(insertImage(insertWords(generateMatrixCode(boxNote), boxNote, dn), "BarCode/sunda.jpg", true), 90);
        ImageIO.write(image, "jpg", new File("BarCode/" + boxNote + ".jpg"));
    }

    public static void createMatrixWithPicture (String boxNote, String dn) throws Exception{
        BufferedImage image = rotateImage(insertImage(insertWords(generateMatrixCode(boxNote), boxNote, dn), "BarCode/sunda.jpg", true), 90);
        ImageIO.write(image, "jpg", new File("BarCode/" + boxNote + ".jpg"));
    }

    public static void createMatrixWithoutPicture (String boxNote, String dn) throws Exception{
        BufferedImage image = rotateImage(insertWords(generateMatrixCode(boxNote), boxNote, dn), 90);
        ImageIO.write(image, "jpg", new File("BarCode/" + boxNote + ".jpg"));
    }
}
