package com.tofly.common.core.util.Qrqd;

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.tofly.common.core.util.StringUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成图片
 */
public class QRCodeMaker {



    private static final int BLUE = 0xFF3ED547;
    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;
    private static final int RED = 0xFFFF0000;

    private static final int defalutheight=30;

    private static final String IMG_FORMATE = "jpg";



    private static final int LOGO_BORDER_WIDTH = 2;//LOGO边框宽度
    private static final Color LOGO_BORDER_COLOR = Color.WHITE;//LOGO边框颜色

    // TODO:logo file path



    /**
     * 生成二维码图片
     * @param info  二维码信息
     * @param file  文件
     */
    public static void MakeQRCode(String info, File file,int size) throws WriterException, IOException {
        BufferedImage image = toBufferedImg(getBitMatrix(info,size));
        ImageIO.write(image, IMG_FORMATE, file);
    }

    /**
     * 生成二维码图片
     * @param info  二维码信息
     * @param file  文件
     */
    public static void MakeQRCode(String info, File file,int size,String buttonmsg) throws WriterException, IOException {
        BufferedImage image = toTopAndButtonImg(getBitMatrix(info,size),size,buttonmsg,"");
        ImageIO.write(image, IMG_FORMATE, file);
    }



    /**
     * 生成带logo的二维码图片
     * @param info      图片信息
     * @param file       输出图片地址
     * @param logofile  logo图片
     * @throws WriterException
     * @throws IOException
     */
    public static void MakeQrCodeWithLogo(String info, File file,File logofile,String title,int size) throws WriterException, IOException {

        BufferedImage image = toTopAndButtonImg(getBitMatrix(info,size),size,info,title);


        if(logofile!=null){
            addLogo2QrCode(image,logofile);
        }

        ImageIO.write(image, IMG_FORMATE, file);
    }


    /**
     * 生成二维码图片
     * @param info  二维码信息
     * @param out  目的图片地址
     */
    public static void MakeQRCode(String info, String out,int size) throws WriterException, IOException {
        File outFile = new File(out);

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }

        BufferedImage image = toBufferedImg(getBitMatrix(info,size));

        ImageIO.write(image, IMG_FORMATE, outFile);

    }


    /**
     * 生成二维码图片
     * @param info  二维码信息
     * @param filePath  文件名
     */
    public static void MakeQRCode(String info, String filePath,int size,String buttonmsg) throws WriterException, IOException {
        BufferedImage image = toTopAndButtonImg(getBitMatrix(info,size),size,buttonmsg,"");
        File outFile = new File(filePath);

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }
        ImageIO.write(image, IMG_FORMATE, outFile);
    }

    /**
     * 生成带logo的二维码图片
     * @param info      图片信息
     * @param out       输出图片地址
     * @param logoPath  logo图片地址
     * @throws WriterException
     * @throws IOException
     */
    public static void MakeQrCodeWithLogo(String info, String out, String logoPath,String title,int size) throws WriterException, IOException {
        File outFile = new File(out);

        if (!outFile.getParentFile().exists()) {
            outFile.getParentFile().mkdirs();
        }


        BufferedImage image = toTopAndButtonImg(getBitMatrix(info,size),size,info,title);


        if(logoPath!=null){
            addLogo2QrCode(image, new File(logoPath));
        }


        ImageIO.write(image, IMG_FORMATE, outFile);
    }


    /**
     * get bitMatrix from content
     * @param conten    qr_code info
     * @return
     * @throws WriterException
     */
    private static BitMatrix getBitMatrix(String conten,int size) throws WriterException {
        MultiFormatWriter writer = new MultiFormatWriter();

        Map hint = new HashMap();
        hint.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hint.put(EncodeHintType.MARGIN, 1);
        return writer.encode(conten, BarcodeFormat.QR_CODE, size, size, hint);
    }

    private static BufferedImage toBufferedImg(BitMatrix bitMatrix) {
        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) ? BLACK : WHITE);
            }
        }

        return image;
    }

    private static BufferedImage toTopAndButtonImg(BitMatrix bitMatrix,int size,String buttonMsg,String topMsg) {
        //info="编号："+info;
        int button_msg=0,top_msg=0;
        if(!StringUtil.isEmpty(buttonMsg)){
            button_msg=defalutheight;
        }
        if(!StringUtil.isEmpty(topMsg)){
            top_msg=defalutheight;
        }

        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();

        BufferedImage image = new BufferedImage(width,height+button_msg+top_msg, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y+top_msg, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }

        Graphics2D graph = image.createGraphics();

        if(top_msg>0){
            //标题
            BufferedImage textImage2 = FontImage.getImage(topMsg,new Font("宋体",Font.BOLD,jssize(topMsg,size)), size, top_msg);
            int width3 = textImage2.getWidth(null);
            int height3 = textImage2.getHeight(null);
            Image src2 =textImage2;
            graph.drawImage(src2, 0, 0, width3, height3, null);
        }
        if(button_msg>0){
            //结尾
            BufferedImage textImage = FontImage.getImage(buttonMsg,size, button_msg);
            int width2 = textImage.getWidth(null);
            int height2 = textImage.getHeight(null);
            Image src =textImage;
            graph.drawImage(src, 0, size+top_msg, width2, height2, null);
        }

//        if(PROPARAM.PREFIX_MSG!=null && PROPARAM.PREFIX_MSG!=""){
//            BufferedImage textImage3 = FontImage.getImage(PROPARAM.PREFIX_MSG,new Font("宋体",Font.BOLD,jssize(PROPARAM.PREFIX_MSG)), QR_SIZE, 30);
//            int width4 = textImage3.getWidth(null);
//            int height4 = textImage3.getHeight(null);
//            Image src3 =textImage3;
//            graph.drawImage(src3, 0, QR_SIZE+60, width4, height4, null);
//        }

        graph.dispose();
        return image;
    }

    private static void addLogo2QrCode(BufferedImage qrImage, File logoFile) throws IOException {

        if (qrImage == null) {
            throw new RuntimeException("qrpic is null");
        }

        if (!logoFile.exists()) {
            throw new FileNotFoundException("can not found logo file at " + logoFile.getAbsolutePath());
        }

        BufferedImage logo = ImageIO.read(logoFile);

        int logoWidth = logo.getWidth(null);
        int logoHeight = logo.getHeight(null);

        int prefix_msg=0;
//        if(PROPARAM.PREFIX_MSG!=null && PROPARAM.PREFIX_MSG!=""){
//            prefix_msg=30;
//        }

        if(qrImage.getWidth()/5<logoWidth){
            logoWidth=qrImage.getWidth()/5;
            logoHeight=qrImage.getHeight()*logoWidth/qrImage.getWidth();
        }

        // get logo position
        int x = (qrImage.getWidth() - logoWidth) / 2;
        int y = (qrImage.getHeight()-prefix_msg - logoHeight) / 2;

        // draw logo on qr picture
        Graphics2D graphics2D = qrImage.createGraphics();

        graphics2D.drawImage(logo, x, y, logoWidth, logoHeight, null);
        graphics2D.drawRoundRect(x, y, logoWidth, logoHeight, 6, 6);

        graphics2D.setStroke(new BasicStroke(LOGO_BORDER_WIDTH));
        graphics2D.setColor(LOGO_BORDER_COLOR);
        graphics2D.drawRect(x, y, logoWidth, logoHeight);

        graphics2D.dispose();
    }

    private static int jssize(String context,int size){
        int length = context.length();
        return Math.min(size/length-1,defalutheight);
    }

}
