<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>常用指令</title>
    <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, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        body {
            background-color: #ffffff;
        }
        .ctx-menu-container {
            position: absolute;
            background: #fff;
            border: 1px solid #d2d2d2;
            border-radius: 2px;
            box-shadow: 0 2px 4px rgba(0,0,0,.12);
            z-index: 999;
            display: none;
        }
        .ctx-menu-container li {
            padding: 7px 15px;
            cursor: pointer;
        }
        .ctx-menu-container li:hover {
            background-color: #f2f2f2;
        }
        .ctx-submenu {
            padding-left: 20px;
            display: none;
        }
        .active-row {
            background-color: #f2f2f2 !important;
        }
        .highlight-row {
            background-color: #fffdd1 !important; 
            transition: background-color 0.5s;
        }
    </style>
</head>
<body>

    <div class="layui-form layuimini-form">
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <input type="hidden" name="device_id" id="device_id" th:value="${device_id}">
        <input type="hidden" name="send_channel" id="send_channel" th:value="${send_channel}">
    </div>

    <div id="cmdFormDialog" style="display: none; padding: 20px;">
        <form class="layui-form" lay-filter="cmdForm">
            <input type="hidden" name="id" id="id">
            
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label required">指令名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="name" id="name" lay-verify="required" lay-reqtext="不能为空" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">指令类型</label>
                    <div class="layui-input-inline">
                        <select name="type" id="type" lay-filter="type">
                            <option value="0">GNSS</option>
                            <option value="10">DTU</option>
                            <option value="2">MPU</option>
                            <option value="11">DTU2</option>
                            <option value="3">DEBUG</option>
                            <option value="16">V3.2 DEBUG</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label required">指令</label>
                <div class="layui-input-block">
                    <textarea name="content" id="content" class="layui-textarea"></textarea>
                </div>
            </div>
        </form>
    </div>

    <div class="ctx-menu-container" id="rightMenu">
        <ul>
            <li id="ctx-menu-edit">编辑</li>
            <li id="ctx-menu-send">发送</li>
            <li id="ctx-menu-top">置顶</li>
            <li id="ctx-menu-up">上移</li>
            <li id="ctx-menu-down">下移</li>
            <li id="ctx-menu-bottom">置底</li>
            <li id="ctx-menu-delete">删除</li>
        </ul>
    </div>

    <script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="add">添加指令</button>
            <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="edit" id="btnEdit" disabled>编辑</button>
            <button class="layui-btn layui-btn-sm" lay-event="go_top" id="btnTop" disabled>置顶</button>
            <button class="layui-btn layui-btn-sm" lay-event="move_up" id="btnUp" disabled>上移</button>
            <button class="layui-btn layui-btn-sm" lay-event="move_down" id="btnDown" disabled>下移</button>
            <button class="layui-btn layui-btn-sm" lay-event="go_bottom" id="btnBottom" disabled>置底</button>
            <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete" id="btnDelete" disabled>删除</button>
        </div>
    </script>

    <script type="text/html" id="currentTableBar">
        <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="use">发送</a>
    </script>

    <script th:inline="javascript">
        layui.use(['form', 'table', 'layer'], function () {
            var $ = layui.$,
                form = layui.form,
                table = layui.table,
                layer = layui.layer;
            var iframeIndex = parent.layer.getFrameIndex(window.name);
            var isMoving = false;
            var lastMovedId = null;
            var isManualOperation = false;
            
            /**
             * 初始化表单，要加上，不然刷新部分组件可能会不加载
             */
            form.render();

            var selectedRow = null;


            var tableIns = table.render({
                elem: '#currentTableId',
                url: '/gnss/cmd/list',
                toolbar: '#toolbarDemo', // 指定工具栏
                defaultToolbar: ['filter', 'exports', 'print'], // 默认工具栏
                cols: [[
                    {type: 'checkbox', fixed: 'left'}, // 添加复选框
                    {field: 'name', title: '指令名称', width: '20%'},
                    {field: 'type', title: '类型', templet: '#typeTrans'},
                    {field: 'content', title: '指令', width: '40%'},
                    {title: '操作', toolbar: '#currentTableBar', width: 100} // 只保留发送按钮
                ]],
                limits: [10, 15, 20, 25, 50, 100],
                limit: 10,
                page: true,
                skin: 'line',
                done: function(res, curr, count) {
                    // 表格加载完成后，检查是否有需要选中的行
                    // 这个部分是需要连续上移或者下移
                    //
                    if (lastMovedId && !isManualOperation) {
                        var data = res.data;
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].id == lastMovedId) {
                                var index = i;
                                var tr = $('.layui-table-body').find('tr[data-index="' + index + '"]');
                                tr.find('.layui-form-checkbox').click();
                                tr.addClass('highlight-row');
                                setTimeout(function() {
                                    tr.removeClass('highlight-row');
                                }, 1000);
                                
                                break;
                            }
                        }
                    }

                    selectedRow = null;
                    updateToolbarStatus();
                    isMoving = false;
                    isManualOperation = false;
                }
            });

            function updateToolbarStatus() {
                var checkStatus = table.checkStatus('currentTableId');
                var hasSelection = checkStatus.data.length > 0;
                var isSingleSelection = checkStatus.data.length === 1;
                // 只能删除，其他的不给点
                $('#btnEdit').prop('disabled', !isSingleSelection);
                $('#btnTop').prop('disabled', !isSingleSelection);
                $('#btnUp').prop('disabled', !isSingleSelection);
                $('#btnDown').prop('disabled', !isSingleSelection);
                $('#btnBottom').prop('disabled', !isSingleSelection);
                $('#btnDelete').prop('disabled', !hasSelection);

                if (isSingleSelection) {
                    $('#btnEdit,#btnTop,#btnUp,#btnDown,#btnBottom').removeClass('layui-btn-disabled');
                } else {
                    $('#btnEdit,#btnTop,#btnUp,#btnDown,#btnBottom').addClass('layui-btn-disabled');
                }
                
                if (hasSelection) {
                    $('#btnDelete').removeClass('layui-btn-disabled');
                } else {
                    $('#btnDelete').addClass('layui-btn-disabled');
                }
            }

            table.on('checkbox(currentTableFilter)', function(obj) {
                updateToolbarStatus();

                if (obj.type === 'one' && !obj.checked) {
                    isManualOperation = true;
                    lastMovedId = null;
                }
            });

            // table.on('rowDouble(currentTableFilter)', function(obj) {
            //     var data = obj.data;
            //     editCmd(data);
            // });

            table.on('sort(currentTableFilter)', function(obj){
                isManualOperation = true;
                lastMovedId = null;
            });

            table.on('tool(currentTableFilter)', function (obj) {
                isManualOperation = true;
                lastMovedId = null;
                
                var data = obj.data;
                if (obj.event === 'use') {
                    sendCmd(data);
                }
            });

            function editCmd(data) {
                form.val("cmdForm", {
                    "id": data.id,
                    "name": data.name,
                    "type": data.type,
                    "content": data.content
                });

                layer.open({
                    type: 1,
                    title: '编辑指令',
                    area: ['500px', '400px'],
                    content: $('#cmdFormDialog'),
                    btn: ['保存', '取消'],
                    yes: function(index, layero) {
                        saveCmd(index);
                    },
                    btn2: function(index, layero) {
                        layer.close(index);
                        return false;
                    }
                });
            }

            function sendCmd(data) {
                parent.setCmd(data.type, data.content);
                var deviceId = $('#device_id').val();
                var sendChannel = $('#send_channel').val();
                
                $.ajax({
                    type:"POST",
                    url:"/gnss/config_cmd",
                    data: {
                        'device_id': deviceId,
                        'send_channel': sendChannel,
                        'cmd_type': data.type,
                        'tx_win': data.content
                    },
                    success: function (result) {
                        if(result.code == 0) parent.setResult(result);
                        else layer.alert(result.msg);
                    },
                    error: function () {
                        console.log("ajax error");
                    }
                });
            }

            function deleteCmd(id) {
                layer.confirm('确定删除此指令?', function(index) {
                    $.ajax({
                        type:"POST",
                        url:"/gnss/cmd/delete",
                        data:{
                            'del_id':id
                        },
                        success: function (data) {
                            tableIns.reload();
                            layer.close(index);
                        },
                        error: function () {
                            console.log("ajax error");
                        }
                    });
                });
            }
            
            // 监听头工具栏事件
            table.on('toolbar(currentTableFilter)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data; // 获取选中的数据
                
                // 如果不是移动操作，重置lastMovedId
                if (obj.event !== 'move_up' && obj.event !== 'move_down' && 
                    obj.event !== 'go_top' && obj.event !== 'go_bottom') {
                    lastMovedId = null;
                    isManualOperation = true;
                }
                
                switch(obj.event){
                    case 'add':
                        // 清空表单
                        form.val("cmdForm", {
                            "id": "",
                            "name": "",
                            "type": 0,
                            "content": ""
                        });

                        layer.open({
                            type: 1,
                            title: '添加指令',
                            area: ['500px', '400px'],
                            content: $('#cmdFormDialog'),
                            btn: ['保存', '取消'],
                            yes: function(index, layero) {
                                saveCmd(index);
                            },
                            btn2: function(index, layero) {
                                layer.close(index);
                                return false;
                            }
                        });
                        break;
                    case 'edit':
                        if(data.length === 1) {
                            editCmd(data[0]);
                        }
                        break;
                    case 'delete':
                        if(data.length === 0) {
                            layer.msg('请选择要删除的数据');
                            return;
                        }
                        layer.confirm('确定删除选中的 ' + data.length + ' 条数据?', function(index) {
                            var deleteCount = 0;
                            var totalCount = data.length;

                            for(var i = 0; i < data.length; i++) {
                                $.ajax({
                                    type:"POST",
                                    url:"/gnss/cmd/delete",
                                    data:{
                                        'del_id': data[i].id
                                    },
                                    success: function() {
                                        deleteCount++;
                                        if(deleteCount === totalCount) {
                                            tableIns.reload();
                                            layer.close(index);
                                        }
                                    }
                                });
                            }
                        });
                        break;
                    case 'go_top':
                        if(data.length === 1) {
                            moveCmd(data[0].id, 'go_top');
                        }
                        break;
                    case 'move_up':
                        if(data.length === 1) {
                            moveCmd(data[0].id, 'move_up');
                        }
                        break;
                    case 'move_down':
                        if(data.length === 1) {
                            moveCmd(data[0].id, 'move_down');
                        }
                        break;
                    case 'go_bottom':
                        if(data.length === 1) {
                            moveCmd(data[0].id, 'go_bottom');
                        }
                        break;
                }
            });

            function saveCmd(index) {
                var formData = form.val("cmdForm");

                if(!formData.name) {
                    layer.msg('指令名称不能为空');
                    return;
                }

                var url = formData.id ? "/gnss/cmd/update" : "/gnss/cmd/add";
                
                $.ajax({
                    type: "POST",
                    url: url,
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify(formData),
                    success: function(result) {
                        // 关闭弹窗
                        layer.close(index);
                        
                        // 刷新表格
                        tableIns.reload();
                        layer.msg('保存成功');
                    },
                    error: function() {
                        console.log("ajax error");
                        layer.msg('保存失败');
                    }
                });
            }
            
            // 移动指令（包括置顶、上移、下移、置底）
            function moveCmd(id, moveType) {
                // 如果当前正在进行移动操作，则忽略本次请求
                if (isMoving) {
                    return;
                }
                
                // 设置锁定状态
                isMoving = true;
                
                // 记录移动的行ID
                lastMovedId = id;
                
                $.ajax({
                    type:"POST",
                    url:"/gnss/cmd/" + moveType,
                    data:{
                        'id': id
                    },
                    success: function() {
                        tableIns.reload();
                    },
                    error: function() {
                        console.log("ajax error");
                        isMoving = false;
                        lastMovedId = null;
                    }
                });
            }

            var rightMenu = $('#rightMenu');
            $(document).on('contextmenu', '.layui-table-view .layui-table-body table tr', function(e) {
                var index = $(this).attr('data-index');
                var tableData = table.cache['currentTableId'];
                selectedRow = tableData[index];

                $('.layui-table-body tr').removeClass('active-row');
                $(this).addClass('active-row');
                var mouseX = e.pageX;
                var mouseY = e.pageY;
                rightMenu.css({
                    left: mouseX,
                    top: mouseY
                }).show();
                
                return false;
            });
            
            $(document).click(function() {
                rightMenu.hide();
            });
            
            $('#ctx-menu-edit').click(function() {
                if(selectedRow) {
                    editCmd(selectedRow);
                    rightMenu.hide();
                }
            });
            
            $('#ctx-menu-send').click(function() {
                if(selectedRow) {
                    sendCmd(selectedRow);
                    rightMenu.hide();
                }
            });
            
            $('#ctx-menu-top').click(function() {
                if(selectedRow) {
                    moveCmd(selectedRow.id, 'go_top');
                    rightMenu.hide();
                }
            });
            
            $('#ctx-menu-up').click(function() {
                if(selectedRow) {
                    moveCmd(selectedRow.id, 'move_up');
                    rightMenu.hide();
                }
            });
            
            $('#ctx-menu-down').click(function() {
                if(selectedRow) {
                    moveCmd(selectedRow.id, 'move_down');
                    rightMenu.hide();
                }
            });
            
            $('#ctx-menu-bottom').click(function() {
                if(selectedRow) {
                    moveCmd(selectedRow.id, 'go_bottom');
                    rightMenu.hide();
                }
            });
            
            $('#ctx-menu-delete').click(function() {
                if(selectedRow) {
                    deleteCmd(selectedRow.id);
                    rightMenu.hide();
                }
            });

            $(document).on('click', '.layui-table-page a', function() {
                lastMovedId = null;
                isManualOperation = true;
            });
            
            $(document).on('click', '.layui-table-tool-panel li', function() {
                lastMovedId = null;
                isManualOperation = true;
            });
        });
    </script>

    <script type="text/html" id="typeTrans">
        {{#  if(d.type == 0){ }}
        <span>GNSS</span>
        {{# } else if(d.type == 10){ }}
        <span >DTU</span>
        {{# } else if(d.type == 2){ }}
        <span >MPU</span>
        {{# } else { }}
        <span >DEBUG</span>
        {{#  } }}
    </script>
</body>
</html>