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

{% block help_message %}
    <div class="alert alert-info help-message">
{#    左侧是资产树，右击可以新建、删除、更改树节点，授权资产也是以节点方式组织的，右侧是属于该节点下的资产#}
    {% trans 'The left side is the asset tree, right click to create, delete, and change the tree node, authorization asset is also organized as a node, and the right side is the asset under that node' %}
    </div>
{% endblock %}

{% block custom_head_css_js %}
    <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>
    <script src="{% static 'js/jquery.form.min.js' %}"></script>
	<style type="text/css">
        div#rMenu {
            position:absolute;
            visibility:hidden;
            text-align: left;
            {#top: 100%;#}
            top: 0;
            left: 0;
            z-index: 1000;
            {#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>

{% endblock %}

{% block content %}
<div class="wrapper wrapper-content">
   <div class="row">
       <div class="col-lg-3" id="split-left" style="padding-left: 3px">
           {% include 'assets/_node_tree.html' %}
       </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">
               <div class="uc pull-left m-r-5"><a class="btn btn-sm btn-primary btn-create-asset"> {% trans "Create asset" %} </a></div>
               <div class="" style="float: right">
                   <div class=" btn-group">
                        <button data-toggle="dropdown" class="btn btn-default btn-sm dropdown-toggle">CSV <span class="caret"></span></button>
                        <ul class="dropdown-menu">
                            <li>
                                <a class=" btn_export" tabindex="0">
                                <span>{% trans "Export" %}</span>
                                </a>
                            </li>
                            <li>
                                <a class=" btn_import" data-toggle="modal" data-target="#import_modal" tabindex="0">
                                <span>{% trans "Import" %}</span>
                                </a>
                            </li>
                            <li>
                                <a class=" btn_update" data-toggle="modal" data-target="#update_modal" tabindex="0">
                                <span>{% trans "Update" %}</span>
                                </a>
                            </li>
                        </ul>
                   </div>
               </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" style="width: 100%">
                   <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 'Hardware' %}</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="remove">{% trans 'Remove from this node' %}</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>
</div>

{% include 'assets/_asset_update_modal.html' %}
{% include 'assets/_asset_import_modal.html' %}
{% include 'assets/_asset_list_modal.html' %}
{% endblock %}

{% block custom_foot_js %}
<script>
var asset_table, show = 0;
var update_node_action = "";
var current_node_id = null;
var testDatetime = "{% trans 'Test datetime: ' %}";

function initTable() {
    var options = {
        ele: $('#asset_list_table'),
        columnDefs: [
            {targets: 1, createdCell: function (td, cellData, rowData) {
                cellData = htmlEscape(cellData);
                {% 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: 3, createdCell: function (td, cellData, rowData) {
                $(td).html(rowData.hardware_info)
            }},
            {targets: 4, createdCell: function (td, cellData, rowData) {
                  var innerHtml = "";
                  if (cellData.status == 1) {
                      innerHtml = '<i class="fa fa-circle text-navy"></i>'
                  } else if (cellData.status == 0) {
                      innerHtml = '<i class="fa fa-circle text-danger"></i>'
                  } else {
                      innerHtml = '<i class="fa fa-circle text-warning"></i>'
                  }
                  var dateManual = toSafeLocalDateStr(cellData.datetime);
                  var dataContent = testDatetime + dateManual;
                  innerHtml = "<a data-toggle='popover' data-content='" + dataContent + "'" + 'data-placement="auto bottom"' + ">" + innerHtml + "</a>";
                  $(td).html(innerHtml);
            }},
            {targets: 5, 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: "cpu_cores", orderable: false},
            {
                data: "connectivity",
                orderable: false,
                width: '60px'
            }, {data: "id", orderable: false}
        ],
        op_html: $('#actions').html()
    };
    asset_table = jumpserver.initServerSideDataTable(options);
    return asset_table
}
function initTree() {
    initNodeTree({
        onSelected: onNodeSelected,
        showMenu: true,
        otherMenu: `
            <li class="divider"></li>
            <li id="menu_asset_add" class="btn-add-asset" data-toggle="modal" data-target="#asset_list_modal" tabindex="0"><a><i class="fa fa-copy"></i> {% trans 'Add assets to node' %}</a></li>
            <li id="menu_asset_move" class="btn-move-asset" data-toggle="modal" data-target="#asset_list_modal" tabindex="0"><a><i class="fa fa-cut"></i> {% trans 'Move assets to node' %}</a></li>
            <li class="divider"></li>
            <li id="menu_refresh_hardware_info" class="btn-refresh-hardware" tabindex="-1"><a><i class="fa fa-refresh"></i> {% trans 'Refresh node hardware info' %}</a></li>
            <li id="menu_test_connective" class="btn-test-connective" tabindex="-1"><a><i class="fa fa-chain"></i> {% trans 'Test node connective' %}</a></li>
            <li class="divider"></li>
            <li id="show_current_asset" class="btn-show-current-asset" style="display: none;" tabindex="-1"><a><i class="fa fa-hand-o-up"></i> {% trans 'Display only current node assets' %}</a></li>
            <li id="show_all_asset" class="btn-show-all-asset" style="display: none;" tabindex="-1"><a><i class="fa fa-th"></i> {% trans 'Displays all child node assets' %}</a></li>
        `
    })
}


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;
    }
}

function onNodeSelected(event, treeNode) {
    current_node = treeNode;
    current_node_id = treeNode.meta.node.id;
    zTree.expandNode(current_node, true);
    var url = asset_table.ajax.url();
    url = setUrlParam(url, "node_id", current_node_id);
    url = setUrlParam(url, "show_current_asset", getCookie('show_current_asset'));
    setCookie('node_selected', treeNode.node_id);
    asset_table.ajax.url(url);
    asset_table.ajax.reload();
}

function onAssetModalConfirmAddAssetToNode(table) {
    var assets_selected = table.selected;
    if (!current_node_id) {
        return
    }

    var data = {'assets': assets_selected};
    var success = function () {
        table.selected = [];
        table.ajax.reload()
    };

    var url = '';
    if (update_node_action === "move") {
        url = "{% url 'api-assets:node-replace-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
    } else {
        url = "{% url 'api-assets:node-add-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);
    }

    requestApi({
        'url': url,
        'method': 'PUT',
        'body': JSON.stringify(data),
        'success': success
    })
}

$(document).ready(function(){
    initTable();
    initTree();

    if(getCookie('show_current_asset') === '1'){
        $('#show_all_asset').css('display', 'inline-block');
    }
    else{
        $('#show_current_asset').css('display', 'inline-block');
    }

    var modalOption = {
        onModalConfirm: onAssetModalConfirmAddAssetToNode,
        onModalTableDone: null
    };
    setAssetModalOptions(modalOption);
})
.on('click', '.labels li', function () {
    var val = 'label:' + $(this).text();
    $("#asset_list_table_filter input").val(val);
    asset_table.search(val).draw();
 })
.on('click', '.btn_export', function () {
    var assets = asset_table.selected;
    var data = {
        'resources': assets
    };
    var search = $("input[type='search']").val();
    var props = {
        method: "POST",
        body: JSON.stringify(data),
        success_url: "{% url 'api-assets:asset-list' %}",
        format: 'csv',
        params: {
            search: search,
            node_id: current_node_id || ''
        }
    };
    APIExportData(props);
})
.on('click', '#btn_import_confirm', function () {
    var file = document.getElementById('id_file').files[0];
    if(!file){
        toastr.error("{% trans "Please select file" %}");
        return
    }
    var url = "{% url 'api-assets:asset-list' %}";
    if (current_node_id){
        url = setUrlParam(url, 'node_id', current_node_id);
    }
    var data_table = $('#asset_list_table').DataTable();

    APIImportData({
        url: url,
        method: "POST",
        body: file,
        data_table: data_table
    });
})
.on('click', '#download_update_template', function () {
    var assets = asset_table.selected;
    var data = {
        'resources': assets
    };
    var search = $("input[type='search']").val();
    var props = {
        method: "POST",
        body: JSON.stringify(data),
        success_url: "{% url 'api-assets:asset-list' %}?format=csv&template=update",
        format: 'csv',
        params: {
            search: search,
            node_id: current_node_id || ''
        }
    };
    APIExportData(props);
})
.on('click', '#btn_update_confirm', function () {
    var file = document.getElementById('update_file').files[0];
    if(!file){
        toastr.error("{% trans "Please select file" %}");
        return
    }
    var url = "{% url 'api-assets:asset-list' %}";
    if (current_node_id){
        url = setUrlParam(url, 'node_id', current_node_id);
    }
    var data_table = $('#asset_list_table').DataTable();

    APIImportData({
        url: url,
        method: "PUT",
        body: file,
        data_table: data_table
    });
})
.on('click', '.btn-create-asset', function () {
    var url = "{% url 'assets:asset-create' %}";
    if (current_node_id) {
        url += "?node_id=" + current_node_id;
    }
    window.open(url, '_self');
})
.on('click', '.btn-asset-delete', function () {
    var $this = $(this);
    var $data_table = $("#asset_list_table").DataTable();
    var name = $(this).closest("tr").find(":nth-child(2)").children('a').html();
    var uid = $this.data('uid');
    var the_url = '{% url "api-assets:asset-detail" pk=DEFAULT_PK %}'.replace("{{ DEFAULT_PK }}", uid);
    objectDelete($this, name, the_url);
    setTimeout( function () {
        $data_table.ajax.reload();
    }, 3000);
})
.on('click', '#btn_bulk_update', function () {
    var action = $('#slct_bulk_update').val();
    var id_list = asset_table.selected;
    if (id_list.length === 0) {
        return false;
    }
    var the_url = "{% url 'api-assets:asset-list' %}";
    var data = {
        'resources': id_list
    };
    function refreshPage() {
        setTimeout( function () {window.location.reload();}, 300);
    }

    function doDeactive() {
        var data = [];
        $.each(id_list, function(index, object_id) {
            var obj = {"pk": object_id, "is_active": false};
            data.push(obj);
        });
        requestApi({
            url: the_url,
            method: 'PATCH',
            body: JSON.stringify(data),
            success: refreshPage
        });
    }
    function doActive() {
        var data = [];
        $.each(id_list, function(index, object_id) {
            var obj = {"pk": object_id, "is_active": true};
            data.push(obj);
        });
        requestApi({
            url: the_url,
            method: 'PATCH',
            body: JSON.stringify(data),
            success: refreshPage
        });
    }
    function doDelete() {
        swal({
            title: "{% trans 'Are you sure?' %}",
            text: "{% trans 'This will delete the selected assets !!!' %}",
            type: "warning",
            showCancelButton: true,
            cancelButtonText: "{% trans 'Cancel' %}",
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "{% trans 'Confirm' %}",
            closeOnConfirm: false
        },function () {
            function success(data) {
                url = setUrlParam(the_url, 'spm', data.spm);
                requestApi({
                    url:url,
                    method:'DELETE',
                    success:refreshPage,
                    flash_message:false,
                });
                var msg = "{% trans 'Asset Deleted.' %}";
                swal("{% trans 'Asset Delete' %}", msg, "success");
            }
            function fail() {
                var msg = "{% trans 'Asset Deleting failed.' %}";
                swal("{% trans 'Asset Delete' %}", msg, "error");
            }
            requestApi({
                url: "{% url 'api-common:resources-cache' %}",
                method:'POST',
                body:JSON.stringify(data),
                success:success,
                error:fail
             })
        })
    }

    function doUpdate() {
        function fail(data) {
            toastr.error(JSON.parse(data))
        }
        function success(data) {
            var url = "{% url 'assets:asset-bulk-update' %}";
            location.href= setUrlParam(url, 'spm', data.spm);
         }
        requestApi({
            url: "{% url 'api-common:resources-cache' %}",
            method:'POST',
            body:JSON.stringify(data),
            flash_message:false,
            success:success,
            error:fail
        })
     }

    function doRemove() {
       if (!current_node_id) {
           return
       }

       var data = {
           'assets': id_list
       };

       var success = function () {
           asset_table.ajax.reload()
       };
       var url = "{% url 'api-assets:node-remove-assets' pk=DEFAULT_PK %}".replace("{{ DEFAULT_PK }}", current_node_id);

       requestApi({
           'url': url,
           'method': 'PUT',
           'body': JSON.stringify(data),
           'success': success
       })
    }

    switch(action) {
        case 'deactive':
            doDeactive();
            break;
        case 'delete':
            doDelete();
            break;
        case 'update':
            doUpdate();
            break;
        case 'active':
            doActive();
            break;
        case 'remove':
            doRemove();
            break;
        default:
            break;
    }
    $(".ipt_check_all").prop("checked", false)
})
.on('hidden.bs.modal', '#asset_list_modal', function () {
    window.location.reload();
}).on('click', '#menu_asset_add', function () {
    update_node_action = "add"
}).on('click', '#menu_asset_move', function () {
    update_node_action = "move"
}).on('click', '.btn-test-connective', function () {
    var url = "{% url 'api-assets:node-test-connective' pk=DEFAULT_PK %}";
    if (!current_node_id) {
        return null;
    }
    var the_url = url.replace("{{ DEFAULT_PK }}", current_node_id);
    function success(data) {
        rMenu.css({"visibility" : "hidden"});
        var task_id = data.task;
        showCeleryTaskLog(task_id);
    }
    requestApi({
        url: the_url,
        method: "GET",
        success: success,
        flash_message: false
    });
}).on('click', '.btn-refresh-hardware', function () {
    var url = "{% url 'api-assets:node-refresh-hardware-info' pk=DEFAULT_PK %}";
    var the_url = url.replace("{{ DEFAULT_PK }}", current_node_id);
    function success(data) {
        rMenu.css({"visibility" : "hidden"});
        var task_id = data.task;
        showCeleryTaskLog(task_id);
    }
    requestApi({
        url: the_url,
        method: "GET",
        success: success,
        flash_message: false
    });

})

</script>

{% endblock %}
