{% extends 'base.html' %}
{% load static %}
{% load i18n %}

{% block custom_head_css_js %}
    <link href="{% static 'css/plugins/jstree/style.min.css' %}" rel="stylesheet">
    <link href="{% static 'css/plugins/ztree/ztreestyle/ztreestyle.css' %}" rel="stylesheet">
{#    <link href="{% static 'css/plugins/ztree/demo.css' %}" rel="stylesheet">#}
    <script type="text/javascript" src="{% static 'js/plugins/ztree/jquery.ztree.all.min.js' %}"></script>
    <script type="text/javascript">
		$(document).ready(function(){

		});
	</script>
	<style type="text/css">
        div#rMenu {
            position:absolute;
            visibility:hidden;
            text-align: left;
            top: 100%;
            left: 0;
            z-index: 1000;
            float: left;
            padding: 5px 0;
            margin: 2px 0 0;
            list-style: none;
            background-clip: padding-box;
        }
        div#rMenu li{
        	margin: 1px 0;
        	cursor: pointer;
        	{#list-style: none outside none;#}
        }
        .dropdown a:hover {
            background-color: #f1f1f1
        }
	</style>

{% endblock %}

{% block content %}
<div class="wrapper wrapper-content">
   <div class="row">
       <div class="col-lg-3">
           <div class="ibox float-e-margins">
               <div class="ibox-content mailbox-content">
                   <div class="file-manager">
                       <h5>Tree View</h5>
                       <div id="assetTree" class="ztree">
                       </div>

                       <div class="clearfix"></div>
                   </div>
               </div>
           </div>
       </div>
       <div class="col-lg-9 animated fadeInRight">
           <div class="row">
               <div class="mail-box-header">
                   <div class="uc pull-left m-r-5"><a href="{% url "assets:asset-create" %}" class="btn btn-sm btn-primary"> {% trans "Add asset" %} </a></div>
                   <div class="btn-group" style="float: right">
                       <button data-toggle="dropdown" class="btn btn-default btn-sm dropdown-toggle">{% trans 'Label' %} <span class="caret"></span></button>
                       <ul class="dropdown-menu labels">
                           {% for label in labels %}
                               <li><a style="font-weight: bolder">{{ label.name }}:{{ label.value }}</a></li>
                           {% endfor %}
                       </ul>
                   </div>
                   <table class="table table-striped table-bordered table-hover " id="asset_list_table" >
                       <thead>
                           <tr>
                               <th class="text-center"><input type="checkbox" class="ipt_check_all"></th>
                               <th class="text-center">{% trans 'Hostname' %}</th>
                               <th class="text-center">{% trans 'IP' %}</th>
                               <th class="text-center">{% trans 'Port' %}</th>
                               <th class="text-center">{% trans 'Cluster' %}</th>
                               <th class="text-center">{% trans 'Hardware' %}</th>
                               <th class="text-center">{% trans 'Active' %}</th>
                               <th class="text-center">{% trans 'Reachable' %}</th>
                               <th class="text-center">{% trans 'Action' %}</th>
                           </tr>
                       </thead>
                       <tbody>
                       </tbody>
                   </table>
                   <div id="actions" class="hide">
                       <div class="input-group">
                           <select class="form-control m-b" style="width: auto" id="slct_bulk_update">
                               <option value="delete">{% trans 'Delete selected' %}</option>
                               <option value="update">{% trans 'Update selected' %}</option>
                               <option value="deactive">{% trans 'Deactive selected' %}</option>
                               <option value="active">{% trans 'Active selected' %}</option>
                           </select>
                           <div class="input-group-btn pull-left" style="padding-left: 5px;">
                               <button id='btn_bulk_update' style="height: 32px;"  class="btn btn-sm btn-primary">
                                {% trans 'Submit' %}
                               </button>
                           </div>
                       </div>
                   </div>
               </div>
           </div>
           <div class="row">
           </div>
       </div>
   </div>
</div>

<div id="rMenu">
    <ul class="dropdown-menu">
        <li id="m_del" tabindex="-1" onclick="removeTreeNode();"><a>重命名</a></li>
        <li id="m_add" tabindex="-1" onclick="addTreeNode();"><a>添加节点</a></li>
        <li class="divider"></li>
        <li id="m_del" tabindex="-1" onclick="removeTreeNode();"><a>删除节点</a></li>
    </ul>
</div>
{% endblock %}

{% block custom_foot_js %}
<script src="{% static 'js/plugins/jstree/jstree.min.js' %}"></script>

