{% load static %}
{% load i18n %}
<link href="{% static 'css/plugins/ztree/awesomeStyle/awesome.css' %}" rel="stylesheet">
{#    <link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet">#}
<script type="text/javascript" src="{% static 'js/plugins/ztree/jquery.ztree.all.min.js' %}"></script>
<style type="text/css">
    div#rMenu {
        position: absolute;
        visibility: hidden;
        text-align: left;
        {#top: 100%;#}
        top: 0;
        left: 0;
        z-index: 999;
        {#float: left;#}
        padding: 0 0;
        margin: 2px 0 0;
        list-style: none;
        background-clip: padding-box;
     }
    .dataTables_wrapper .dataTables_processing {
        opacity: .9;
        border: none;
    }
    div#rMenu li{
        margin: 1px 0;
        cursor: pointer;
        list-style: none outside none;
     }
    .dropdown a:hover {
        background-color: #f1f1f1
    }
</style>

<div class="ibox treebox float-e-margins" style="overflow:auto;">
   <div class="ibox-content mailbox-content" style="padding-top: 0;padding-left: 1px">
       <div class="file-manager" id="tree-node-id">
           <div id="{% block treeID %}nodeTree{% endblock %}" class="ztree">
           {% trans 'Loading' %} ...
           </div>
           <div class="clearfix"></div>
       </div>
   </div>
</div>

<div id="rMenu">
    <ul class="dropdown-menu menu-actions">
        <li class="divider"></li>
        <li id="m_create" tabindex="-1" onclick="addTreeNode();"><a><i class="fa fa-plus-square-o"></i> {% trans 'Add node' %}</a></li>
        <li id="m_del" tabindex="-1" onclick="editTreeNode();"><a><i class="fa fa-pencil-square-o"></i> {% trans 'Rename node' %}</a></li>
        <li id="m_del" tabindex="-1" onclick="removeTreeNode();"><a><i class="fa fa-minus-square"></i> {% trans 'Delete node' %}</a></li>
    </ul>
</div>
<script>
var zTree, rMenu = null;
var current_node_id = null;
var current_node = null;
var showMenu = false;


var treeUrl = '{% url 'api-assets:node-children-tree' %}?assets=0';
// options:
//    {
//       "onSelected": func,
//       "showAssets": false,
//       "beforeAsync": func()
//       "showMenu": false,
//       "otherMenu": "",
//       "showAssets": false,
//    }
var inited = false;
function initNodeTree(options) {
    if (options.showAssets) {
        treeUrl = setUrlParam(treeUrl, 'assets', '1')
    }
    var setting = {
        view: {
            dblClickExpand: false,
            showLine: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        async: {
			enable: true,
			url: treeUrl,
			autoParam: ["id=key", "name=n", "level=lv"],
            type: 'get'
		},
        edit: {
            enable: true,
			showRemoveBtn: false,
			showRenameBtn: false,
            drag: {
                isCopy: true,
                isMove: true
            }
        },
        callback: {
            onRightClick: OnRightClick,
            beforeClick: beforeClick,
            onRename: onRename,
            onSelected: options.onSelected || defaultCallback("On selected"),
            beforeDrag: beforeDrag,
            onDrag: onDrag,
            beforeDrop: beforeDrop,
            onDrop: onDrop,
            beforeAsync: options.beforeAsync || defaultCallback("Before async")
        }
    };
    $.get(treeUrl, function (data, status) {
        zTree = $.fn.zTree.init($("#nodeTree"), setting, data);
        rootNodeAddDom(zTree, function () {
            const url = '{% url 'api-assets:refresh-nodes-cache' %}';
            requestApi({
                url: url,
                method: 'GET',
                flash_message: false,
                success: function () {
                    initNodeTree(options);
                }
            });
        });
        inited = true;
    });

    if (inited) {
        return
    }

    if (options.showMenu) {
        showMenu = true;
        rMenu = $("#rMenu");
    }
    if (options.otherMenu) {
        $(".menu-actions").append(options.otherMenu)
    }
    return zTree
}

function addTreeNode() {
	hideRMenu();
	var parentNode = zTree.getSelectedNodes()[0];
	if (!parentNode){
	    return
    }
    var url = "{% url 'api-assets:node-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", parentNode.meta.node.id);
    $.post(url,  {}, function (data, status){
        if (status === "success") {
            var newNode = {
                id: data["key"],
                name: data["value"],
                pId: parentNode.id,
                meta: {
                    "node": data
                }
            };
            newNode.checked = zTree.getSelectedNodes()[0].checked;
            zTree.addNodes(parentNode, 0, newNode);
            var node = zTree.getNodeByParam('id', newNode.id, parentNode);
            zTree.editName(node);
        } else {
            alert("{% trans 'Create node failed' %}")
        }
    });
}

function removeTreeNode() {
	hideRMenu();
	var current_node = zTree.getSelectedNodes()[0];
	if (!current_node){
	    return
    }
	if (current_node.children && current_node.children.length > 0) {
		toastr.error("{% trans 'Have child node, cancel' %}");
	 } else if (current_node.meta.node.assets_amount !== 0) {
        toastr.error("{% trans 'Have assets, cancel' %}");
    } else {
        var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
		$.ajax({
            url: url,
            method: "DELETE",
            success: function () {
                zTree.removeNode(current_node);
            }
        });
	}
}

function editTreeNode() {
    hideRMenu();
    var current_node = zTree.getSelectedNodes()[0];
    if (!current_node){
        return
    }
    if (current_node) {
        current_node.name = current_node.meta.node.value;
    }
    zTree.editName(current_node);
}

function OnRightClick(event, treeId, treeNode) {
    if (!showMenu) {
        return
    }
    if (!treeNode && event.target.tagName.toLowerCase() !== "button" && $(event.target).parents("a").length === 0) {
		zTree.cancelSelectedNode();
		showRMenu("root", event.clientX, event.clientY);
	} else if (treeNode && !treeNode.noR) {
		zTree.selectNode(treeNode);
		showRMenu("node", event.clientX, event.clientY);
	}
}

function showRMenu(type, x, y) {
    var offset = $("#tree-node-id").offset();
    x -= offset.left;
    y -= offset.top;
    x += document.body.scrollLeft;
    y += document.body.scrollTop + document.documentElement.scrollTop;
    rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});
    $("#rMenu ul").show();
	$("body").bind("mousedown", onBodyMouseDown);
}

