package cn.com.capcloud.core.util;


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 javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class QRCodeUtil {
    private static final int BLACK = 0x000000;// 二维码颜色==黑色
    private static final int WHITE = 0xFFFFFF;// 二维码背景颜色==白色

    public static String drawLogoQRCode(File logoFile, File codeFile, String contents, String bottomText, int WIDTH, int HEIGHT) {
        try {
            Map<EncodeHintType, Object> hints = new HashMap();
            //设置编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置容错率最高
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(contents, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0x000000）白（0xFFFFFF）两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
                }
            }
            int width = image.getWidth();
            int height = image.getHeight();
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }
            // 自定义文本描述
            if (bottomText != null && !bottomText.isEmpty()) {
                // 新的图片，把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(WIDTH, HEIGHT+70, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                int strWidth = outg.getFontMetrics().stringWidth(bottomText);
                if (strWidth > 399) {
                    // //长度过长就截取前面部分
                    // 长度过长就换行
                    String note1 = bottomText.substring(0, bottomText.length() / 2);
                    String note2 = bottomText.substring(bottomText.length() / 2, bottomText.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("宋体", Font.BOLD, 30)); // 字体、字型、字号
                    outg2.drawString(note2, 100, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                } else {
                    outg.drawString(bottomText, 60, height + (outImage.getHeight() - height) / 2); // 画文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }
            image.flush();
            ImageIO.write(image, "png", codeFile);
            return "1";
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }
    public static Map<String,Object> drawLogoQRCode(File logoFile, File codeFile,Map<String,Object> map) {
        String contents=String.valueOf(map.get("contents"));
        String logoSeat=String.valueOf(map.get("logoSeat"));
        String bottomText=String.valueOf(map.get("bottomText"));
        Integer bottomTextSize=Integer.valueOf(String.valueOf(map.get("bottomTextSize")));
        Integer WIDTH=Integer.valueOf(String.valueOf(map.get("width")));
        Integer HEIGHT=Integer.valueOf(String.valueOf(map.get("height")));
        Integer qrCodeColor=Integer.decode(String.valueOf(map.get("qrCodeColor")));
        try {
            Map<EncodeHintType, Object> hints = new HashMap();
            //设置编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置容错率最高
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为：编码内容，编码类型，生成图片宽度，生成图片高度，设置参数
            BitMatrix bm = multiFormatWriter.encode(contents, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 开始利用二维码数据创建Bitmap图片，分别设为黑（0x000000）白（0xFFFFFF）两色
            for (int x = 0; x < WIDTH; x++) {
                for (int y = 0; y < HEIGHT; y++) {
                    image.setRGB(x, y, bm.get(x, y) ? qrCodeColor : WHITE);
                }
            }
            int width = image.getWidth();
            int height = image.getHeight();
            if (Objects.nonNull(logoFile) && logoFile.exists()) {
                Graphics2D g = image.createGraphics();// 构建绘图对象
                BufferedImage logo = ImageIO.read(logoFile);// 读取Logo图片
                Integer x;
                Integer y;
                if(logoSeat.equals("centre")){//放中间
                    x=width * 2 / 5;
                    y=height * 2 / 5;
                }else{//放右下角
                    x=width * 4/ 5-18;
                    y=height * 4/ 5-12;
                }
                // 开始绘制logo图片
                g.drawImage(logo, x, y, width * 2 / 10, height * 2 / 10, null);
                g.dispose();
                logo.flush();
            }
            // 自定义文本描述
            if (bottomText != null && !bottomText.isEmpty()) {
                // 新的图片，把带logo的二维码下面加上文字
                BufferedImage outImage = new BufferedImage(WIDTH, HEIGHT+(40+bottomTextSize), BufferedImage.TYPE_4BYTE_ABGR);//高度是默认高度+40+字体高度
                Graphics2D outg = outImage.createGraphics();
                // 画二维码到新的面板
                outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
                // 画文字到新的面板
                outg.setColor(Color.BLACK);
                outg.setFont(new Font("宋体", Font.BOLD, bottomTextSize)); // 字体、字型、字号
                int strWidth = outg.getFontMetrics().stringWidth(bottomText);
                if (strWidth > (WIDTH-50)) {
                    // 长度过长就换行
                    String note1 = bottomText.substring(0, bottomText.length() / 2);
                    String note2 = bottomText.substring(bottomText.length() / 2, bottomText.length());
                    int strWidth1 = outg.getFontMetrics().stringWidth(note1);
                    outg.drawString(note1, 200 - strWidth1 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                    BufferedImage outImage2 = new BufferedImage(WIDTH, HEIGHT+(60+bottomTextSize), BufferedImage.TYPE_4BYTE_ABGR);
                    Graphics2D outg2 = outImage2.createGraphics();
                    outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                    outg2.setColor(Color.BLACK);
                    outg2.setFont(new Font("宋体", Font.BOLD, bottomTextSize)); // 字体、字型、字号
                    outg2.drawString(note2, 100, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                    outg2.dispose();
                    outImage2.flush();
                    outImage = outImage2;
                    HEIGHT+=60+bottomTextSize;
                } else {
                    HEIGHT+=40+bottomTextSize;
                    outg.drawString(bottomText, 60, height + (outImage.getHeight() - height) / 2); // 画文字
                }
                outg.dispose();
                outImage.flush();
                image = outImage;
            }
            image.flush();
            ImageIO.write(image, "png", codeFile);
            map.put("height",HEIGHT);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}