<!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: 12px;transform: translate(-50%,-50%)}

        #debug{position:absolute;right:10px;top:10px;z-index:88;border:1px solid #ccc;width:100px;height:100px;background:#fff;}
        #toolbar{position:absolute;left:10px;top:10px;z-index:88;}
    </style>
</head>
<body id="pageArea" class="list">
    <div id="toolbar" >
        <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-danger" lay-submit lay-filter="areaForm">重新生成该模板的静态页</button>
    </div>
    <div id="canvas" style=" width:{{d.bigdataTemplateWidth}}px;height:{{d.bigdataTemplateHeight}}px;">
        <img id="imgId" height="100%" width="100%" src="route/file/downloadfile/false/{{d.bigdataTemplateBackgroundImage}}" alt=""/>
    </div>
<script src="assets/layuiadmin/layui/layui.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 bigdataTemplateId = top.restAjax.params(window.location.href).bigdataTemplateId;
        var bigdataTemplateCode = top.restAjax.params(window.location.href).bigdataTemplateCode;
        var dataFormData = {};

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

        document.addEventListener('keydown', function(e){
            if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)){
                e.preventDefault();
                var loadLayerIndex;
                top.restAjax.get(top.restAjax.path('app/bigdatatemplate/buiderbigdatatemplaterelease/{bigdataTemplateCode}', [bigdataTemplateCode]), {}, null, function(code, data) {
                    if(code == 200) {
                        top.layer.msg('重新生成该模板下全部页面执行成功！',{
                            icon: 1,
                            time: 20000,
                        });
                    }else{
                        top.layer.msg('重新生成该模板下全部页面执行失败！',{
                            icon: 2,
                            time: 20000,
                        });
                    }
                }, function(code, data) {
                    top.dialog.msg(data.msg, {time: 1000});
                }, function() {
                    loadLayerIndex = top.dialog.msg('生成中...', {icon: 16, time: 0, shade: 0.3});
                }, function() {
                    top.dialog.close(loadLayerIndex);
                });
            }
        });

        // 初始化计数器
        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.bigdataTemplateAreaId || '';
            var value = data.bigdataModuleName || '区域';
            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 curNum = num++;
            //创建区域块
            var pos = $("#canvas").position();
            // background-image:url(route/file/downloadfile/false/'+ data.bigdataModulePhoto +');
            /**
             * 键盘控制位置移动必须添加tabindex
             * */
            var box = $('<div tabindex="1"  id="'+dataId+'" class="box" rel="'+curNum+'" areaName="' + value + '" dataId="'+dataId+'"><pre class="content" style="color:'+color+';">'+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/bigdatatemplatearea/updatebigdatatemplateareapoint/{bigdataTemplateAreaId}', [id]), formData, null, function(code, data) {
                    }, function(code, data) {
                    }, function() {
                    }, function() {
                    });
                }
            });

            //计算文本位置
            // 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 areaName = $('.box[rel='+curNum+']').attr("areaName");
                        var id = $('.box[rel='+curNum+']').attr("id");
                        layer.open({
                            type: 2,
                            title: areaName,
                            closeBtn: 1,
                            area: ['60%', '98%'],
                            shadeClose: false,
                            anim: 2,
                            content: top.restAjax.path('route/bigdatatemplatearea/updatebigdatatemplateareadata?bigdataTemplateAreaId={bigdataTemplateAreaId}', [id]),
                            end: function() {
                                // location.reload();
                            }
                        });
                    }
                },
                {text: '修改区域', action: function(e){
                        e.preventDefault();
                        //当前区域的id
                        var id = $('.box[rel='+curNum+']').attr("id");
                        layer.open({
                            type: 2,
                            title: false,
                            closeBtn: 0,
                            area: ['80%', '90%'],
                            shadeClose: false,
                            anim: 2,
                            content: top.restAjax.path('route/bigdatatemplatearea/updatebigdatatemplatearea?bigdataTemplateAreaId={bigdataTemplateAreaId}', [id]),
                            end: function() {
                                location.reload();
                            }
                        });
                    }
                },
                {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.put(top.restAjax.path('api/bigdatatemplatearea/copybigdatatemplatearea/{bigdataTemplateAreaId}', [id]), {}, 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/bigdatatemplatearea/removebigdatatemplatearea/{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: ['80%', '90%'],
                shadeClose: true,
                anim: 2,
                content: top.restAjax.path('route/bigdatatemplatearea/savebigdatatemplatearea?bigdataTemplateId={bigdataTemplateId}', [bigdataTemplateId]),
                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) {
                    var width = Math.max(30, e.pageX - posix.x + posix.w);
                    var height = Math.max(30, 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(30, e.pageX - posix.x + posix.w),
                        'height': Math.max(30, 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;
        }


        //修改设备点的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").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/bigdatatemplatearea/updatebigdatatemplateareapoint/{bigdataTemplateAreaId}', [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();
            }else{
                $(this).text("解锁区域");
                lock = true;
                $('.box .coor').hide();
            }
        });
        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);
            }
        }

        // 获取高和宽
        form.on('submit(areaForm)', function(formData) {
            top.dialog.confirm(top.dataMessage.commit, function(index) {
                top.dialog.close(index);
                var loadLayerIndex;
                top.restAjax.get(top.restAjax.path('app/bigdatatemplate/buiderbigdatatemplaterelease/{bigdataTemplateCode}', [bigdataTemplateCode]), {}, null, function(code, data) {
                    if(code == 200) {
                        top.layer.msg('重新生成该模板下全部页面执行成功！',{
                            icon: 1,
                            time: 20000,
                        });
                    }else{
                        top.layer.msg('重新生成该模板下全部页面执行失败！',{
                            icon: 2,
                            time: 20000,
                        });
                    }
                }, 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/bigdatatemplate/getbigdatatemplatebyid/{bigdataTemplateId}', [bigdataTemplateId]), {}, null, function(code, data) {
               /* for(var i in data) {
                    dataFormData[i] = data[i] +'';
                }*/
                dataFormData = data;

                dataFormData.templateHeight = data.bigdataTemplateHeight; //numDiv(data.showTemplateHeight, 2);
                dataFormData.templateWidth = data.bigdataTemplateWidth;//numDiv(data.showTemplateWidth, 2);

                //初始化设备点
                $.each(data.areaList, function(i, row){
                    createBox(row);
                });

                // 初始化背景图
                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>