{% load i18n %}
<div class="col-lg-3" style="padding-left: 0" id="split-left">
   <div class="ibox float-e-margins">
       <div class="ibox-content mailbox-content" style="padding-top: 0">
           <div class="file-manager ">
               <div id="assetTree" class="ztree">
                   {% trans 'Loading' %} ...
               </div>
               <div class="clearfix"></div>
           </div>
       </div>
   </div>
</div>
<div class="col-lg-9 animated fadeInRight" id="split-right">
    <div class="tree-toggle">
       <div class="btn btn-sm btn-primary tree-toggle-btn" onclick="toggle()">
           <i class="fa fa-angle-left fa-x" id="toggle-icon"></i>
       </div>
    </div>
    <div class="mail-box-header">
        <table class="table table-striped table-bordered table-hover" id="user_assets_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 'System user' %}</th>
                    {% if show_actions %}
                    <th class="text-center">{% trans 'Action' %}</th>
                    {% endif %}
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>
</div>
<script>
var zTree;
var inited = false;
var url;
var assetTable;
var treeUrl = "NeedInput";
var assetTableUrl = 'NeedInput';
var selectUrl = 'NeedInput';
var systemUsersUrl = "NeedInput";
var showAssetHref = true; // Need input default true
var actions = {};
var labels = '';
var requesting = false;

function initTable() {
    if (inited){
        return assetTable
    } else {
        inited = true;
    }
    var options = {
        ele: $('#user_assets_table'),
        columnDefs: [
            {targets: 1, createdCell: function (td, cellData, rowData) {
                cellData = htmlEscape(cellData);
                var assetDetailUrl = '{% url 'assets:asset-detail' pk=DEFAULT_PK %}'
                        .replace("{{ DEFAULT_PK }}", rowData.id);
                var detailBtn = '<a href="assetDetailUrl" class="asset-detail" data-asset="assetId">' + cellData + '</a>';
                if (showAssetHref) {
                    cellData = detailBtn.replace("assetDetailUrl", assetDetailUrl);
                } else {
                    detailBtn = detailBtn.replace("assetId", rowData.id);
                    cellData = detailBtn.replace("assetDetailUrl", "");
                }
                $(td).html(cellData);
            }},
            {targets: 3, createdCell: function (td, cellData) {
                var innerHtml = '<a class="btn-show-system-users" data-aid="99999999"> {% trans "Show" %} </a>'
                    .replace('99999999', cellData);
                $(td).html(innerHtml);

            }},
        ],
        ajax_url: assetTableUrl,
        columns: [
            {data: "id"}, {data: "hostname" }, {data: "ip" },
            {data: "id", orderable: false},
            {% if show_actions %}
            {data: "id", orderable: false}
            {% endif %}
        ]
    };
    {% if show_actions %}
    options.columnDefs.push(actions);
    {% endif %}
    assetTable = jumpserver.initServerSideDataTable(options);
    return assetTable
}

function onSelected(event, treeNode) {
    var node_id = treeNode.meta.node.id;
    url = selectUrl.replace("{{ DEFAULT_PK }}", node_id);
    assetTable.ajax.url(url);
    assetTable.ajax.reload();
}


function initTree(refresh) {
    var asyncUrl = setUrlParam(treeUrl, 'cache_policy', '1');
    var setting = {
        view: {
            dblClickExpand: false,
            showLine: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        async: {
			enable: true,
			url: asyncUrl,
			autoParam: ["id=key", "name=n", "level=lv"],
            type: 'get'
		},
        callback: {
            onSelected: onSelected
        }
    };

    $.get(treeUrl, function(data, status) {
        if (data.length === 0) {
            data.push({"name": "{% trans 'empty' %}", "id": ""})
        }
        zTree = $.fn.zTree.init($("#assetTree"), setting, data);
        if (!refresh) {
            initTable();
        }
        rootNodeAddDom(zTree, function () {
            treeUrl = setUrlParam(treeUrl, 'cache_policy', '2');
            initTree(true);
        });
    });
}

function getGrantedAssetSystemUsers(assetID, success) {
    var url = systemUsersUrl.replace("{{ DEFAULT_PK }}", assetID);
    requestApi({
        url: url,
        method: "GET",
        success: success,
        flash_message: false
    })
}

function loadLabels() {
    var labelListUrl = '{% url "api-assets:label-list" %}';
    var label = '<li><a style="font-weight: bolder">labelName:labelValue</a></li>';
    if (requesting) {
        return
    }
    if (!labels) {
        var data = {
            url: labelListUrl,
            method: "GET",
            success: function (data) {
                data.forEach(function (value) {
                    labels += label.replace("labelName", value.name).replace("labelValue", value.value)
                });
                $(".labels-menu").append(labels);
                requesting = false;
            },
            error: function() {
                requesting = false;
            },
            flash_message: false
        };
        requesting = true;
        requestApi(data)
    }
}

var show = 0;

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;
    }
    setTimeout(function () {
        $(".table").css("width", "100%");
        {#assetTable.columns.adjust();#}
    }, 500)
}

$(document).ready(function () {
    {#loadLabels()#}
}).on('click', '.labels-menu li', function () {
    var val = $(this).text();
    $("#user_assets_table_filter input").val(val);
    assetTable.search(val).draw();
}).on('click', '.btn-show-system-users', function () {
    var $this = $(this);
    var assetId = $this.data('aid');

    function success(systemUsers) {
        var users = [];
        $.each(systemUsers, function (id, data) {
            var name = htmlEscape(data.name);
            users.push(name);
        });
        $this.parent().html(users.join(','))
    }

    getGrantedAssetSystemUsers(assetId, success)
})
</script>
