{% extends '_base_list.html' %}
{% load i18n %}
{% load static %}
{% load common_tags %}
{% block custom_head_css_js %}
    <link href="{% static 'css/plugins/datepicker/datepicker3.css' %}" rel="stylesheet">
    <style>
        .toggle {
            cursor: pointer;
        }
        .detail-key {
            width: 70px;
        }
    </style>
{% endblock %}

{% block table_pagination %}
{% endblock %}

{% block table_search %}
{% endblock %}

{% block table_container %}
    <table class="table table-striped table-bordered table-hover" id="command_table" data-page="false" >
        <thead>
        <tr>
            <th></th>
            <th>{% trans 'Command' %}</th>
            <th>{% trans 'User' %}</th>
            <th>{% trans 'Asset' %}</th>
            <th>{% trans 'System user'%}</th>
            <th>{% trans 'Session' %}</th>
            <th>{% trans 'Datetime' %}</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="export">{% trans 'Export command' %}</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 class="hide" id="daterange">
        <div class="form-group p-l-5" id="date" style="padding-left: 5px">
        <div class="input-daterange input-group p-l-5" id="datepicker">
            <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
            <input type="text" class="input-sm form-control" style="width: 100px;" id="date_from" name="date_from" value="{{ date_from|date:'Y-m-d' }}">
            <span class="input-group-addon">to</span>
            <input type="text" class="input-sm form-control" style="width: 100px;" id="date_to" name="date_to" value="{{ date_to|date:'Y-m-d' }}">
        </div>
        </div>
    </div>

    <ul class="dropdown-menu search-help">
        <li><a class="search-item" data-value="user">{% trans 'User' %}</a></li>
        <li><a class="search-item" data-value="asset">{% trans 'Asset' %}</a></li>
        <li><a class="search-item" data-value="system_user">{% trans 'System user' %}</a></li>
        <li><a class="search-item" data-value="input">{% trans 'Command' %}</a></li>
    </ul>
{% endblock %}
{% block content_bottom_left %}{% endblock %}
{% block custom_foot_js %}
<script src="{% static 'js/plugins/datepicker/bootstrap-datepicker.js' %}" charset="UTF-8"></script>
<script src="{% static 'js/plugins/datepicker/bootstrap-datepicker.zh-CN.min.js' %}" ></script>
<script>

var table;
$(document).ready(function () {
    table = initTable().on("init", function () {
        var dateFromRef = $("#date_from");
        var dateToRef = $("#date_to");
        var options = {
            format: "yyyy-mm-dd",
            todayBtn: "linked",
            keyboardNavigation: false,
            forceParse: false,
            calendarWeeks: true,
            autoclose: true,
            language: navigator.language || "en",
        };
        dateFromRef.datepicker(options).on("changeDate", function () {
            var value = $(this).val() + ' 0:0:0';
            var date = safeDate(value);
            var url = table.ajax.url();
            url = setUrlParam(url, "date_from", date.getTime()/1000);
            table.ajax.url(url);
            table.ajax.reload();
        });
        dateToRef.datepicker(options).on("changeDate", function () {
            var value = $(this).val() + ' 23:59:59';
            var date = safeDate(value);
            var url = table.ajax.url();
            url = setUrlParam(url, "date_to", date.getTime()/1000);
            table.ajax.url(url);
            table.ajax.reload();
        });
    });
})
.on('click', '#btn_bulk_update', function(){
    // var action = $('#slct_bulk_update').val();
    var params = getUrlParams(table.ajax.url());

    var exportPath = "{% url 'api-terminal:command-export' %}";
    var url = exportPath + "?" + params;
    window.open(url);
}).on("click", '#command_table_filter input', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var offset1 = $('#command_table_filter input').offset();
    var x = offset1.left;
    var y = offset1.top;
    var offset = $(".search-help").parent().offset();
    x -= offset.left;
    y -= offset.top;
    x += 18;
    y += 80;
    $('.search-help').css({"top":y+"px", "left":x+"px", "position": "absolute"});
    $('.dropdown-menu.search-help').show();
})
.on('click', '.search-item', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var keyword = $("#command_table_filter input");
    var value = $(this).data('value');
    var old_value = keyword.val();
    var new_value = old_value + ' ' + value + ':';
    keyword.val(new_value.trim());
    $('.dropdown-menu.search-help').hide();
    keyword.focus()
})
.on('click', 'body', function (e) {
    $('.dropdown-menu.search-help').hide()
})
.on('click', '.toggle', function (e) {
    e.preventDefault();
    var detailRows = [];
    var tr = $(this).closest('tr');
    var row = table.row(tr);
    var idx = $.inArray(tr.attr('id'), detailRows);

    if (row.child.isShown()) {
        tr.removeClass('details');
        $(this).children('i:first-child').removeClass('fa-angle-down').addClass('fa-angle-right');
        row.child.hide();

        // Remove from the 'open' array
        detailRows.splice(idx, 1);
    } else {
        tr.addClass('details');
        $(this).children('i:first-child').removeClass('fa-angle-right').addClass('fa-angle-down');
        row.child(format(row.data())).show();
        // Add to the 'open' array
        if (idx === -1) {
            detailRows.push(tr.attr('id'));
        }
    }
});


function format(d) {
    var output = $("<pre style='border: none; background: none'></pre>");

    output.append('$ ', d.input);
    output.append('\r\n\r\n');
    output.append(d.output);
    return output
}

var commandListUrl = '{% url "api-terminal:command-list" %}';
var dateFrom = "{{ date_from.timestamp }}";
var dateTo = "{{ date_to.timestamp }}";

function initTable() {
    commandListUrl = setUrlParam(commandListUrl, "date_from", dateFrom);
    commandListUrl = setUrlParam(commandListUrl, "date_to", dateTo);
    var options = {
        ele: $('#command_table'),
        columnDefs: [
            {targets: 0, createdCell: function (td, cellData, rowData) {
                $(td).addClass("toggle");
                $(td).html("<i class='fa fa-angle-right'></i>");
            }},
            {targets: 1, createdCell: function (td, cellData) {
                var data = htmlEscape(cellData);
                var interHtml = $("<span></span>");
                if (data.length > 40) {
                    interHtml.attr('title', data);
                    data = data.slice(0, 40);
                    data += ' ...';
                }
                interHtml.html(data);
                $(td).html(interHtml);
            }},
            {targets: 5, createdCell: function (td, cellData) {
                var data = '<a href="{% url "terminal:session-detail" pk=DEFAULT_PK %}">{% trans "Goto" %}</a>'
                        .replace('{{ DEFAULT_PK }}', cellData);
                $(td).html(data);
            }},
            {targets: 6, createdCell: function (td, cellData) {
                var data = toSafeLocalDateStr(cellData*1000);
                $(td).html(data);
            }},
        ],
        toggle: true,
        ajax_url: commandListUrl,
        columns: [
            {data: "id"}, {data: "input", orderable: false, width: "40%"}, {data: "user", orderable: false},
            {data: "asset", orderable: false}, {data: "system_user", orderable: false},
            {data: "session", orderable: false}, {data: "timestamp", width: "160px", orderable: false},
        ],
        select: {},
        op_html: $('#actions').html(),
        fb_html: $("#daterange").html(),
    };
    table = jumpserver.initServerSideDataTable(options);
    return table
}
</script>
{% endblock %}


