package com.ruoyi.common.utils.poi;

import com.alibaba.fastjson.JSON;
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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QRCodeUtil<T> {
    private static final Logger log = LoggerFactory.getLogger(QRCodeUtil.class);

    /**
     * 导出数据列表
     */
    private List<T> list;
    private static XWPFDocument doc;

    //CODE_WIDTH：二维码宽度，单位像素
    private static final int CODE_WIDTH = 400;
    //CODE_HEIGHT：二维码高度，单位像素
    private static final int CODE_HEIGHT = 400;
    //FONT_WIDTH：字体大小
    private static final int FONT_WIDTH = 16;
    //FRONT_COLOR：二维码前景色，0x000000 表示黑色
    private static final int FRONT_COLOR = 0x000000;
    //BACKGROUND_COLOR：二维码背景色，0xFFFFFF 表示白色
    //演示用 16 进制表示，和前端页面 CSS 的取色是一样的，注意前后景颜色应该对比明显，如常见的黑白
    private static final int BACKGROUND_COLOR = 0xFFFFFF;

    /**
     * 实体对象
     */
    public Class<T> clazz;


    public QRCodeUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    private void init(List<T> list, String title) {
        if (CollectionUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        this.list = list;
        doc = new XWPFDocument();
    }

    public void exportQRCode(HttpServletResponse response, List<T> list) {
        exportQRCode(response, list, StringUtils.EMPTY);
    }

    public void exportQRCode(HttpServletResponse response, List<T> list, String title) {
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setCharacterEncoding("utf-8");
        this.init(list, title);
        exportQRCode(response);
    }

    public void exportQRCode(HttpServletResponse response) {
        try {
            writeDoc();
            doc.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("导出Word异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(doc);
        }
    }

    public static void createCodeToFile(String content, File codeImgFileSaveDir, String fileName) {
        try {
            if (StringUtils.isBlank(content) || StringUtils.isBlank(fileName)) {
                return;
            }
            content = content.trim();
            if (codeImgFileSaveDir == null || codeImgFileSaveDir.isFile()) {
                //二维码图片存在目录为空，默认放在桌面...
                codeImgFileSaveDir = new File(RuoYiConfig.getQRCodePath());
            }
            if (!codeImgFileSaveDir.exists()) {
                //二维码图片存在目录不存在，开始创建...
                codeImgFileSaveDir.mkdirs();
            }

            //核心代码-生成二维码
            BufferedImage bufferedImage = getBufferedImage(content);

            File codeImgFile = new File(codeImgFileSaveDir, fileName);
            ImageIO.write(bufferedImage, "png", codeImgFile);

            log.info("二维码图片生成成功：" + codeImgFile.getPath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createCodeToStream(String content, ByteArrayOutputStream baos,String text) {
        try {
            if (StringUtils.isBlank(content)) {
                return;
            }
            content = content.trim();
            //核心代码-生成二维码
            BufferedImage qrCodeImage = getBufferedImage(content);


            // 添加底部文字
            BufferedImage combinedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT + 30, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = combinedImage.createGraphics();
            g.setColor(Color.WHITE); // 设置背景颜色为白色
            g.fillRect(0, 0, CODE_WIDTH, CODE_HEIGHT + 30); // 填充背景颜色
            g.drawImage(qrCodeImage, 0, 0, null);
            g.setColor(Color.BLACK); // 设置文字颜色为黑色
            g.setFont(new Font("微软雅黑", Font.PLAIN, FONT_WIDTH));
            int textWidth = g.getFontMetrics().stringWidth(text);
            int textX = (CODE_WIDTH - textWidth) / 2;
            g.drawString(text, textX, CODE_HEIGHT + 20);
            g.dispose();
            ImageIO.write(combinedImage, "png", baos);

            log.info("二维码图片生成到输出流成功...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Font loadFont(String fontFilePath, int fontSize) throws IOException, FontFormatException {
        return Font.createFont(Font.TRUETYPE_FONT, new File(fontFilePath)).deriveFont(Font.PLAIN, fontSize);
    }

    //核心代码-生成二维码
    private static BufferedImage getBufferedImage(String content) throws WriterException {

        //com.google.zxing.EncodeHintType：编码提示类型,枚举类型
        Map<EncodeHintType, Object> hints = new HashMap<>();

        //EncodeHintType.CHARACTER_SET：设置字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        //EncodeHintType.ERROR_CORRECTION：设置误差校正
        //ErrorCorrectionLevel：误差校正等级，L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
        //不设置时，默认为 L 等级，等级不一样，生成的图案不同，但扫描的结果是一样的
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        //EncodeHintType.MARGIN：设置二维码边距，单位像素，值越小，二维码距离四周越近
        hints.put(EncodeHintType.MARGIN, 1);

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
        BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
        for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }
        return bufferedImage;
    }


    private void writeDoc() {
        XWPFParagraph paragraph = doc.createParagraph();
        list.forEach(item -> {
            try {
                log.info("==================================================" + JSON.toJSONString(item));
                //务必重写类的toString方法
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                createCodeToStream(JSON.toJSONString(item), baos,item.toString());
                InputStream is = new ByteArrayInputStream(baos.toByteArray());
                paragraph.createRun().addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, "image.jpg", Units.toEMU(200), Units.toEMU(200));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

}
