package com.liquidnet.client.admin.zhengzai.admin.service.impl.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.liquidnet.service.kylin.entity.KylinOrderExpress;
import com.liquidnet.service.kylin.entity.KylinOrderTickets;
import gui.ava.html.Html2Image;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.PrintQuality;
import javax.servlet.ServletOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 二维码 条形码 html转img
 * </p>
 *
 * @author jiangxiulong
 * @since 2021-07-15 6:57 下午
 */
@Component
public class CodeUtil {

    private static final Logger logger = LoggerFactory.getLogger(CodeUtil.class);

//    public static String pathName = "/data/images/tmphtml/";
    public static String pathName = "/Users/jiangxiulong/Desktop/tmphtml/";

    public static String getQRCode(String content, int width, int height) {
        if (!StringUtils.isEmpty(content)) {
            ServletOutputStream stream = null;

            HashMap<EncodeHintType, Comparable> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 0);

            try {
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, width, height, hints);

                BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
//                ImageIO.write(bufferedImage, "png", os);

                String htmlPath = pathName.concat("qrcode/QRCode.png");
                ImageIO.write(bufferedImage, "png", new File(htmlPath));
                return htmlPath;

//                BASE64Encoder encoder = new BASE64Encoder();
//                String resultImage = new String("data:image/png;base64," + encoder.encode(os.toByteArray()));
//
//                return resultImage;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    try {
                        stream.flush();
                        stream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public static String getBarCode(String content, 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, 0);

            int realWidth = getBarCodeNoPaddingWidth(width, content, width);

            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.CODE_128, realWidth, height, hints);

            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
//            ImageIO.write(bufferedImage, "png", os);

            String htmlPath = pathName.concat("qrcode/barCode.png");
            ImageIO.write(bufferedImage, "png", new File(htmlPath));
            return htmlPath;

//            BASE64Encoder encoder = new BASE64Encoder();
//            String resultImage = new String("data:image/png;base64," + encoder.encode(os.toByteArray()));

//            return resultImage;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 打印图片
     *
     * @param fileName
     * @param count
     */
    public static void drawImage(String fileName, int count) {
        FileInputStream fin = null;
        try {
            DocFlavor dof = null;
            if (fileName.endsWith(".gif")) {
                dof = DocFlavor.INPUT_STREAM.GIF;
            } else if (fileName.endsWith(".jpg")) {
                dof = DocFlavor.INPUT_STREAM.JPEG;
            } else if (fileName.endsWith(".png")) {
                dof = DocFlavor.INPUT_STREAM.PNG;
            }

            PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
            if (ps == null) {
                logger.error("ERROR-01: no default print service");
            }
            logger.error("Printer: " + ps.getName());

            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            pras.add(OrientationRequested.PORTRAIT);
            pras.add(new Copies(count));
            pras.add(PrintQuality.HIGH);

            DocAttributeSet das = new HashDocAttributeSet();
            // 设置打印纸张的大小（以毫米为单位）
            das.add(new MediaPrintableArea(0, 0, 210, 296, MediaPrintableArea.MM));

            fin = new FileInputStream(fileName);

            Doc doc = new SimpleDoc(fin, dof, das);

            DocPrintJob job = ps.createPrintJob();

            job.print(doc, pras);
            fin.close();
            logger.info("打印成功！文件：" + fileName + "数量为：" + count);
        } catch (IOException ie) {
            ie.printStackTrace();
        } catch (PrintException pe) {
            pe.printStackTrace();
        } finally {
            IOUtils.closeQuietly(fin);
        }
    }

    public static int getBarCodeNoPaddingWidth(int expectWidth, String contents, int maxWidth) {
        boolean[] code = new Code128Writer().encode(contents);

        int inputWidth = code.length;

        double outputWidth = (double) Math.max(expectWidth, inputWidth);
        double multiple = outputWidth / inputWidth;

        //优先取大的
        int returnVal = 0;
        int ceil = (int) Math.ceil(multiple);
        if (inputWidth * ceil <= maxWidth) {
            returnVal = inputWidth * ceil;
        } else {
            int floor = (int) Math.floor(multiple);
            returnVal = inputWidth * floor;
        }

        return returnVal;
    }

