
/*   menuEntities example:
[
    {
        "id": 100,
        "pid": 0,
        "sortIndex": 100,
        "title": "Sqler",

        "url": "/Scripts/autoTemp/item.html?apiRoute=/autoTemp/data/Sqler_SqlBackup_SqlServerBackup_Config/{action}&mode=update&id=1",
        "target": "blank" // 'blank', 'jump' , '' (default: add to tab)
    }
]
//*/

let menuEntities = [];


/*   jsMenus example:
{
    "attributes": {
        "url": "/sqler/DataEditor/index.html",
        "target": "blank"  // 'blank', 'jump' , '' (default: add to tab)
    },
    "text": "<img  mid='" + Math.random() + "' />DataEditor",
     "iconCls": "icon-null",
    "children":[]
}
//*/

var jsMenus = [];



let mid = 1;
function getMenu(menuEntity) {

    if (typeof (menuEntity.extra) === 'string') {
        try {
            menuEntity.extra = JSON.parse(menuEntity.extra);
        } catch (e) { }
    }


    let children = null;

    let childrenMenu = menuEntities.filter(child => child.pid == menuEntity.id);
    if (childrenMenu?.length) {
        children = childrenMenu.map(getMenu);
    }

    let menu =
    {
        attributes: {
            url: menuEntity.url || '',
            target: menuEntity.extra?.target || '',
        },
        text: "<img mid='" + (mid++) + "' />" + menuEntity.title,
        iconCls: menuEntity.extra?.iconCls || "icon-tip",
        children: children
    };

    return menu;
}







// get menu items
$.ajax({
    type: 'GET',
    url: '/autoTemp/data/Sqler_Menu_Mng/getList?sort=[{"field":"sortIndex","asc":true}]',
    dataType: "json",
    success: function (apiReturn) {

        try {
            menuEntities = apiReturn?.data?.items;
            if (menuEntities) {

                jsMenus = menuEntities
                    .filter(m => !m.pid && m.enabled != false)
                    .map(getMenu);
            }

        } catch (e) {
        }


        $(function () {
            // load menu tree
            $('#MenuTree').tree({
                checkbox: false,
                animate: true,
                onClick: function (node) {
                    var url = node.attributes.url;
                    if (!url) return;
                    switch (node.attributes.target) {
                        case 'jump': window.top.location = url; break;
                        case 'blank': window.open(url); break;
                        default: addTab(node.text, url);
                    }
                },
                data: jsMenus
            });

        });

    }
});
