{* Вкладки *}
{capture name=tabs}
    <li><a href="index.php?module=ServicesAdmin">Услуги</a></li>
    <li class="active"><a href="index.php?module=ServicesMenuAdmin">Меню услуг</a></li>
    <li><a href="{url module=RepairsAdmin id=null page=null}">Автосервис</a></li>
{/capture}

{* Title *}
{$meta_title='Меню услуг' scope=parent}

{* Поиск *}
<form id="search" method="get">
    <input class="search" type="text" name="keyword" value="">
    <input class="search_button" type="submit" value="">
</form>

<style>
    .jstree-anchor {
        display: inline-flex !important;
        width: 100%;
        align-items: center;
        position: relative;
        box-sizing: border-box;
    }
    .jstree-search a {
        color: inherit;
    }
    #list .row {
        border: none;
        background: none;
    }
    #list .icons {
        padding-right: 20px;
    }
    #list .icons a {
        margin: 0 5px;
    }
    #list {
        display: none;
    }
</style>

{* Заголовок *}
<div id="header">
    <h1>Меню услуг</h1>
</div>
<!-- Заголовок (The End) -->

{if $services}
    <div id="main_list">
        <div class="mb-3">
            <a id="expand_all" href="#" class="">Развернуть все</a>&nbsp;/&nbsp;
            <a id="collapse_all" href="#">Свернуть все</a>
        </div>
        <form id="list_form" method="post">
            <input type="hidden" name="session_id" value="{$smarty.session.id}">
            <div id="list" class="pb-3">
                {function name=services_tree level=0}
                    {if $services}
                        <ul class="list">
                            {foreach $services as $service}
                                <li data-id="{$service->id}" data-parent="{$service->parent}" class="row">
                                    <span class="flex-grow-1">
                                        <a href="{url module=ServiceAdmin id=$service->id return=$smarty.server.REQUEST_URI}">{$service->name|escape}</a>
                                    </span>
                                    <span class="icons">
                                        <a class="preview" title="Предпросмотр в новом окне" href="../{$root_url}{$service->url}/"
                                           target="_blank"></a>
                                        <a class="enable{if $service->visible} a-visible{else} a-invisible{/if}" title="Активна" href="#"></a>
                                        <a class="delete" title="Удалить" href="#"></a>
                                    </span>
                                    {services_tree services=$service->children level=$level+1}
                                </li>
                            {/foreach}
                        </ul>
                    {/if}
                {/function}
                {services_tree services=$services}
            </div>
            <div id="action">
                <div id="select">
                    <select name="action">
                        <option value="enable">Сделать видимыми</option>
                        <option value="disable">Сделать невидимыми</option>
                        <option value="delete">Удалить</option>
                    </select>
                    <input id="apply_action" class="button_green" type="submit" value="Применить">
                </div>
            </div>
        </form>
    </div>
{else}
    Нет услуг
{/if}

<div id="right_menu">
</div>

{literal}
<link rel="stylesheet" href="design/js/jstree/themes/default/style.css">
    <script src="design/js/jquery/jquery.min.js"></script>
    <script src="design/js/jstree/jstree.js"></script>
<script>
    $(document).ready(function () {
        var $tree = $("#list"),
            $form = $("#list_form");

        function enable_node(icon, node) {
            var visible = icon.hasClass('a-invisible') ? 1 : 0;
            $tree.jstree('uncheck_all');
            $tree.jstree('check_node', node);
            $form.find('select[name="action"]').val(visible ? 'enable' : 'disable');
            $form.submit();
            /*$.ajax({
                type: 'POST',
                url: 'ajax/update_object.php',
                dataType: 'json',
                data: {
                    'object': 'page',
                    'action': 'enable',
                    'id': node.data.id,
                    'values': {'visible': icon.hasClass('a-invisible') ? 1 : 0},
                    'session_id': '{/literal}{$smarty.session.id}{literal}'
                },
                beforeSend: function () {
                    icon.addClass('loading_icon');
                },
                success: function (data) {
                    $('a.enable:first', icon.closest(".row")).toggleClass('a-invisible').toggleClass('a-visible');
                    icon.removeClass('loading_icon');
                }
            });*/
        }

        function delete_node(icon, node){
            $tree.jstree('uncheck_all');
            $tree.jstree('check_node', node);
            $form.find('select[name="action"]').val('delete')
            //$form.find('select[name="action"] option[value=delete]').attr('selected', true);
            $form.submit();
        }

        $tree.jstree({
            "core": {
                animation: 0,
                multiple: false,
                check_callback: function (operation, node, node_parent, node_position, more) {
                    return operation === 'move_node' ? true : false;
                },
                themes: {"theme": "default", "dots": false, "stripes": true, icons: false},
            },
            "checkbox": {
                //visible: false,
                whole_node: false,
                tie_selection: false,
                three_state: false
                //keep_selected_style	: false
                //cascade: 'down'
            },
            "plugins": [
                "dnd", "checkbox", "wholerow", "search"
            ]
        }).on("click.jstree", function (e, data) {
            var $el = $(e.target);
            if ($el.is('a')) {
                e.stopPropagation();
                e.stopImmediatePropagation();

                if($el.hasClass('enable') || $el.hasClass('delete')) {
                    if($el.hasClass('enable') )
                        enable_node($el, $tree.jstree('get_node', e.target));
                    else if($el.hasClass('delete') )
                        delete_node($el, $tree.jstree('get_node', e.target));
                    return false;
                }
            }
        }).on("move_node.jstree", function (e, data) {
            $.ajax({
                type: 'POST',
                url: 'ajax/update_object.php',
                dataType: 'json',
                data: {
                    'object': 'page',
                    'action': 'move',
                    'id': data.node.id,
                    'values': {
                        'parent': data.parent === "#" ? 28 : data.parent,
                        'position':data.position
                    },
                    'session_id': '{/literal}{$smarty.session.id}{literal}'
                },
                success: function (data) {
                    return;
                }
            });
        }).on("ready.jstree", function (e, data){
            //$tree.jstree('open_all');
            $tree.show();
            $.each(data.instance.get_json(null, {flat: true}), function(index, node) {
                $tree.jstree('set_id', node.id, node.data.id);
            });
        });

        $("#search").submit(function (e) {
            e.preventDefault();
            $tree.jstree("search", $("#search .search").val());
            return false;
        });

        $('#collapse_all').click(function () {
            $tree.jstree('close_all');
            return false;
        });
        $('#expand_all').click(function () {
            $tree.jstree('open_all');
            return false;
        });

        // Выделить все
        $("#check_all").click(function () {
            $tree.jstree('check_all');
        });

        $form.submit(function (e) {
            // Подтвердить удаление
            if ($('select[name="action"]').val() === 'delete' && !confirm("Подтвердите удаление.\n\nВнимание!\nБудут удалены ВСЕ страницы, включая дочерние к выбранным!"))
                return false;

            var inp = document.createElement("INPUT");
            inp.name = 'check[]';
            inp.type = "hidden";
            $($tree.jstree("get_checked", true)).each(function() {
                $form.append($(inp).clone().val(this.data.id));
            });
            //return false;
        });
    });
</script>
{/literal}