package com.cirle.scientific.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

@Slf4j
public class QRCodeUtil {

    // LOGO宽度
    private static final int LOGO_WIDTH = 60;
    // LOGO高度
    private static final int LOGO_HEIGHT = 60;
    // 二维码尺寸
    private static final int QRCODE_SIZE = 200;

    /**
     * 生成二维码
     * @param content 二维码中的内容
     * @param wide 二维码的宽
     * @param high 二维码的高
     * @param isLog 是否需要二维码 0 不许要  1需要
     * @param logUrl log的url地址
     * @return 二维码图片
     */
    public static byte[] createQr(String content , Integer wide ,Integer high, Integer isLog ,String logUrl) throws Exception {
        byte[] bytes = null;
        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);
            //申明二维码像素点的信息对象
            BitMatrix bitMatrix = null;
            //保存二维码图像
            BufferedImage result = null;
            //返回的base64
            String binary = null;

            // 1、读取文件转换为字节数组
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,wide,high,hints);
            result = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < bitMatrix.getWidth(); x++) {
                for (int y = 0; y < bitMatrix.getHeight(); y++) {
                    result.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
                }
            }
            if(isLog == 1){
                createQrAddLog(2, result, logUrl);
            }
            //转换成png格式的IO流
            ImageIO.write(result, "png", out);
            bytes = out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("生成二维码报错 e->{}" , e);
        }
        return  bytes;
    }

    /**
     * @param fileOrUrl 本地地址或者url 1: 本地  2: url
     * @param bufferedImage 二维码的图片
     * @param log log的url或者本地地址
     * @return 返回带有log的二维码
     */
    public static BufferedImage createQrAddLog(Integer fileOrUrl , BufferedImage bufferedImage , String log){
        URL url ;
        //返回保存log保存的图片
        BufferedImage logImage = null;
        try {
            if(log != null && !"".equals(log)){
                if(fileOrUrl == 2){
                    url = new URL(log);
                    logImage = ImageIO.read(url);
                }else{
                    logImage = ImageIO.read(new File(log));
                }
            }
            int height =bufferedImage.getHeight() / 3;
            int width = bufferedImage.getWidth() / 3;
            //设置log的宽设置log的高
            Image logImage1 = logImage.getScaledInstance(width ,  height , Image.SCALE_SMOOTH);
            //插入图片
            Graphics g = bufferedImage.getGraphics();
            int y = (bufferedImage.getHeight() -height) / 2;
            int x = (bufferedImage.getWidth() - width ) /2;
            g.drawImage(logImage1,x,y,width,height,null);
            g.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  bufferedImage;
    }


    /**
     * 自定义颜色生成二维码
     * @param count 内容
     * @param onColor
     * @param offColor
     * @param wide 宽
     * @param high 高
     * @return 返回图片
     */
    public static  BufferedImage createQr(String count , Integer onColor , Integer offColor , Integer wide , Integer high){
        Map<EncodeHintType , Object> hints = new HashMap<>();
        //设置二维码的容错率
        hints.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.H);
        //设置编码
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        //设置二维码留白
        hints.put(EncodeHintType.MARGIN, 1);
        //创建二维码像素对象
        BitMatrix bitMatrix  = null;
        //返回的图片
        BufferedImage bufferedImage = null;
        try {
            bitMatrix = new MultiFormatWriter().encode(count, BarcodeFormat.QR_CODE, wide, high, hints);
            MatrixToImageConfig config  = new MatrixToImageConfig(onColor,offColor);
            bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix,config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  bufferedImage;
    }


    public static String creatRrCode(String contents, int width, int height) {
        String binary = null;
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(
                    contents, BarcodeFormat.QR_CODE, width, height, hints);
            // 1、读取文件转换为字节数组
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            BufferedImage image = toBufferedImage(bitMatrix);
            //转换成png格式的IO流
            ImageIO.write(image, "png", out);
            byte[] bytes = out.toByteArray();

            // 2、将字节数组转为二进制
            BASE64Encoder encoder = new BASE64Encoder();
            binary = encoder.encodeBuffer(bytes).trim();
        } catch (WriterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return binary;
    }

    /**
     * image流数据处理
     *
     * @author ianly
     */
    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) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    // 使用以下main方法可以直接生成以下链接的专属二维码base64地址，赋值到浏览器上即可看到效果
    public static void main(String[] args) {
        String binary = creatRrCode("https://m.woyaoce.cn/special/act/getCode?mid=17657", 200,200);
//        System.out.println(binary);
    }
}

