<template>
    <lj-win-common :title="title" :show-back="true" ref="baseWin">
        <template slot="header_right">
            <mu-menu placement="bottom-end" :open.sync="openTitle">
                <mu-button icon>
                    <i class="iconfont icon-more"></i>
                </mu-button>
                <mu-list slot="content">
                    <mu-list-item button @click="downloadPdf">
                        <mu-list-item-title>导出pdf</mu-list-item-title>
                    </mu-list-item>
                    <mu-list-item button @click="downloadPic">
                        <mu-list-item-title>导出图片</mu-list-item-title>
                    </mu-list-item>
                </mu-list>
            </mu-menu>
        </template>
        <div slot="body" ref="ljbody" class="ljbody">
            <div ref="printTemplate">
                <div class="wrapper" id="print-wrapper">
                    <div class="print-content" id="print-content"></div>
                </div>
            </div>
        </div>
    </lj-win-common>
</template>

<script>
import LjWinCommon from "components/lj-win-common";
import { jsPDF } from "jspdf";
import { hiprint,hiPrintPlugin } from 'vue-plugin-hiprint'
import html2canvas from 'html2canvas'
import LjImg from "components/lj-img"
export default {
    name: "hiprint-template",
    components: {
        LjWinCommon,
        LjImg
    },
    data() {
        return {
            template: null,
            queryParams: {},
            openTitle: false
        }
    },
    created(){
        let pageParam = $lj.getPageParam();
        if (pageParam) {
            this.template = pageParam.template;
            this.queryParams = pageParam.queryParams;
        }
    },
    mounted(){
        this.getTemplateData()
    },
    computed:{

    },
    methods: {
        getTemplateData() {
            let self = this;
            $lj.postLJRequest("GetL1APPCommonPrintBillData", {
                token: $lj.getStorage("token"),
                bill_dsname: "web_saletask_index",
                mx_dsname: "web_saletaskmx",
                fj_billtype: 201,
                queryparams: this.queryParams
            }, (ret) => {
                let data = {};
                if(ret.bill) {
                    data = ret.bill[0];
                }

                if(ret.billMx) {

                    self.refreshImg(ret.billMx).then((val) => {
                        data.table = ret.billMx;

                        self.templateInit(data);
                    })
                }
            })
        },
        async refreshImg(mxlist) {
            if(mxlist.length <= 0) return;

            async function GetCacheFile(md5) {
                return new Promise((resolve,reject) => {
                    $lj.getCacheDir(function (cacheDir) {
                        let path = cacheDir + "/" + md5;
                        var fs = $lj.getFileHelperModule();
                        console.warn(path);
                        fs.exist({
                            path: path
                        }, function (ret, err) {
                            if (ret.exist) {
                                resolve(path);
                            } else {
                                $lj.postLJRequest("GetCacheFile", {filemd5: md5}, function (ret) {
                                    var cacheDir = $lj.constant.cacheDir + "/";
                                    let newPath = cacheDir + "/" + md5;
                                    if (ret.filedata !== md5) {
                                        let oldPath = cacheDir + "/" + ret.filedata;
                                        console.error(`!!!!!!!!  lj-img:renaming ${ret.filedata} to ${md5}  !!!`);
                                        fs.rename({
                                            oldPath: oldPath,
                                            newPath: newPath
                                        }, function (ret, err) {
                                            if (ret.status) {
                                                resolve(newPath);
                                            } else {
                                                console.error("图片重命名: " + JSON.stringify(err));
                                            }
                                        });
                                    } else {
                                        resolve(newPath);
                                    }
                                });
                            }
                        });
                    });
                });
            }

            for(let item of mxlist) {
                if(!item.filemd5) continue;
                const url = await GetCacheFile(item.filemd5);
                item.mtrl_pic = url;
            }
        },
        templateInit(data) {
            // 引入后使用示例
            hiPrintPlugin.disAutoConnect();
            hiprint.init();
            // 下列方法都是没有拖拽设计页面的, 相当于代码模式, 使用代码设计页面
            // 想要实现拖拽设计页面,请往下看 '自定义设计'
            let options = {
                // template: {"panels":[{"index":0,"height":148,"width":210,"paperHeader":-1.5,"paperFooter":380,"printElements":[{"options":{"left":540,"top":10.5,"height":35,"width":33,"borderColor":"#f20000"},"printElementType":{"title":"椭圆","type":"oval"}},{"options":{"left":454.5,"top":15,"height":18,"width":74,"title":"8888888","fontSize":18,"fontWeight":"600","color":"#2935e3","textAlign":"center","lineHeight":16},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":424.5,"top":15,"height":19,"width":24,"title":"NO","fontSize":18,"color":"#2935e3","textAlign":"center","lineHeight":15},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":190.5,"top":15,"height":21,"width":226,"title":"上海增值税普通发票","fontSize":18,"fontWeight":"600","letterSpacing":2.5,"color":"#cc5a5a","textAlign":"center","lineHeight":18},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":244.5,"top":19.5,"height":51,"width":112,"borderColor":"#eb1111","borderWidth":"2"},"printElementType":{"title":"椭圆","type":"oval"}},{"options":{"left":90,"top":19.5,"height":21,"width":96,"title":"8888888","fontSize":19,"letterSpacing":1,"color":"#2935e3","textAlign":"center","lineHeight":18},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":19.5,"top":19.5,"height":61,"width":65,"title":"031001800204","textType":"qrcode"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":250.5,"top":25.5,"height":42,"width":104,"borderColor":"#f00505"},"printElementType":{"title":"椭圆","type":"oval"}},{"options":{"left":190.5,"top":45,"height":10,"width":228,"borderColor":"#b5a8a8"},"printElementType":{"title":"横线","type":"hline"}},{"options":{"left":190.5,"top":49.5,"height":10,"width":228,"borderColor":"#baafaf"},"printElementType":{"title":"横线","type":"hline"}},{"options":{"left":244.5,"top":55.5,"height":22,"width":120,"title":"发票联","fontSize":18,"fontWeight":"600","letterSpacing":8,"color":"#cc5a5a","textAlign":"center","lineHeight":18},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":510,"top":55.5,"height":13,"width":69,"title":"2019年05月09日","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":445.5,"top":55.5,"height":15,"width":57,"title":"开票日期：","color":"#cc5a5a","lineHeight":13},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":90,"top":64.5,"height":15,"width":141,"title":"校验码：123456 788942 52344","color":"#2935e3","textAlign":"center","lineHeight":13},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":400,"top":90,"height":60,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":35,"top":90,"height":60,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":420,"top":90,"height":61,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":10.5,"top":90,"height":282,"width":572,"borderColor":"#cc5a5a"},"printElementType":{"title":"矩形","type":"rect"}},{"options":{"left":405,"top":94.5,"height":55,"width":13,"title":"密码区","fontSize":13,"color":"#cc5a5a","lineHeight":18},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":424.5,"top":94.5,"height":50,"width":152,"title":"","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":15,"top":94.5,"height":53,"width":15,"title":"购买方","fontSize":13,"color":"#cc5a5a","lineHeight":18},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":45,"top":100.5,"height":10,"width":348,"title":"名称：北京地铁税务局有限公司","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":45,"top":115.5,"height":10,"width":347,"title":"纳税人识别号：999999999999999999","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":45,"top":130.5,"height":10,"width":347,"title":"地址、电话：18888888888","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":345,"top":150,"height":190,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":409.5,"top":150,"height":190,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":295.5,"top":150,"height":190,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":480,"top":150,"height":190,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":215,"top":150,"height":224,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":520.5,"top":150,"height":190,"width":10,"borderColor":"#cc5a5a"},"printElementType":{"title":"竖线","type":"vline"}},{"options":{"left":10,"top":150,"height":10,"width":574,"borderColor":"#cc5a5a"},"printElementType":{"title":"横线","type":"hline"}},{"options":{"left":300,"top":160.5,"height":10,"width":36,"title":"单位","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":349.5,"top":160.5,"height":11,"width":51,"title":"数量","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":225,"top":160.5,"height":10,"width":62,"title":"规格名称","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":420,"top":160.5,"height":10,"width":53,"title":"单价","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":484.5,"top":160.5,"height":10,"width":32,"title":"税率","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":525,"top":160.5,"height":10,"width":52,"title":"税额","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":19.5,"top":160.5,"height":10,"width":184,"title":"货物或应税劳务、服务名称","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":40.5,"top":175.5,"height":12,"width":120,"title":"*餐饮服务*餐费","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":10.5,"top":340.5,"height":10,"width":574,"borderColor":"#cc5a5a"},"printElementType":{"title":"横线","type":"hline"}},{"options":{"left":225,"top":349.5,"height":14,"width":229,"title":"壹佰贰拾元整","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":460.5,"top":349.5,"height":13,"width":58,"title":"（小写）","fontSize":13,"color":"#cc5a5a"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":520.5,"top":349.5,"height":13,"width":48,"title":"￥100.00","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":15,"top":349.5,"height":14,"width":193,"title":"价税合计（大写）","fontSize":13,"color":"#cc5a5a","textAlign":"center"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":300,"top":385.5,"height":10,"width":39,"title":"开票人：","color":"#cc5a5a"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":190.5,"top":385.5,"height":10,"width":103,"title":"轩大可","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":150,"top":385.5,"height":10,"width":33,"title":"复核：","color":"#cc5a5a"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":345,"top":385.5,"height":10,"width":86,"title":"张天天","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":64.5,"top":385.5,"height":10,"width":78,"title":"轩天天","color":"#2935e3"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":439.5,"top":385.5,"height":10,"width":40,"title":"销售方：","color":"#cc5a5a"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":15,"top":385.5,"height":10,"width":44,"title":"收款人：","color":"#cc5a5a"},"printElementType":{"title":"文本","type":"text"}}],"paperNumberLeft":565.5,"paperNumberTop":394.5,"paperNumberDisabled":true}]},
                template: JSON.parse(this.template.content)
            }
            var hiprintTemplate = new hiprint.PrintTemplate(options);
            var jqObj = hiprintTemplate.getHtml(data);
            var jqObjHTML = jqObj.html(); 
            var hiprintPrintTemplate = document.getElementById('print-content');  
            hiprintPrintTemplate.innerHTML = jqObjHTML;

            /**
             * 因客户目前只使用A4尺寸，先写死
             */
            let scaleBy = $lj.floatDiv(api.winWidth,this.convertMmToPx(210));

            hiprintPrintTemplate.style.transform = `scale(${scaleBy})`;
            hiprintPrintTemplate.style.transformOrigin = `0 0`;
        },
        getpdf(canvas) {
            // this.hiprintTemplate.toPdf({},"导出pdf",{scale:2 });
            // canvas 渲染的是需要下载的元素
            const pdf = new jsPDF("p", "pt", "a4"); // 创建一个 pdf
            const ctx = canvas.getContext("2d");
            const margin = 30; // pdf 每页的边距
            const a4w = 592.28 - 2 * margin, a4h = 841.89 - 2 * margin;
            const imgHeight = Math.floor((a4h * canvas.width) / a4w); // 将 canvas 按 pdf 内容的高度分页，imgHeight 为分页的高度
            let renderedHeight = 0; // 已经添加到 pdf 的高度

            while (renderedHeight < canvas.height) {
                // canvas 没有全部添加到 pdf
                const page = document.createElement("canvas"); // 创建一个新的画布
                // 将 canvas 切割后渲染到新的画布上
                page.width = canvas.width;
                page.height = Math.min(imgHeight, canvas.height - renderedHeight);
                page
                .getContext("2d")
                .putImageData(
                    ctx.getImageData(
                        0,
                        renderedHeight,
                        canvas.width,
                        Math.min(imgHeight, canvas.height - renderedHeight)
                    ),
                    0,
                    0
                );
                // 将新画布生成图片并添加到 pdf 中
                pdf.addImage(
                    page.toDataURL("image/jpeg", 1.0),
                    "JPEG",
                    margin,
                    margin,
                    a4w,
                    Math.min(a4h, (a4w * page.height) / page.width)
                );
                renderedHeight += imgHeight;
                if (renderedHeight < canvas.height)
                // 如果 canvas 没有被全部添加到 pdf，则新增一页空白 pdf
                pdf.addPage();
                page.remove(); // 移除新的画布
            }
            // 保存 pdf
            this.savePdfToDocument(pdf.output("dataurl"))
        },
        savePdfToDocument(dataurl) {
            let self = this;
            var trans = $lj.getBase64TranModule();
            $lj.getCacheDir(function (cacheDir) {
                if (cacheDir) {
                    const pdfName = self.generateRandomImageName('pdf','.pdf');
                    trans.saveFile({
                        base64Str: dataurl.split(',')[1],
                        filePath: cacheDir,
                        fileName: pdfName
                    }, function(ret, err) {
                        if (ret.status) {
                            api.alert({
                                msg:'保存PDF成功'
                            });
                        } else {
                            api.alert({
                                msg:'导出PDF失败'
                            });
                        }
                    });
                }
            });
        },
        downloadPdf() {
            this.openTitle = false;

            api.showProgress({
                title: '努力加载中...',
                text: '请稍等...'
            });

            this.drawCanvas().then((canvas) => {
                this.getpdf(canvas);

                api.hideProgress();
            })
        },
        downloadPic() {
            this.openTitle = false;

            api.showProgress({
                title: '努力加载中...',
                text: '请稍等...'
            });

            this.drawCanvas().then((canvas) => {
                this.convertCanvasToImage(canvas);

                api.hideProgress();
            })
        },
        DPR() {
            if (window.devicePixelRatio && window.devicePixelRatio > 1) {
                return window.devicePixelRatio;
            }
            return 1;
        },
        /**
         *  将传入值转为整数
         */
        parseValue(value) {
            return parseInt(value, 10);
        },
        /**
         * 绘制canvas
         */
        async drawCanvas () {
            const dom = document.getElementById('print-content');  
            // DOM 节点计算后宽高
            // const width = dom.offsetWidth;
            const width = this.convertMmToPx(210)
            // const height = dom.offsetHeight;
            const height = this.convertMmToPx(296)
            // 创建自定义 canvas 元素
            var canvas = document.createElement('canvas');
            // 设定 canvas 元素属性宽高为 DOM 节点宽高 * 像素比
            // canvas.width = width;
            canvas.width = width;
            canvas.height = height;
            // 设定 canvas css宽高为 DOM 节点宽高
            canvas.style.width = `${width}px`;
            canvas.style.height = `${height}px`;

            let scaleBy = $lj.floatDiv(this.convertMmToPx(210),api.winWidth);

            var opts = {
                scale: scaleBy,
                useCORS: true,
                canvas: canvas, 
                width: width, 
                height: height,
                x: 0, //x坐标
                y: 0, //y坐标
            };

            return await html2canvas(dom, opts);
        },
        convertCanvasToImage(canvas) {
            let image = new Image();
            image.src = canvas.toDataURL("image/jpeg",1.0);

            this.saveMediaToAlbum(image.src);

            return image;
        },
        generateRandomImageName(prefix = '', suffix = '.js') {
            const timestamp = Date.now().toString().slice(-10); // 取最后10位时间戳  
            const randomString = Math.random().toString(36).substring(2, 5); // 较短的随机字符串  
            return `${prefix}${timestamp}-${randomString}${suffix}`; 
        },
        convertMmToPx(mm) {
            const mmPerInch = 25.4; // 每英寸的毫米数
            const screenDPI = 96; // 默认屏幕DPI为96
            
            // 计算出1 CSS像素对应的实际毫米数
            const cssPixelToMm = mmPerInch / screenDPI;
            
            // 换算mm到px
            return (mm / cssPixelToMm);
        },
        saveMediaToAlbum(url) {
            let self = this;
            $lj.getCacheDir(function (cacheDir) {
                if (cacheDir) {
                    var trans = api.require('trans');
                    const imgName = self.generateRandomImageName('img','.jpg');
                    trans.saveImage({
                        base64Str: url.split(',')[1],
                        imgPath: cacheDir,
                        imgName: imgName
                    }, function(ret, err) {
                        if (ret.status) {
                            api.saveMediaToAlbum({
                                path: `${cacheDir}/${imgName}`
                            }, function(_res, _err) {
                                if (_res && _res.status) {
                                    api.alert({
                                        msg:'保存图片成功'
                                    });
                                } else {
                                    api.alert({
                                        msg:'保存图片失败'
                                    });
                                }
                            })
                        } else {
                            api.alert({
                                msg:'导出图片失败'
                            });
                        }
                    });
                }
            });
        }
    },
    computed: {
        title() {
            return this.template ? this.template.aliase : "打印模版选择";
        }
    }
}
</script>
<style lang="less">
    .background-color {
        background-color: #FFF !important;
    }
</style>

<style lang="less" scope>
    #hiprint-printTemplate {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    .wrapper {  
        width: 100%; /* 初始宽度 */  
        height: 100%; /* 初始高度 */  
    }  
    
    .content {  
        width: 100%; /* 填充包裹器 */  
        height: 100%; /* 填充包裹器 */  
        transition: transform 0.3s ease; /* 平滑过渡效果 */  
    }
</style>