<script>
    var zTree, rMenu;
    function initTable() {
        var options = {
            ele: $('#asset_list_table'),
            columnDefs: [
                {targets: 1, createdCell: function (td, cellData, rowData) {
                    {% url 'assets:asset-detail' pk=DEFAULT_PK as the_url  %}
                    var detail_btn = '<a href="{{ the_url }}">' + cellData + '</a>';
                    $(td).html(detail_btn.replace('{{ DEFAULT_PK }}', rowData.id));
                }},
                {targets: 4, createdCell: function (td, cellData, rowData) {
                     $(td).html(rowData.cluster_name)
                }},
                {targets: 5, createdCell: function (td, cellData, rowData) {
                    $(td).html(rowData.hardware_info)
                }},
                {targets: 6, createdCell: function (td, cellData) {
                    if (!cellData) {
                        $(td).html('<i class="fa fa-times text-danger"></i>')
                    } else {
                        $(td).html('<i class="fa fa-check text-navy"></i>')
                    }
                }},
                {targets: 7, createdCell: function (td, cellData) {
                    if (cellData == 'Unknown'){
                        $(td).html('<i class="fa fa-circle text-warning"></i>')
                    } else if (!cellData) {
                        $(td).html('<i class="fa fa-circle text-danger"></i>')
                    } else {
                        $(td).html('<i class="fa fa-circle text-navy"></i>')
                    }
                }},
                {targets: 8, createdCell: function (td, cellData, rowData) {
                    var update_btn = '<a href="{% url "assets:asset-update" pk=DEFAULT_PK %}" class="btn btn-xs btn-info">{% trans "Update" %}</a>'.replace("{{ DEFAULT_PK }}", cellData);
                    var del_btn = '<a class="btn btn-xs btn-danger m-l-xs btn_asset_delete" data-uid="{{ DEFAULT_PK }}">{% trans "Delete" %}</a>'.replace('{{ DEFAULT_PK }}', cellData);
                    $(td).html(update_btn + del_btn)
                }}
            ],
            ajax_url: '{% url "api-assets:asset-list" %}',
            columns: [
                {data: "id"}, {data: "hostname" }, {data: "ip" }, {data: "port" },
                {data: "cluster"},
                {data: "cpu_cores"}, {data: "is_active", orderable: false },
                {data: "is_connective", orderable: false}, {data: "id", orderable: false }
            ],
            op_html: $('#actions').html()
        };
        return jumpserver.initServerSideDataTable(options);
    }

    function OnRightClick(event, treeId, treeNode) {
	    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) {
		$("#rMenu ul").show();
		if (type === "root") {
			$("#m_del").hide();
			$("#m_check").hide();
			$("#m_unCheck").hide();
		} else {
			$("#m_del").show();
			$("#m_check").show();
			$("#m_unCheck").show();
		}
        {#y += $("#page-wrapper")[0].scrollTop;#}
        {#x += $("#page-wrapper")[0].scrollLeft;#}
        x -= 220;
        {#y -= 100;#}
        {#y += document.body.scrollTop;#}
        {#x += document.body.scrollLeft;#}
        rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

		$("body").bind("mousedown", onBodyMouseDown);
	}

	function beforeClick(treeId, treeNode, clickFlag) {
        return true;
	}
	
	function onClick(event, treeId, treeNode, clickFlag) {
		showLog("On click");
	}

	function showLog(str) {
        console.log(str)
	}

	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 addTreeNode() {
		hideRMenu();
		var parentNode = zTree.getSelectedNodes()[0];
		if (!parentNode){
		    return
        }
        var url = "{% url 'api-assets:node-children' pk='0:0' %}".replace("0:0", parentNode.id );

        $.post(url,  {}, function (data, status){
            if (status === "success") {
                var newNode = { name:data["name"], id:data["id"],  pId: parentNode.id };
                newNode.checked = zTree.getSelectedNodes()[0].checked;
                zTree.addNodes(parentNode, newNode);
            } 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) {
			alert("{% trans 'Have child node, cancel' %}")
		} else {
            var url = "{% url 'api-assets:node-detail' pk='0:0' %}".replace("0:0", current_node.id );
			$.ajax({
                url: url,
                method: "DELETE",
                success: function () {
                    zTree.removeNode(current_node);
                }
            });
		}
	}

    function initTree() {
        var setting = {
            view: {
                dblClickExpand: false
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onRightClick: OnRightClick,
                beforeClick: beforeClick,
				onClick: onClick
            }
        };

        var zNodes = [];
        $.get("{% url 'api-assets:node-list' %}", function(data, status){
            $.each(data, function (index, value) {
                value["pId"] = value["parent"];
                if (value["id"] === "0") {
                    value["open"] = true;
                }
            });
            zNodes = data;
            $.fn.zTree.init($("#assetTree"), setting, zNodes);
            zTree = $.fn.zTree.getZTreeObj("assetTree");
			rMenu = $("#rMenu");
        });
    }
    $(document).ready(function(){
        initTable();
        initTree();
    });
</script>

{% endblock %}