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)
    {
        String barCode = getBarCode(kylinOrderExpress.getMailno(), 90, 13);

        String qrCode = getQRCode(kylinOrderExpress.getTwoDimensionCode(), 25, 25);

        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)
                ;
        Html2Image html2Image = Html2Image.fromHtml(replace3);

        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");

        html2Image.getImageRenderer().saveImage(imgPath);

        return imgPath;
    }

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

    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" +
                "<!-- 顺丰快递面单打印，尺寸：100mm*150mm模版 -->\n" +
                "<div\n" +
                "        style=\"width: 98mm;\n" +
                "\t\t\theight: 150mm;\n" +
                "\t\t\tpadding-top: 5mm;\n" +
                "\t\t\tborder: 1px solid #000;\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: 90%; 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: 92mm;\"\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" +
                "    <table\n" +
                "            border=\"1\"\n" +
                "            style=\"margin: 0 auto; border: 1px solid #000; width: 92.5mm; border-collapse:collapse;\"\n" +
                "    >\n" +
                "        <tr>\n" +
                "            <td style=\"font-family: 宋体; font-size: 9pt;\">\n" +
                "                到付22元\n" +
                "            </td>\n" +
                "            <td rowspan=\"3\">\n" +
                "                <img src=\"images/erweima.png\" style=\"width: 25mm; height: 25mm; margin: 1mm\">\n" +
                "            </td>\n" +
                "            <!-- 13\t已验视 -->\n" +
                "            <td\n" +
                "                    rowspan=\"3\"\n" +
                "                    style=\"font-family: 黑体; font-size: 20pt; font-weight: bold; color: #272727b3; writing-mode:vertical-lr;\"\n" +
                "            >\n" +
                "                已验视\n" +
                "            </td>\n" +
                "            <!-- 产品名称\t限时限时KC24字段 -->\n" +
                "            <td\n" +
                "                    rowspan=\"2\"\n" +
                "                    style=\"font-family: 宋体; font-size: 12pt; width: 20mm;\"\n" +
                "            >\n" +
                "                限时\n" +
                "                KC24\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td rowspan=\"2\" style=\"font-family: 黑体; font-size: 22pt; font-weight: bold;\">\n" +
                "                A22\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <td>\n" +
                "                1A\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "    </table>\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: 92mm;\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" +
                "\n" +
                "    <table\n" +
                "            border=\"1\"\n" +
                "            style=\"\n" +
                "\t\t\t\tmargin: 0 auto;\n" +
                "\t\t\t\tborder: 1px solid #000;\n" +
                "\t\t\t\twidth: 92.5mm;\n" +
                "\t\t\t\tfont-family: 宋体;\n" +
                "\t\t\t\tfont-size: 9pt;\n" +
                "\t\t\t\ttext-align: left;\n" +
                "\t\t\t\tborder-collapse:collapse;\"\n" +
                "    >\n" +
                "        <tr>\n" +
                "            <!-- 15\t托寄物 -->\n" +
                "            <td rowspan=\"2\">\n" +
                "                托寄物：演出票\n" +
                "            </td>\n" +
                "            <!-- 16\t增值服务 -->\n" +
                "            <!-- <td>\n" +
                "                增值服务：\n" +
                "            </td> -->\n" +
                "        </tr>\n" +
                "        <!-- 17\t其他信息 -->\n" +
                "        <tr>\n" +
                "            <!-- 17. 1重量 -->\n" +
                "            <!-- 17.2 付款方式、费用等 -->\n" +
                "            <td>\n" +
                "                <div>计费重量：1kg</div>\n" +
                "                <div>实际重量：1kg</div>\n" +
                "                <div>费用合计：22元</div>\n" +
                "                <div>付款方式：到付</div>\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "        <tr>\n" +
                "            <!-- 18\t客户自定义区 -->\n" +
                "            <td>\n" +
                "                票种:\n" +
                "                <br>\n" +
                "                数量:\n" +
                "            </td>\n" +
                "            <!-- 19\t图标区域 -->\n" +
                "            <td>\n" +
                "                <!-- 图标区域 -->\n" +
                "                <!-- 贴纸信息 -->\n" +
                "            </td>\n" +
                "        </tr>\n" +
                "    </table>\n" +
                "\n" +
                "</div>\n" +
                "</body>\n" +
                "\n" +
                "\n" +
                "</html>";
        return html;
    }

}