    public static String html2img(KylinOrderExpress kylinOrderExpress,String jContact, String jAddress, String jTel, KylinOrderTickets orderInfo)
    {
        long s = System.currentTimeMillis();
        String barCode = getBarCode(kylinOrderExpress.getMailno(), 90, 13);
        logger.debug("#barCode耗时:{}ms", System.currentTimeMillis() - s);

        String qrCode = getQRCode(kylinOrderExpress.getTwoDimensionCode(), 25, 25);
        logger.debug("#qrCode耗时:{}ms", System.currentTimeMillis() - s);


        String html = tmpHtml();

        // 码图
        String replace1 = html.replace("images/yiweima.png", barCode).replace("images/erweima.png", qrCode);
        // 收 寄图
        String replace2 = replace1.replace("images/iconJi.png", pathName.concat("images/iconJi.png"))
                .replace("images/iconShou.png", pathName.concat("images/iconShou.png"));
        String replace3 = replace2.replace("SF1010874393776", kylinOrderExpress.getMailno())
                .replace("755W-BA-0123456789", kylinOrderExpress.getDestRouteLabel())

                .replace("收货姓名", orderInfo.getExpressContacts())
                .replace("18510988888", orderInfo.getExpressPhone())
                .replace("收货地址北京市朝阳区摩登天空测试地址", orderInfo.getExpressAddress())

                .replace("22元", kylinOrderExpress.getFreightPrice().toString().concat("元"))

                .replace("KC24", kylinOrderExpress.getProName())
                .replace("A22", kylinOrderExpress.getCargoTypeCode())
                .replace("1A", kylinOrderExpress.getExpressTypeCode())

                .replace("寄件人姓名", jContact)
                .replace("18510989999", jTel)
                .replace("寄件地址北京市朝阳区摩登天空测试地址", jAddress)
                ;
        logger.debug("#replace1耗时:{}ms", System.currentTimeMillis() - s);
        Html2Image html2Image = Html2Image.fromHtml(replace3);
        logger.debug("#fromHtml耗时:{}ms", System.currentTimeMillis() - s);

        String imgPathName = pathName.concat("faceImg");
        File fatherFile = new File(imgPathName);
        try {
            if (!fatherFile.exists()) {
                fatherFile.mkdir();
            } else {
                fatherFile.delete();
                fatherFile.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String imgPath = imgPathName.concat("/").concat(kylinOrderExpress.getMailno()).concat(".png");
        logger.debug("#mkdir耗时:{}ms", System.currentTimeMillis() - s);

        html2Image.getImageRenderer().saveImage(imgPath);
        logger.debug("#saveImage耗时:{}ms", System.currentTimeMillis() - s);

        return imgPath;
    }

    public static void main(String[] args) {
        html2imgTest();
        // 打印图片
//        drawImage(imgPath, 1);
    }

    public static void html2imgTest()
    {
        Html2Image html2Image = Html2Image.fromFile(new File("/Users/jiangxiulong/Desktop/shunfeng-div.html"));


        html2Image.getImageRenderer().saveImage("/Users/jiangxiulong/Desktop/testttt.png");

    }

    public static String tmpHtml()
    {
        String html = "<!DOCTYPE html>\n" +
                "<html lang=\"en\" style=\"width: 100mm;\">\n" +
                "<head>\n" +
                "    <meta charset=\"utf-8\">\n" +
                "    <meta name=\"renderer\" content=\"webkit\">\n" +
                "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
                "    <meta http-equiv=\"Cache-Control\" content=\"no-transform\">\n" +
                "    <meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\" />\n" +
                "    <meta content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0\" name=\"viewport\">\n" +
                "    <meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />\n" +
                "    <meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />\n" +
                "    <meta name=\"format-detection\" content=\"address=no\" />\n" +
                "    <meta name=\"keywords\" content=\"\">\n" +
                "    <meta name=\"description\" content=\"\">\n" +
                "</head>\n" +
                "<body style=\"margin: 0;\n" +
                "    padding: 0;\">\n" +
                "<!-- 顺丰快递面单打印，尺寸：76mm*130mm模版 -->\n" +
                "<div\n" +
                "        style=\"width: 98mm;\n" +
                "\t\t\theight: 150mm;\n" +
                "\t\t\tpadding-top: 5mm;\n" +
                "\t\t\ttext-align: center;\"\n" +
                ">\n" +
                "    <!-- 1. 运单打印系统来源及时间等 -->\n" +
                "    <div\n" +
                "            style=\"width: 100%;\n" +
                "\t\t\t\tfont-family: 宋体;\n" +
                "\t\t\t\tfont-size: 4pt;\"\n" +
                "    >\n" +
                "        <!-- 1.1 打印系统来源(太长放不下了，所以去掉了) -->\n" +
                "        <!-- <div class=\"source\">\n" +
                "            SCP顺丰云打印\n" +
                "        </div> -->\n" +
                "        <!-- 1.2 打印次数/时间 -->\n" +
                "        <!-- <div\n" +
                "            style=\"width: 80%;\n" +
                "                font-family: 宋体;\n" +
                "                font-size: 4pt;\n" +
                "                display: flex;\n" +
                "                flex-direction: row;\n" +
                "                justify-content: center;\n" +
                "                align-items: flex-end;\"\n" +
                "        >\n" +
                "            第一次打印 2020-05-05 12:00 第8/10个\n" +
                "        </div> -->\n" +
                "        <!-- 3  时效类型 -->\n" +
                "        <div\n" +
                "            style=\"font-family: 黑体;\n" +
                "\t\t\t\tfont-size: 26px;\n" +
                "\t\t\t\tfont-weight: bolder;\n" +
                "\t\t\t\twidth: 100%;\n" +
                "\t\t\t\ttext-align: right;\n" +
                "\t\t\t\tmargin-right: 3mm;\"\n" +
                "        >\n" +
                "            <!-- 3.1 特快即日、特快A、特快、标快、标快陆运、特惠、电商标快 -->\n" +
                "            特快\n" +
                "        </div>\n" +
                "    </div>\n" +
                "\n" +
                "\n" +
                "    <!-- 2. 条码区 -->\n" +
                "    <div>\n" +
                "        <!-- 2.1 条码 -->\n" +
                "        <div>\n" +
                "            <img src=\"images/yiweima.png\" style=\"width: 70mm; height: 13mm; margin: 2mm 5mm;\">\n" +
                "        </div>\n" +
                "        <!-- 2.2 子母件单号、汉字、件数标识、 -->\n" +
                "        <div\n" +
                "                style=\"font-family: 黑体;\n" +
                "\t\t\t\t\tfont-size: 10pt;\n" +
                "\t\t\t\t\tdisplay: flex;\n" +
                "\t\t\t\t\tflex-direction: column;\"\n" +
                "        >\n" +
                "            <div>\n" +
                "                运单号：SF1010874393776\n" +
                "            </div>\n" +
                "            <!-- <div>\n" +
                "                母单号：SF1 010 874 393 776\n" +
                "            </div> -->\n" +
                "        </div>\n" +
                "    </div>\n" +
                "\n" +
                "    <!-- 4\t目的地 -->\n" +
                "    <!-- 4.1 路由信息  暂无-->\n" +
                "    <div\n" +
                "            style=\"margin: 0 auto;\n" +
                "\t\t\t\tborder: 1px solid #000;\n" +
                "\t\t\t\tborder-bottom: none;\n" +
                "\t\t\t\twidth: 96mm;\"\n" +
                "    >\n" +
                "        <!-- 2.3 运单号 -->\n" +
                "        <div\n" +
                "                style=\"font-size: 22pt; font-weight: bold;\"\n" +
                "        >\n" +
                "            755W-BA-0123456789\n" +
                "        </div>\n" +
                "        <!-- 5\t收方信息 -->\n" +
                "        <div style=\"text-align: left;\">\n" +
                "            <!-- 5.1 收 -->\n" +
                "            <div style=\"display: inline-block; width: 9mm; text-align: center;\">\n" +
                "                <img src=\"images/iconShou.png\" style=\"width:7mm; height:7mm\">\n" +
                "            </div>\n" +
                "            <!-- 5.2 收件人姓名/电话/地址 -->\n" +
                "            <div\n" +
                "                    style=\"display: inline-block; width: 62mm; font-family: 宋体; font-size: 9pt; text-align: left;\"\n" +
                "            >\n" +
                "                <div>\n" +
                "                    <span>收货姓名</span>\n" +
                "                    <span>18510988888</span>\n" +
                "                </div>\n" +
                "                <div>\n" +
                "                    <span>收货地址北京市朝阳区摩登天空测试地址</span>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "            <!-- 5.3 单元区域编码 暂无-->\n" +
                "            <!-- 6\t代收货款 -->\n" +
                "            <div style=\"display: inline-block;\">\n" +
                "                <!-- 6.1 COD -->\n" +
                "                <img src=\"images/COD.jpg\" style=\"width: 17mm; height:9mm\">\n" +
                "            </div>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "\n" +
                "    <div style=\"border: 1px solid #000;  \n" +
                "        margin: 0 auto; width: 96mm; height: 28mm;\"\n" +
                "    >\n" +
                "        <div style=\"display: inline-block;\">\n" +
                "            <div style=\"width: 33mm; height: 6mm; border-bottom: 1px solid #000;\">\n" +
                "                到付22元\n" +
                "            </div>\n" +
                "            <div style=\"width: 33mm; height: 22mm; font-family: 黑体; font-size: 36pt; font-weight: bolder;\">\n" +
                "                A22\n" +
                "            </div>\n" +
                "        </div>\n" +
                "        <div style=\"display: inline-block; width: 33mm; height: 28mm;border-left: 1px solid #000; border-right: 1px solid #000;\">\n" +
                "            <img src=\"images/erweima.png\" style=\"width: 25mm; height: 25mm; margin: 1mm\">\n" +
                "        </div>\n" +
                "        <div style=\"display: inline-block; width: 10mm; height: 28mm; font-family: 黑体; font-size: 20pt; font-weight: bold; color: #272727b3; border-right: 1px solid #000; word-wrap: break-word; word-break: break-all; overflow: hidden;\">\n" +
                "                <div>已</div>\n" +
                "                <div>验</div>\n" +
                "                <div>视</div>\n" +
                "        </div>\n" +
                "        <div style=\"display: inline-block;\">\n" +
                "            <div style=\"height: 8mm; border-bottom: 1px solid #000;\">\n" +
                "                <div>限时</div>\n" +
                "                <div>KC24</div>\n" +
                "            </div>\n" +
                "            <div style=\"height: 17mm; font-family: 黑体; font-size: 30pt; font-weight: bolder;\">\n" +
                "                1A\n" +
                "            </div>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "\n" +
                "    <!-- 14\t寄方信息 -->\n" +
                "    <div\n" +
                "            style=\"border-left: 1px solid #000;\n" +
                "\t\t\t\tborder-right: 1px solid #000;\n" +
                "\t\t\t\twidth: 96mm;\n" +
                "\t\t\t\tmargin: 0 auto;\n" +
                "\t\t\t\ttext-align: left;\"\n" +
                "    >\n" +
                "        <div\n" +
                "                style=\"display: inline-block; width: 9mm; text-align: center;\"\n" +
                "        >\n" +
                "            <img src=\"images/iconJi.png\" style=\"width:7mm; height:7mm\">\n" +
                "        </div>\n" +
                "        <!-- 14.1 寄件人人姓名/电话/地址 -->\n" +
                "        <div\n" +
                "                style=\"display: inline-block; width: 62mm; font-family: 宋体; font-size: 9pt; text-align: left;\"\n" +
                "        >\n" +
                "            <div>\n" +
                "                <span>寄件人姓名</span>\n" +
                "                <span>18510989999</span>\n" +
                "            </div>\n" +
                "            <div>\n" +
                "                <span>寄件地址北京市朝阳区摩登天空测试地址</span>\n" +
                "            </div>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "    <div style=\"border: 1px solid #000;  \n" +
                "        margin: 0 auto; width: 96mm; height: 24mm; text-align: left\"\n" +
                "    >\n" +
                "        <div style=\"display: inline-block; width: 48mm; height: 24mm;\">\n" +
                "            托寄物：演出票\n" +
                "        </div>\n" +
                "        <div style=\"display: inline-block; width: 46mm; height: 24mm; border-left: 1px solid #000;\">\n" +
                "            <div>计费重量：1kg</div>\n" +
                "            <div>实际重量：1kg</div>\n" +
                "            <div>费用合计：22元</div>\n" +
                "            <div>付款方式：到付</div>\n" +
                "        </div>\n" +
                "    </div>\n" +
                "    <div style=\"border: 1px solid #000;  \n" +
                "        margin: 0 auto; width: 96mm; height: 25mm; text-align: left\"\n" +
                "    >\n" +
                "        票种：单日票\n" +
                "        数量：2\n" +
                "    </div>\n" +
                "</body>\n" +
                "\n" +
                "\n" +
                "</html>";
        return html;
    }

}
