package com.ssm.core.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ssm.manage.entity.SmsException;
import com.ssm.manage.response.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;

@Slf4j
public class QRCodeUtil {
    /**
     * 字符编码
     */
    private static final String CHASET = "UTF-8";
    /**
     * 图片格式
     */
    private static final String FORMAT_NAME = "JPG";
    /**
     * 二维码大小
     */
    private static final int QRCODE_SIZE = 300;
    /**
     * 宽度
     */
    private static final int WIDTH = 60;
    /**
     * 高度
     */
    private static final int HEIGHT = 60;
    /**
     * 斜线分隔符
     */
    private static final String OBLIQUE_LINE = File.separator;
    /**
     * 图片格式 .JPG
     */
    private static final String SPOT_FORMAT_NAME = ".JPG";


    /**
     * 生成二维码
     *
     * @param content      源内容
     * @param logoPath     生成二维码保存的路径
     * @param needCompress 是否要压缩
     * @return 返回一张二维码图片
     * @throws Exception
     */
    private static BufferedImage createImage(String content, String logoPath, boolean needCompress, boolean isInsertLogo) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHASET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
        //去除白边
        int[] rec = bitMatrix.getEnclosingRectangle();
        int resWidth = rec[2] + 1;
        int resHeight = rec[3] + 1;
        BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
        resMatrix.clear();
        for (int i = 0; i < resWidth; i++) {
            for (int j = 0; j < resHeight; j++) {
                if (bitMatrix.get(i + rec[0], j + rec[1])) {
                    resMatrix.set(i, j);
                }
            }
        }
        //绘制二维码
        int width = bitMatrix.getWidth();
        int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || logoPath == "")
            return image;
        // 插入图片
        if (isInsertLogo)
            QRCodeUtil.insertImage(image, logoPath, needCompress);
        // 返回二维码图片
        return image;
    }

    /**
     * 将二维码中插入图片
     *
     * @param source       二维码
     * @param logoPath     logo图片
     * @param needCompress 是否压缩图片（logo图片宽高超过60需执行压缩）
     * @throws Exception
     */
    private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
        File file = new File(logoPath);
        // 判断文件是否存在
        if (!file.exists()) {
            System.err.println(logoPath + "该文件不存在！");
        }
        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        // 压缩Logo图片
        if (needCompress) {
            if (width > WIDTH)
                width = WIDTH;
            if (height > HEIGHT)
                height = HEIGHT;
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            // 获取画笔工具对象
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null);// 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入logo
        // 获取画笔根据
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - width) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 从二维码中解析数据
     *
     * @param file 二维码文件
     * @return 返回解析完二维码的数据
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null)
            return null;
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHASET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        //返回解析结果
        return resultStr;
    }

    /**
     * 生成带logo二维码，并保存到磁盘
     *
     * @param content      链接或者内容
     * @param logoPath     logo图片
     * @param fileName     文件名
     * @param savePath     保存二维码图片的文件路径
     * @param needCompress 是否压缩logo
     * @param isInsertLogo 是否插入logo
     * @throws Exception
     */
    public static String encode(String content, String logoPath, String fileName, String savePath, boolean needCompress, boolean isInsertLogo)
            throws Exception {
        //以时间为文件名
        if (StringUtils.isEmpty(fileName)) {
            throw new SmsException(ResponseCode.PARAMETER_NOT_EXIST_S, "文件名");
        }
        if (StringUtils.isEmpty(savePath)) {
            //获取系统路径  E:\IdeaProjects\sys3\out\artifacts\sys3
            throw new SmsException(ResponseCode.PARAMETER_NOT_EXIST_S, "存放路径");
        }
        String mkdirs = mkdirs(savePath) +OBLIQUE_LINE + fileName + SPOT_FORMAT_NAME;
        savePath = savePath + OBLIQUE_LINE + mkdirs;
//        System.err.println(savePath);
        BufferedImage image = createImage(content, logoPath, needCompress, isInsertLogo);
        if (image == null)
            return null;
        ImageIO.write(image, FORMAT_NAME, new File(savePath));
        return mkdirs;
    }

    /**
     *
     * @param content
     * @param logoPath
     * @param needCompress
     * @param isInsertLogo
     * @return
     * @throws Exception
     */
    public static byte[] encode(String content, String logoPath, boolean needCompress, boolean isInsertLogo)
            throws Exception {
        BufferedImage image = createImage(content, logoPath, needCompress, isInsertLogo);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] bytes = new byte[0];
        try {
            ImageIO.write(image, "png", output);
            bytes = output.toByteArray();
        }catch (Exception e){
            log.error("二维码生成失败");
            return bytes;
        }finally {
            output.close();
        }
        return bytes;
    }

    /**
     * 判断文件夹是否存在，不存在时会自动创建多层目录
     *
     * @param destPath 文件路径
     */
    private static String mkdirs(String destPath) {
        // 根据日期格式生成文件夹
        String dateDir = new SimpleDateFormat("yyyyMM").format(new Date());
        String dirPath = "img"+OBLIQUE_LINE+"QRcode" + OBLIQUE_LINE + dateDir;
        String localPath = destPath + OBLIQUE_LINE + dirPath;
        File dirFile = new File(localPath);
        if (!dirFile.exists())
            dirFile.mkdirs();
        return dirPath;
    }

    /**
     * 生成不带logo二维码，并保存到磁盘
     * @param content  链接或者内容
     * @param savePath 保存二维码图片的文件路径
     * @throws Exception
     */
    public static String encode(String content, String fileName, String savePath)
            throws Exception {
        return encode(content, null, fileName, savePath, false, false);
    }
}