function beforeClick(treeId, treeNode, clickFlag) {
    return true;
}

function hideRMenu() {
	if (rMenu) rMenu.css({"visibility": "hidden"});
	$("body").unbind("mousedown", onBodyMouseDown);
}

function onBodyMouseDown(event){
	if (!(event.target.id === "rMenu" || $(event.target).parents("#rMenu").length>0)) {
		rMenu.css({"visibility" : "hidden"});
	}
}

function onRename(event, treeId, treeNode, isCancel){
    var url = "{% url 'api-assets:node-detail' pk=DEFAULT_PK %}"
        .replace("{{ DEFAULT_PK }}", current_node_id);
    var data = {"value": treeNode.name};
    if (isCancel){
        return
    }
    requestApi({
        url: url,
        body: JSON.stringify(data),
        method: "PATCH",
        success_message: "{% trans 'Rename success' %}",
        success: function () {
            var assets_amount = treeNode.meta.node.assets_amount;
            if (!assets_amount) {
                assets_amount = 0;
            }
            treeNode.name = treeNode.name + ' (' + assets_amount + ')';
            zTree.updateNode(treeNode);
        },
    })
}


function beforeDrag() {
    return true
}

function beforeDrop(treeId, treeNodes, targetNode, moveType) {
    var treeNodesNames = [];
    $.each(treeNodes, function (index, value) {
        treeNodesNames.push(value.name);
    });

    var msg = "你想移动节点: `" + treeNodesNames.join(",") + "` 到 `" + targetNode.name + "` 下吗?";
    return confirm(msg);
}

function onDrag(event, treeId, treeNodes) {
}

function onDrop(event, treeId, treeNodes, targetNode, moveType) {
    var treeNodesIds = [];
    $.each(treeNodes, function (index, value) {
        treeNodesIds.push(value.meta.node.id);
    });

    var the_url = "{% url 'api-assets:node-add-children' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", targetNode.meta.node.id);
    var body = {nodes: treeNodesIds};
    requestApi({
        url: the_url,
        method: "PUT",
        body: JSON.stringify(body)
    })
}

function defaultCallback(action) {
    function logging() {
        console.log(action)
    }
    return logging
}

function toggle() {
    if (show === 0) {
        $("#split-left").hide(500, function () {
            $("#split-right").attr("class", "col-lg-12");
            $("#toggle-icon").attr("class", "fa fa-angle-right fa-x");
            show = 1;
        });
    } else {
        $("#split-right").attr("class", "col-lg-9");
        $("#toggle-icon").attr("class", "fa fa-angle-left fa-x");
        $("#split-left").show(500);
        show = 0;
    }
}


$(document).ready(function () {
    $('.treebox').css('height', window.innerHeight - 60);
})
.on('click', '.btn-show-current-asset', function(){
    hideRMenu();
    $(this).css('display', 'none');
    $('#show_all_asset').css('display', 'inline-block');
    setCookie('show_current_asset', '1');
    location.reload()
})
.on('click', '.btn-show-all-asset', function(){
    hideRMenu();
    $(this).css('display', 'none');
    $('#show_current_asset').css('display', 'inline-block');
    setCookie('show_current_asset', '');
    location.reload();
}).on('click', '.tree-toggle-btn', function (e) {
    e.preventDefault();
    toggle();
})

</script>
