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

{% block custom_head_css_js %}
    <link href="{% static "css/plugins/select2/select2.min.css" %}" rel="stylesheet">
    <script src="{% static "js/plugins/select2/select2.full.min.js" %}"></script>
	<style type="text/css">

	</style>
{% endblock %}
{% block content %}
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="panel-options">
                        <ul class="nav nav-tabs">
                            <li>
                                <a href="{% url 'assets:idc-detail' pk=idc.id %}" class="text-center"><i class="fa fa-laptop"></i> {% trans 'Detail' %} </a>
                            </li>
                            <li class="active"><a href="{% url 'assets:idc-assets' pk=idc.id %}" class="text-center">
                                <i class="fa fa-bar-chart-o"></i> {% trans 'IDC assets' %}</a>
                            </li>
                        </ul>
                    </div>
                    <div class="tab-content">
                        <div class="col-sm-7" style="padding-left: 0;">
                            <div class="ibox float-e-margins">
                                <div class="ibox-title">
                                    <span style="float: left">{% trans 'IDC assets' %} <b>{{ idc.name }} </b><span class="badge"></span></span>
                                    <div class="ibox-tools">
                                        <a class="collapse-link">
                                            <i class="fa fa-chevron-up"></i>
                                        </a>
                                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                            <i class="fa fa-wrench"></i>
                                        </a>
                                        <ul class="dropdown-menu dropdown-user">
                                        </ul>
                                        <a class="close-link">
                                            <i class="fa fa-times"></i>
                                        </a>
                                    </div>
                                </div>

                                <div class="ibox-content">
                                    <table class="table table-striped table-bordered table-hover " id="idc_assets_table" >
                                        <thead>
                                            <tr>
                                                <th class="text-center">
                                                    <input type="checkbox" id="check_all" class="ipt_check_all" >
                                                </th>
                                                <th>{% trans 'Hostname' %}</th>
                                                <th>{% trans 'IP' %}</th>
                                                <th>{% trans 'Port' %}</th>
                                                <th>{% trans 'Type' %}</th>
                                                <th>{% trans 'Valid' %}</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 'Remove 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-warning">
									                               {% trans 'Submit' %}
									                              </button>
									                          </div>
									                      </div>
									                  </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-sm-5" style="padding-left: 0;padding-right: 0">
                            <div class="panel panel-primary">
                                <div class="panel-heading">
                                    <i class="fa fa-info-circle"></i> {% trans 'Add assets to' %} {{ idc.name }}
                                </div>
                                <div class="panel-body">
                                    <table class="table">
                                        <tbody>
                                        <form>
                                            <tr class="no-borders-tr">
                                                <td colspan="2">
                                                    <select data-placeholder="{% trans 'Select asset' %}" class="select2" style="width: 100%" multiple="" tabindex="4">
                                                        {% for asset in assets_remain %}
                                                            <option value="{{ asset.id }}" id="opt_{{ asset.id }}">{{ asset.ip}}:{{ asset.port }}</option>
                                                        {% endfor %}
                                                    </select>
                                                </td>
                                            </tr>
                                            <tr class="no-borders-tr">
                                                <td colspan="2">
                                                    <button type="button" class="btn btn-primary btn-sm btn-asset-attach">{% trans 'Confirm' %}</button>
                                                </td>
                                            </tr>
                                        </form>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/jquery.form.min.js' %}"></script>
<script>

jumpserver.assets_selected = {};

Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
		if (index > -1) {
		this.splice(index, 1);
	}
};

function updateIDCAssets(assets) {
    var the_url = "{% url 'api-assets:idc-update-assets' pk=idc.id %}";
    var body = {
        assets: Object.assign([], assets)
    };
	var $data_table = $("#idc_assets_table").DataTable();
    var success = function(data) {
        $('.select2-selection__rendered').empty();
        $.map(jumpserver.assets_selected, function(asset_ip, index) {
	        $('#opt_' + index).remove();
			$data_table.ajax.reload();
        });
        jumpserver.groups_selected = {};
    };
    APIUpdateAttr({
        url: the_url,
        body: JSON.stringify(body),
	    method: 'PUT',
        success: success
    });
}

function deleteIDCAssets(assets) {
	var the_url = "{% url 'api-assets:idc-update-assets' pk=idc.id %}";
    var body = {
        assets: Object.assign([], assets)
    };
	var $data_table = $("#idc_assets_table").DataTable();
	var success = function(data) {
		$data_table.ajax.reload();
    };
    APIUpdateAttr({
        url: the_url,
        body: JSON.stringify(body),
	    method: 'PUT',
        success: success
    });
}

$(document).ready(function () {
	$('.select2').select2()
	.on("select2:select", function (evt) {
		var data = evt.params.data;
		jumpserver.assets_selected[data.id] = data.text;
	})
	.on('select2:unselect', function(evt) {
		var data = evt.params.data;
		delete jumpserver.assets_selected[data.id];
	});
	var options = {
		ele: $('#idc_assets_table'),
		buttons: [],
		order: [],
		columnDefs: [
			{targets: 1, createdCell: function (td, cellData, rowData) {
				var detail_btn = '<a href="{% url "assets:asset-detail" pk=99991937 %}" data-aid="'+rowData.id+'">' + cellData + '</a>';
				$(td).html(detail_btn.replace('99991937', rowData.id));
			}},
			{targets: 5, 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>')
				}
			}}],
		ajax_url: '{% url "api-assets:asset-list" %}?idc_id={{ idc.id }}',
		columns: [{data: function(){return ""}}, {data: "hostname" }, {data: "ip" }, {data: "port" },
			{data: "type" }, {data: "is_active" }],
		op_html: $('#actions').html()
	};
	jumpserver.initDataTable(options);

})

