<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <base th:href="${#request.getContextPath() + '/'} ">
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="assets/fonts/font-awesome/css/font-awesome.css"/>
    <link rel="stylesheet" href="assets/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="assets/layuiadmin/style/admin.css" media="all">

    <script type="text/javascript" src="assets/js/vendor/safety/js/jquery.min.js" ></script>
    <script type="text/javascript" src="assets/js/vendor/safety/js/context.js"></script>
    <script type="text/javascript" src="assets/js/vendor/safety/js/drag.js" ></script>
    <link rel="stylesheet" type="text/css" href="assets/js/vendor/safety/css/context.standalone.css">

    <style type="text/css">
        html,body{margin:0;padding:0;font:14px/1.5em simsun;overflow:auto;}
        #canvas{position:absolute;left:0px;top:0px;z-index:9;border:2px dashed #ccc;padding:1px;background:#fff;margin-top:100px;}
        .transparent{filter:alpha(opacity=50);-moz-opacity:0.5;-khtml-opacity:0.5;opacity:0.5;}
        .box{width:200px;height:100px;cursor:move;position:absolute;top:30px;left:30px;z-index:99;}
        .box .bg{width:100%;height:100%;background-color:orange;}
        .box .coor{width:10px;height:10px;overflow:hidden;cursor:se-resize;position:absolute;right:0;bottom:0;background-color:red;z-index: 100;}
        .box .content{position:absolute;left:50%;top:50%;z-index:99;text-align:center;font:bold 20px/1.5em simsun;color:black;font-size: 20px;transform: translate(-50%,-50%)}
        #debug{position:absolute;right:10px;top:10px;z-index:88;border:1px solid #ccc;width:100px;height:100px;background:#fff;}
        .bgTransparent{
            background-color:transparent !important;
        }
        #toolbar{position:absolute;top:10px;z-index:88;}
    </style>
</head>
<body id="pageArea" class="list">
    <div id="toolbar" style="margin-left:{{ (d.currentWindowWidth - 432) / 2 }}px;width:435px;" >
        <button type="button" class="layui-btn" id="btnAdd" lay-filter="btnAdd">添加区域</button>
        <button type="button" class="layui-btn layui-btn-primary" id="btnLock" lay-filter="btnLock">锁定区域</button>
        <button type="button" class="layui-btn layui-btn-success" id="updateData" lay-filter="btnLock">快速修改</button>
        <button type="button" class="layui-btn layui-btn-danger" lay-submit lay-filter="areaForm">生成预览图</button>
        <textarea id="target" style="opacity: 0;"></textarea>
    </div>
    <div id="canvas" style="margin-left:{{d.marginLeft}}px;width:{{d.picturesTemplateWidth}}px;height:{{d.picturesTemplateHeight}}px;">
        <img id="imgId" height="100%" width="100%"  alt=""/>
    </div>
