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

{% block modal_class %}modal-lg{% endblock %}
{% block modal_id %}asset_list_modal{% endblock %}
{% block modal_title%}{% trans "Asset list" %}{% endblock %}
{% block modal_body %}
<link href="{% static 'css/plugins/ztree/awesomeStyle/awesome.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>
.inmodal .modal-header {
    padding: 10px 10px;
    text-align: center;
}

#asset_modal_tree.ztree * {
    background-color: white;
}
#asset_modal_tree.ztree {
    background-color: white;
}
</style>

<div class="wrapper wrapper-content">
   <div class="row">
       <div class="col-sm-3" id="split-left" style="padding-left: 3px;overflow: auto;max-height: 500px">
           <div class="ibox float-e-margins">
               <div class="ibox-content mailbox-content" style="padding-top: 0;padding-left: 1px">
                   <div class="file-manager ">
                       <div id="asset_modal_tree" class="ztree">
                           {% trans 'Loading' %} ...
                       </div>
                       <div class="clearfix"></div>
                   </div>
               </div>
           </div>
       </div>
       <div class="col-sm-9 animated fadeInRight" id="split-right">
           <div class="mail-box-header">
               <table class="table table-striped table-bordered table-hover " id="asset_list_modal_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>
                       </tr>
                   </thead>
                   <tbody>
                   </tbody>
               </table>
           </div>
       </div>
   </div>
</div>

<script>
function syncTableSelectedAssetToSelect2(table) {
    var assets = table.selected;
    var options = [];
    var select2Id = assetModalOption.select2Id;
    $(select2Id + ' option').each(function (i, v) {
        options.push(v.value)
    });
    table.selected_rows.forEach(function (i) {
        var name = i.hostname + '(' + i.ip + ')';
        var option = new Option(name, i.id, false, true);

        if (options.indexOf(i.id) === -1) {
            $(select2Id).append(option).trigger('change');
        }
    });
    $(select2Id).val(assets).trigger('change');
}



// 解决input框中的资产和弹出表格中资产的显示不一致
function syncSelectedAssetsToModalTable(assetModalTable) {
    var select2Id = assetModalOption.select2Id;
    var inputAssets = $(select2Id).val();
    var selectedAssets = assetModalTable.selected.concat();

    // input assets无，table assets选中，则取消勾选(再次click)
    if (selectedAssets.length !== 0) {
        $.each(selectedAssets, function (index, assetId) {
            if ($.inArray(assetId, inputAssets) === -1) {
                $('#' + assetId).trigger('click');  // 取消勾选
            }
        });
    }

    // input assets有，table assets没选，则选中(click)
    if (inputAssets) {
        assetModalTable.selected = inputAssets;
        $.each(inputAssets, function (index, assetId) {
            var dom = document.getElementById(assetId);
            if (dom !== null) {
                var selected = dom.parentElement.parentElement.className.indexOf('selected')
            }
            if (selected === -1) {
                $('#' + assetId).trigger('click');
            }
        });
    }
}

defaultOnAssetModalConfirm = syncTableSelectedAssetToSelect2;
defaultOnModalTableDone = syncSelectedAssetsToModalTable;


var assetModalOption = {
    selectStyle: 'multi',
    select2Id: '#id_assets',
    onModalTableDone: defaultOnModalTableDone,
    onModalTreeDone: null,
    onModalConfirm: defaultOnAssetModalConfirm,
};

var assetModalTable, assetModalTree = null;

function initAssetModalTable() {
    if(assetModalTable){
        return
    }
    if (assetModalOption.selectStyle === 'single') {
        $('.ipt_check_all').addClass('hidden')
    }
    var options = {
        ele: $('#asset_list_modal_table'),
        ajax_url: '{% url "api-assets:asset-list" %}?show_current_asset=1',
        columns: [
            {data: "id"}, {data: "hostname" }, {data: "ip" }
        ],
        lengthMenu: [[10, 25, 50], [10, 25, 50]],
        pageLength: 10,
        select_style: assetModalOption.selectStyle,
        paging_numbers_length: 3
    };
    assetModalTable = jumpserver.initServerSideDataTable(options);
    if (assetModalOption.onModalTableDone) {
        assetModalOption.onModalTableDone(assetModalTable);
    }
    return assetModalTable
}

function onModalTreeNodeSelected(event, treeNode) {
    var url = assetModalTable.ajax.url();
    url = setUrlParam(url, "node_id", treeNode.meta.node.id);
    url = setUrlParam(url, "show_current_asset", "");
    assetModalTable.ajax.url(url);
    assetModalTable.ajax.reload();
}


function initModalTree() {
    var url = '{% url 'api-assets:node-children-tree' %}?assets=0';
    var setting = {
        view: {
            dblClickExpand: false,
            showLine: true
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        async: {
			enable: true,
			url: url,
			autoParam: ["id=key", "name=n", "level=lv"],
            type: 'get'
		},
        callback: {
            onSelected: onModalTreeNodeSelected
        }
    };
    $.get(url, function(data, status){
        $.fn.zTree.init($("#asset_modal_tree"), setting);
        assetModalTree = $.fn.zTree.getZTreeObj("assetTree2");
        if (assetModalOption.onModalTreeDone) {
            assetModalOption.onModalTreeDone(assetModalTree);
        }
        return assetModalTree;
    });
}

function setAssetModalOptions(options) {
    assetModalOption = options;
}

function initAssetTreeModel(selector) {
    $(selector).parent().find(".select2-selection").on('click', function (e) {
        if ($(e.target).attr('class') !== 'select2-selection__choice__remove'){
            e.preventDefault();
            e.stopPropagation();
            $("#asset_list_modal").modal();
        }
    })
}


$(document).ready(function(){

}).on('show.bs.modal', function () {
    initAssetModalTable();
    initModalTree();
}).on('click', '#btn_asset_modal_confirm', function () {
    if (assetModalOption.onModalConfirm) {
        assetModalOption.onModalConfirm(assetModalTable, assetModalTree);
    }
    $("#asset_list_modal").modal('hide');
})
</script>
{% endblock %}

{% block modal_button %}
    {{ block.super }}
{% endblock %}
{% block modal_confirm_id %}btn_asset_modal_confirm{% endblock %}