.on('click', '.btn-asset-attach', function () {
	if (Object.keys(jumpserver.assets_selected).length === 0) {
		return false;
	}
	var assets=[];
	var $data_table = $("#idc_assets_table").DataTable();
	$.ajax({
		url: '{% url "api-assets:asset-list" %}',
		method: 'GET',
		data: {"idc_id": {{ idc.id }}},
		dataType: 'json',
		success: function (result) {
			for(var i in result){
				if (!isNaN(parseInt(result[i]['id']))) {
					assets.push(parseInt(result[i]['id']))
				}
			}
			$.map(jumpserver.assets_selected, function(value, index) {
				assets.push(parseInt(index));
			});
			updateIDCAssets(assets);

		}
	});
})

.on('click', '#btn_bulk_update', function () {
	var action = $("#slct_bulk_update").val();
	var $data_table = $("#idc_assets_table").DataTable();
	var id_list = [];
	var plain_id_list = [];
	var assets = [];
	$data_table.rows({selected: true}).every(function(){
        id_list.push({id: this.data().id});
        plain_id_list.push(this.data().id);
    });
    if (id_list === []) {
        return false;
    }
    $.ajax({
    	url: '{% url "api-assets:asset-list" %}',
	    data: {"idc_id": {{ idc.id }}},
	    dataType: 'json',
	    method: 'GET',
	    success: function (result) {
		    for (var i in result) {
		    	if (!isNaN(result[i]['id'])) {
		    		assets.push(result[i]['id']);
			    }
		    }
		    for (var j in plain_id_list) {
		    	assets.remove(plain_id_list[j])
		    }
		    function doDelete() {
				    swal({
		                title: "{% trans 'Are you sure?' %}",
		                text: "{% trans 'This will delete the selected assets !!!' %}",
		                type: "warning",
		                showCancelButton: true,
		                confirmButtonColor: "#DD6B55",
		                confirmButtonText: "{% trans 'Confirm' %}",
		                closeOnConfirm: false
		            }, function() {
		                var success = function() {
		                    var msg = "{% trans 'Asset Deleted.' %}";
		                    swal("{% trans 'Asset Delete' %}", msg, "success");
		                    $('#idc_assets_table').DataTable().ajax.reload();
		                };
		                var fail = function() {
		                    var msg = "{% trans 'Asset Deleting failed.' %}";
		                    swal("{% trans 'Asset Delete' %}", msg, "error");
		                };
		                var url_delete = "{% url 'api-assets:idc-update-assets' pk=idc.id %}";
		                var body = {
				            assets: Object.assign([], assets)
				        };
		            APIUpdateAttr({url: url_delete, body: JSON.stringify(body),  method: 'PUT', success: success, error: fail});
		            jumpserver.checked = false;
                });
		    }
		    function doUpdate() {
				$('#asset_bulk_update_modal').modal('show');
		    }
		    switch (action) {
		        case 'delete':
		            doDelete();
		            break;
		        case 'update':
		            doUpdate();
		            break;
		        default:
		            break;
		    }

	    }
    });
})

.on('click', '#btn_asset_bulk_update', function () {
	var json_data = $("#fm_asset_bulk_update").serializeObject();
	var body = {};
    body.enable_otp = (json_data.enable_otp === 'on')? true: false;
    if (json_data.type != '') {
        body.type = json_data.type;
    }

    if (json_data.groups != undefined) {
        body.groups = json_data.groups;
    }
    if (typeof body.groups === 'string') {
        body.groups = [parseInt(body.groups)]
    } else if(typeof body.groups === 'array') {
        var new_groups = body.groups.map(Number);
        body.groups = new_groups;
    }

    if (json_data.users != undefined) {
    	body.users = json_data.users;
    }
    if (typeof body.users === 'string') {
    	body.users = [parseInt(body.users)]
    } else if(typeof body.users === 'array') {
    	var new_users = body.users.map(Number);
    	body.users = new_users;
    }

    if (json_data.tags != undefined) {
    	body.tags = json_data.tags;
    }
    if (typeof body.tags == 'string') {
    	body.tags = [parseInt(body.tags)];
    } else if (typeof body.tags === 'array') {
    	var new_tags = body.tags.map(Number);
    	body.tags = new_tags;
    }

    var $data_table = $('#asset_list_table').DataTable();
    var post_list = [];
    $data_table.rows({selected: true}).every(function(){
        var content = Object.assign({id: this.data().id}, body);
        post_list.push(content);
    });
    if (post_list === []) {
        return false
    }
    var the_url = "{% url 'api-assets:asset-list' %}";
    var success = function() {
        var msg = "{% trans 'The selected assets has been updated successfully.' %}";
        swal("{% trans 'Asset Updated' %}", msg, "success");
        $('#asset_list_table').DataTable().ajax.reload();
        jumpserver.checked = false;
    };
    APIUpdateAttr({url: the_url, method: 'PATCH', body: JSON.stringify(post_list), success: success});
    $('#asset_bulk_update_modal').modal('hide');
});






</script>
{% endblock %}