<script src="assets/layuiadmin/layui/layui.js"></script>
<script src="assets/js/vendor/safety/copy/clipboard.min.js"></script>
<script>
    layui.config({
        base: 'assets/layuiadmin/', //静态资源所在路径
        extend: 'extend/layer.ext.js'
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', "table", 'form', 'laydate', 'laytpl'], function(){
        var $ = layui.$;
        var form = layui.form;
        var table = layui.table;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;
        var picturesTemplateId = top.restAjax.params(window.location.href).picturesTemplateId;
        var picturesTemplateCode = top.restAjax.params(window.location.href).picturesTemplateCode;
        var dataFormData = {};

        function closeBox() {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        }

        /**
         * 监听Curl+S键, 快速生成预览图
         * */
        document.addEventListener('keydown', function(e){
            if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
                e.preventDefault();
                buiddingPicture();
            }
        });

        // 初始化计数器
        var num = 0;
        // 区块锁定标识
        var lock = false;

        // 右键菜单参数
        context.init({
            fadeSpeed: 100,
            filter: function ($obj){},
            above: 'auto',
            preventDoubleContext: true,
            compress: false
        });
        // 调试输出方法
        function debug(msg){
            $("#debug").text(msg);
        }
        // 创建区域
        function createBox(data){
            var dataId = data.picturesTemplateAreaId || '';
            var value = data.templateAreaName || '区域';
            var color = data.templateAreaColor || '';
            var height = data.templateAreaHeight || 0;
            var width = data.templateAreaWidth || 0;
            var pageX = data.templateAreaLeft || 0;
            var pageY = data.templateAreaTop || 0;
            var fontSize = data.templateAreaFontSize || 20;
            var fontColor = data.templateAreaFontColor || "";
            //更新计数器并记录当前计数
            var curNum = num++;
            //创建区域块
            var pos = $("#canvas").position();
            // background-image:url(route/file/download/false/'+ data.picturesModulePhoto +');
            var box = $('<div tabindex="1" id="'+dataId+'" class="box" rel="'+curNum+'" areaName="' + value + '" dataId="'+dataId+'" ><pre class="content" style="font-size:' +fontSize + 'px;color:'+fontColor+';">'+value+'</pre><div class="bg transparent"  style="background-color:'+color+'"></div><div class="coor transparent"></div></div>').css({
                width : width,
                height : height,
                top : pageY > 0 ? pageY : (pos.top > 0 ? 0 : pos.top * -1 + 50),
                left : pageX > 0 ? pageX : (pos.left > 0 ? 0 : pos.left * -1 + 30)
            }).appendTo("#canvas");
            /**
             * 键盘控制位置移动 2021年6月22日16:33:34 由CBC新增
             * */
            $(document).on('keydown', '#' + dataId, function(e){
                if(lock == true){
                    return
                }
                var x = Number($(this).css("left").replace("px",""));
                var y = Number($(this).css("top").replace("px",""));
                var w = $(this).width();
                var h = $(this).height();
                var id = $(this).attr("id");
                var noChange = false;
                // 向左移动
                if (e.keyCode == 37 ){
                    e.preventDefault();
                    x = (x - 1) >= 0 ? x - 1 : 0;
                    if(x == 0) {
                        layer.msg("已到左侧边缘");
                        noChange  = true;
                    }else{
                        $('#'+id).css("left", x + "px");
                        console.log("向左移动1: x坐标:"+ x +"y坐标:"+ y +"宽度:"+ w +"高度:"+ h +"id:"+ id);
                    }
                }
                // 向上移动
                if (e.keyCode == 38 ){
                    e.preventDefault();
                    y = (y - 1) >= 0 ? y - 1 : 0;
                    if(y == 0) {
                        layer.msg("已到顶部边缘");
                        noChange  = true;
                    }else{
                        $('#'+id).css("top", y + "px");
                        console.log("向上移动1: x坐标:"+ x +"y坐标:"+ y +"宽度:"+ w +"高度:"+ h +"id:"+ id);
                    }
                }
                // 向右移动
                if (e.keyCode == 39 ){
                    e.preventDefault();
                    x = (x + 1) >= (dataFormData.picturesTemplateWidth - w ) ? ( dataFormData.picturesTemplateWidth - w + 1) : x + 1;
                    if(x > (dataFormData.picturesTemplateWidth - w)) {
                        layer.msg("已到右侧边缘");
                        noChange  = true;
                    }else{
                        $('#'+id).css("left", x + "px");
                        console.log("向右移动1: x坐标:"+ x +"y坐标:"+ y +"宽度:"+ w +"高度:"+ h +"id:"+ id);
                    }
                }
                // 向下移动
                if (e.keyCode == 40 ){
                    e.preventDefault();
                    y = (y + 1) >= (dataFormData.picturesTemplateHeight - h ) ? (dataFormData.picturesTemplateHeight - h + 1) : y + 1;
                    if(y > (dataFormData.picturesTemplateHeight - h) ) {
                        layer.msg("已到底部边缘");
                        noChange  = true;
                    }else{
                        $('#'+id).css("top", y + "px");
                        console.log("向下移动1: x坐标:"+ x +"y坐标:"+ y +"宽度:"+ w +"高度:"+ h +"id:"+ id);
                    }
                }
                if(!noChange) {
                    var formData = {templateAreaLeft : x , templateAreaTop : y , templateAreaHeight : h , templateAreaWidth : w };
                    top.restAjax.put(top.restAjax.path('api/picturestemplatearea/updatepicturestemplateareapoint/{picturesTemplateAreaId}', [id]), formData, null, function(code, data) {
                    }, function(code, data) {
                    }, function() {
                    }, function() {
                    });
                }
            });

            // 计算文本位置 , 改为通过css控制
            // box.find('.content').css({
            //     marginLeft : box.find('.content').width()/2*-1,
            //     marginTop : box.find('.content').height()/2*-1
            // });
            //创建右键菜单
            context.attach('.box[rel='+curNum+']', [
                {header: '区域操作'},
                {text: '修改区域', action: function(e){
                        e.preventDefault();
                        //当前区域的id
                        var id = $('.box[rel='+curNum+']').attr("id");
                        layer.open({
                            type: 2,
                            title: false,
                            closeBtn: 0,
                            area: ['60%', '90%'],
                            shadeClose: false,
                            anim: 2,
                            content: top.restAjax.path('route/picturestemplatearea/updatepicturestemplatearea?picturesTemplateAreaId={picturesTemplateAreaId}', [id]),
                            end: function() {
                                location.reload();
                            }
                        });
                    }
                },
                {text: '复制区域', action: function(e){
                        e.preventDefault();
                        //当前区域的id
                        var id = $('.box[rel='+curNum+']').attr("id");
                        layer.prompt({title: '输入新区域的字段标识', formType: 3}, function(code, index){
                            if(code) {
                                layer.close(index);
                                top.dialog.msg("复制出一个新的区域", {
                                    time: 0,
                                    btn: ["确定复制", "我再想想"],
                                    shade: 0.3,
                                    yes: function (index) {
                                        top.dialog.close(index);
                                        var layIndex;
                                        top.restAjax.put(top.restAjax.path('api/picturestemplatearea/copypicturestemplatearea/{picturesTemplateAreaId}/{templateAreaSource}', [id, code]), {}, null, function (code, data) {
                                            top.dialog.msg('复制成功', {time: 1000});
                                            location.reload();
                                        }, function (code, data) {
                                            top.dialog.msg(data.msg);
                                        }, function () {
                                            layIndex = top.dialog.msg('正在复制中...', {icon: 16, time: 0, shade: 0.3});
                                        }, function () {
                                            top.dialog.close(layIndex);
                                        });
                                    }
                                });
                            }
                        });
                    },
                },
                {text: '删除区域', action: function(e){
                        e.preventDefault();
                        //当前区域的id
                        var id = $('.box[rel='+curNum+']').attr("id");
                        top.dialog.msg("删除后会影响当前区域的显示", {
                            time: 0,
                            btn: ["确定要删除", "我再想想"],
                            shade: 0.3,
                            yes: function (index) {
                                top.dialog.close(index);
                                var layIndex;
                                top.restAjax.delete(top.restAjax.path('api/picturestemplatearea/removepicturestemplatearea/{ids}', [id]), {}, null, function (code, data) {
                                    top.dialog.msg(top.dataMessage.deleteSuccess, {time: 1000});
                                    location.reload();
                                }, function (code, data) {
                                    top.dialog.msg(data.msg);
                                }, function () {
                                    layIndex = top.dialog.msg(top.dataMessage.deleting, {icon: 16, time: 0, shade: 0.3});
                                }, function () {
                                    top.dialog.close(layIndex);
                                });
                            }
                        });
                    },
                },
                {divider: true}
            ] );
        }
        // 添加区域
        $(document).on('click', '#btnAdd', function() {
            layer.open({
                type: 2,
                title: false,
                closeBtn: 0,
                area: ['60%', '90%'],
                shadeClose: true,
                anim: 2,
                content: top.restAjax.path('route/picturestemplatearea/savepicturestemplatearea?picturesTemplateId={picturesTemplateId}', [picturesTemplateId]),
                end: function() {
                    location.reload();
                }
            });
        });
        // 统一修改区域
        $(document).on('click', '#updateData', function() {
            layer.open({
                type: 2,
                title: "全部更改",
                closeBtn: 0,
                area: ['60%', '90%'],
                shadeClose: true,
                anim: 2,
                content: top.restAjax.path('route/picturestemplatearea/updatepicturestemplateareaall?picturesTemplateId={picturesTemplateId}', [picturesTemplateId]),
                end: function() {
                    location.reload();
                }
            });
        });

        //创建拖拽方法
        $(document).on('mousedown', '#canvas', function(e){
            var canvas = $(this);
            e.preventDefault();
            var pos = $(this).position();
            this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
            $.extend(document, {'move': true, 'move_target': this, 'call_down' : function(e, posix){
                    canvas.css({
                        'cursor': 'move',
                        'top': e.pageY - posix.y,
                        'left': e.pageX - posix.x
                    });
                }, 'call_up' : function(){
                    canvas.css('cursor', 'default');
                }});
        }).on('mousedown', '.box', function(e) {
            if(lock) return;
            var pos = $(this).position();
            this.posix = {'x': e.pageX - pos.left, 'y': e.pageY - pos.top};
            $.extend(document, {'move': true, 'move_target': this});
            e.stopPropagation();
        }).on('mousedown', '.box .coor', function(e) {
            var $box = $(this).parent();
            /**
             * 崔宝铖 2021年6月22日17:15:54 新增 innerX和innerY 用于拖拉拽超出区域判断
             * */
            var posix = {
                'w': $box.width(),
                'h': $box.height(),
                'x': e.pageX,
                'y': e.pageY,
                'innerX': Number($box.css("left").replace("px","")),
                'innerY': Number($box.css("top").replace("px",""))
            };
            $.extend(document, {'move': true, 'call_down': function(e) {
                    console.log(posix);
                    console.log(e);
                    var width = Math.max(10, e.pageX - posix.x + posix.w);
                    var height = Math.max(10, e.pageY - posix.y + posix.h);
                    if(width > dataFormData.templateWidth) {
                        layer.msg("宽度超出范围")
                        return;
                    }
                    if(height > dataFormData.templateHeight) {
                        layer.msg("高度超出范围")
                        return;
                    }
                    $box.css({
                        'width': Math.max(10, e.pageX - posix.x + posix.w),
                        'height': Math.max(10, e.pageY - posix.y + posix.h)
                    });
                }});
            e.stopPropagation();
        });

        function getAbsLeft(obj){
            var   l = obj.offsetLeft;
            while(obj.offsetParent != null){
                obj = obj.offsetParent;
                l += obj.offsetLeft;
            }
            return l;
        }
/*        $('.box').attr('tabindex', 1);
        $(document).on('keydown', '.box', function(e){
            if(lock == true){
                return
            }
            id = $(this).attr("id");
            alert(id);
            // 左
            if (e.keyCode == 37 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
                e.preventDefault();

            }
        });*/

        //修改区域点的x,y,width,height
        $(document).on('mouseup', '#canvas', function(e){
            if(lock == true){
                return
            }
            var x = "";
            var y = "";
            var w = "";
            var h = "";
            var id = "";
            // $(".box").keydown(function(){
            //     alert(1);
            // });
            $(".box").click(function(){
                id = $(this).attr("id");
                w = $(this).width();
                h = $(this).height();
                x = $('#'+id).css("left");
                y = $('#'+id).css("top");
                console.log("x坐标:"+x.replace("px","")+"y坐标:"+y.replace("px","")+"宽度:"+w+"高度:"+h+"id:"+id);
                var formData = {templateAreaLeft : x.replace("px","") , templateAreaTop : y.replace("px","") , templateAreaHeight : h , templateAreaWidth : w };
                var loadLayerIndex;
                top.restAjax.put(top.restAjax.path('api/picturestemplatearea/updatepicturestemplateareapoint/{picturesTemplateAreaId}', [id]), formData, null, function(code, data) {
                }, function(code, data) {
                    top.dialog.msg(data.msg, {time: 1000});
                }, function() {
                    loadLayerIndex = top.dialog.msg(top.dataMessage.committing, {icon: 16, time: 0, shade: 0.3});
                }, function() {
                    top.dialog.close(loadLayerIndex);
                });
            })
        });

        $(document).on('click', '#btnLock', function() {
            if(lock){
                $(this).text("锁定区域");
                lock = false;
                $('.box .coor').show();
                $('.bg').removeClass("bgTransparent");
            }else{
                $(this).text("解锁区域");
                lock = true;
                $('.box .coor').hide();
                $('.bg').addClass("bgTransparent");
            }
        });
        lock = false;
        $('.box .coor').show();
        $('#btnLock').text("锁定区域");

        function numDiv(num1, num2) {
            var baseNum1 = 0, baseNum2 = 0;
            var baseNum3, baseNum4;
            try {
                baseNum1 = num1.toString().split(".")[1].length;
            } catch (e) {
                baseNum1 = 0;
            }
            try {
                baseNum2 = num2.toString().split(".")[1].length;
            } catch (e) {
                baseNum2 = 0;
            }
            with (Math) {
                baseNum3 = Number(num1.toString().replace(".", ""));
                baseNum4 = Number(num2.toString().replace(".", ""));
                return (baseNum3 / baseNum4) * pow(10, baseNum2 - baseNum1);
            }
        }

        // 对Date的扩展，将 Date 转化为指定格式的String
        // 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
        // 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
        // 例子：
        // (new Date()).Format("yyyy-MM-dd HH:mm:ss.S") ==> 2006-07-02 08:09:04.423
        // (new Date()).Format("yyyy-M-d H:m:s.S")      ==> 2006-7-2 8:9:4.18
        Date.prototype.Format = function(fmt) { //author: meizz
            var o = {
                "M+" : this.getMonth()+1,                 //月份
                "d+" : this.getDate(),                    //日
                "H+" : this.getHours(),                   //小时
                "m+" : this.getMinutes(),                 //分
                "s+" : this.getSeconds(),                 //秒
                "q+" : Math.floor((this.getMonth()+3)/3), //季度
                "S"  : this.getMilliseconds()             //毫秒
            };
            if(/(y+)/.test(fmt))
                fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
            for(var k in o)
                if(new RegExp("("+ k +")").test(fmt))
                    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            return fmt;
        }

        var fileId = "";
        // 获取高和宽
        form.on('submit(areaForm)',function () {
            buiddingPicture();
        });

        var clipboard = undefined;
        function buiddingPicture() {
            var loadLayerIndex;
            top.restAjax.put(top.restAjax.path('api/picturestemplate/buiderpicturestemplate/{picturesTemplateCode}', [picturesTemplateCode]), {}, null, function(code, data) {
                var currentWindowWidth = $(window).width();
                var currentWindowHeight = $(window).height();
                fileId = data.data;
                console.log(fileId);
                if(code == 200) {
                    $("#target").text(data.data);
                    layer.open({
                        type: 0,
                        title: false,
                        btn: ['复制图片Base64','下载原图','新窗口预览'],
                        closeBtn: 1,
                        // area: [(dataFormData.templateWidth > currentWindowWidth ? currentWindowWidth / 10 * 9 : dataFormData.templateWidth )+ 'px', (dataFormData.templateHeight > currentWindowHeight ? currentWindowHeight / 10 * 9 : dataFormData.templateHeight) + 'px'],
                        area: ["1000px" , "600px"],
                        shadeClose: true,
                        anim: 2,
                        btn1:function(data) {
                            return false;
                        },
                        btn2:function(data) {
                            var time = new Date().Format("yyyyMMdd-HHmmss");
                            var a = document.createElement('a');
                            a.href = fileId;
                            a.setAttribute('download', dataFormData.picturesTemplateTitle + time);
                            a.click();
                            return false;
                        },
                        btn3:function(data) {
                            window.open(fileId);
                            return false;
                        },
                        // content: '<img width="100%" height="100%" src="route/file/download/true/' + data.data + '"></img>',
                        content: '<img width="100%" height="100%" src="' + data.data + '"></img>',
                        end: function() {
                            clipboard.off("success");
                            clipboard.off("error");
                        },success:function() {
                            clipboard = new Clipboard('.layui-layer-btn0',{
                                target: function(e) {
                                    var param = $(e).data("param");
                                    return document.querySelector('#target'); //复制标签文本
                                }
                            });
                            clipboard.on('success', function(e) {
                                top.layer.msg("已复制到剪切板")
                            });
                            clipboard.on('error', function(e) {
                                top.layer.msg("复制失败");
                            });
                        }
                    });
                }
            }, function(code, data) {
                top.dialog.msg(data.msg, {time: 1000});
            }, function() {
                loadLayerIndex = top.dialog.msg(top.dataMessage.committing, {icon: 16, time: 0, shade: 0.3});
            }, function() {
                top.dialog.close(loadLayerIndex);
            });
        }

        // 初始化内容
        function initData() {
            var loadLayerIndex;
            top.restAjax.get(top.restAjax.path('api/picturestemplate/getpicturestemplatebyid/{picturesTemplateId}', [picturesTemplateId]), {}, null, function(code, data) {
               /* for(var i in data) {
                    dataFormData[i] = data[i] +'';
                }*/
                dataFormData = data;
                dataFormData.templateHeight = data.picturesTemplateHeight; //numDiv(data.showTemplateHeight, 2);
                dataFormData.templateWidth = data.picturesTemplateWidth;//numDiv(data.showTemplateWidth, 2);
                $("#imgId").attr("src", 'route/file/download/true/' + data.picturesTemplateBackgroundImage + "?time=" + new Date());


                //初始化设备点
                $.each(data.areaList, function(i, row){
                    createBox(row);
                });
                var currentWindowWidth = $(window).width();
                dataFormData.marginLeft = (currentWindowWidth - dataFormData.templateWidth) / 2;
                dataFormData.currentWindowWidth  = currentWindowWidth;
                $("#target").css("margin-left", dataFormData.marginLeft);
                // 初始化背景图
                laytpl(document.getElementById("pageArea").innerHTML).render(dataFormData, function(html) {
                    document.getElementById("pageArea").innerHTML = html;
                });
            }, function(code, data) {
                top.dialog.msg(data.msg);
            }, function() {
                loadLayerIndex = top.dialog.msg(top.dataMessage.loading, {icon: 16, time: 0, shade: 0.3});
            }, function() {
                top.dialog.close(loadLayerIndex);
            });
        }
        initData();


        $('.close').on('click', function() {
            closeBox();
        });

        // 校验
        form.verify({
        });
    });
</script>
</body>
</html>