{% extends "layout.html" %}
{% block head %}
    {{ super() }}
    <style type="text/css">
        .table {
            font-size: 12px;
            border-width: 1px;
            line-height: 20px;
        }
        .table > thead > tr > th,
        .table > tfoot > tr > th {
            color: #999999;
            font-weight: normal;
            border-bottom: 0 solid #e1e6eb;
            background-color: #F5F6FA;
        }
        
        .table > tbody > tr > td {
            color: #424547;
        }

        .table-bordered > tbody > tr {
            padding-top: 10px;
            padding-bottom: 10px;
        }

        .table-bordered > thead > tr > th,
        .table-bordered > tbody > tr > th,
        .table-bordered > tfoot > tr > th,
        .table-bordered > thead > tr > td,
        .table-bordered > tbody > tr > td,
        .table-bordered > tfoot > tr > td {
            border-style: solid;
            border-width: 1px 0 0 0;
        }

        .btn,
        .form-control,
        .modal-content {
            border-radius: 0 !important;
        }

        .tr-selected td,
        .tr-selected {
            color: #000 !important;
            background: #fffdf4 !important;
        }
    </style>

{% endblock head %}
{% block content %}

<script type="text/javascript">
    var page = 1;
    var page_size = 10;
    var keyword = '';
    var resource_path = window.location.pathname;
    var cur_url = resource_path;

    $(document).ready(function() {
        page_size = $('#page_size').val();
        cur_url = resource_path + '?page=' + page + '&page_size=' + page_size;

        var last_ready = null;
        $('#content_search').keydown(function() {
            if (last_ready !== null) {
                clearTimeout(last_ready);
            }
            last_ready = setTimeout(function () {
                keyword = $('#content_search').val();
                cur_url = resource_path + '?page=' + page + '&page_size=' + page_size;
                if (keyword.length > 0) {
                    cur_url = resource_path + '?page=' + page + '&page_size=' + page_size + '&keyword=' + keyword;
                }
                window.location.href=cur_url;
            }, 1000);
        });

        $('#page_size').change(function () {
            keyword = $('#content_search').val();
            page_size = $('#page_size').val();
            cur_url = resource_path + '?page=' + page + '&page_size=' + page_size;
            if (keyword.length > 0) {
                cur_url = resource_path + '?page=' + page + '&page_size=' + page_size + '&keyword=' + keyword;
            }
            window.location.href=cur_url;
        });

        $("thead").on('click', ".all_selector", function() {
            if ($("thead .all_selector").is(':checked')) {
                $("tbody tr").find('td input[type="checkbox"]:eq(0)').prop('checked', true);
                $(".all_selector").prop('checked', true);
            } else {
                $("tbody tr").find('td input[type="checkbox"]:eq(0)').prop('checked', false);
                $(".all_selector").prop('checked', false);
            }

            select_item_action();
        });

        $("tfoot").on('click', ".all_selector", function() {
            if ($("tfoot .all_selector").is(':checked')) {
                $("tbody tr").find('td input[type="checkbox"]:eq(0)').prop('checked', true);
                $(".all_selector").prop('checked', true);
            } else {
                $("tbody tr").find('td input[type="checkbox"]:eq(0)').prop('checked', false);
                $(".all_selector").prop('checked', false);
            }

            select_item_action();
        });

        $("tbody tr").on('click', "input[type='checkbox']", function() {
            select_item_action();
        });

        $('body').addClass('add-transition');
        $('.add-page-transition').on('click', function(){
            var transAttr = $(this).attr('data-transition');
            $('.add-transition').attr('class', 'add-transition');
            $('.add-transition').addClass(transAttr);
        });
    });

    function get_selected_element(checked) {
        if (checked === null) {
            checked = true;
        }

        if (checked) {
            return $('tbody :checked');
        } else {

            return $('tbody input:not(:checked)');
        }
    }

    function highlight_selected_element() {
        var selected_element = get_selected_element(true);
        var no_selected_element = get_selected_element(false);

        selected_element.each(function(i, e) {
            $(e).parent().parent().toggleClass('tr-selected', true);
        });

        no_selected_element.each(function(i, e) {
            $(e).parent().parent().toggleClass('tr-selected', false);
        });
    }

    function shortcut_bar_enable() {
        var selected_element = get_selected_element(true);

        if (selected_element.length > 0) {
            $('.btn-shortcut').toggleClass('disabled', false);
        } else {
            $('.btn-shortcut').toggleClass('disabled', true);
        }
    }

    function select_item_action() {
        highlight_selected_element();
        shortcut_bar_enable();
    }

    function refresh() {
        page = $('#pagination li.active a').text();
        page_size = $('#page_size').val();
        cur_url = resource_path + '?page=' + page + '&page_size=' + page_size;
        window.location.href=cur_url;
    }

    function remove(uuid, boot_job_id, do_refresh) {
        $.ajax({
            url : '/api/guests/_boot_jobs/' + uuid + '/' + boot_job_id,
            type : 'DELETE',
            contentType: "application/json; charset=utf-8",
            error : function() {
                alter_danger('启动作业删除指令发送失败！');
            },
            success : function() {
                // 未指定值的参数为 undefined
                if (do_refresh) {
                    alter_success('启动作业删除指令发送成功！');
                    refresh();
                }
            }
        });
    }

    function delete_at(me) {
        var uuid = $('#instance_uuid').val();
        var boot_job_id = $('#instance_boot_job_id').val();
        remove(uuid, boot_job_id, true);
        $('#delete_modal').modal('hide');
    }

    function get_selected_uuids_and_boot_jobs_id() {
        var selected_element = get_selected_element(true);
        var uuids = [];
        var boot_jobs_id = [];

        selected_element.each(function(i, e) {
            var uuid = $(e).parent().prev().prev().text();
            var boot_job_id = $(e).parent().prev().text();
            uuids.push(uuid);
            boot_jobs_id.push(boot_job_id);
        });

        return {'uuids': uuids, 'boot_jobs_id': boot_jobs_id};
    }

    function get_checked_uuids_and_boot_jobs_id() {
        var uuids_and_boot_jobs_id = get_selected_uuids_and_boot_jobs_id();

        if (uuids_and_boot_jobs_id['uuids'].length < 1) {
            alter_warning('未选择任何可操作的实例！');
            return false;
        }

        return uuids_and_boot_jobs_id;
    }

    function batch_delete() {
        var uuids_and_boot_jobs_id = get_checked_uuids_and_boot_jobs_id();
        if (uuids_and_boot_jobs_id['uuids'] && uuids_and_boot_jobs_id['boot_jobs_id']) {
            for (var i=0; i<uuids_and_boot_jobs_id['uuids'].length; i++) {
                if (i === uuids_and_boot_jobs_id['uuids'].length  - 1) {
                    remove(uuids_and_boot_jobs_id['uuids'][i], uuids_and_boot_jobs_id['boot_jobs_id'][i], true);
                } else {
                    remove(uuids_and_boot_jobs_id['uuids'][i], uuids_and_boot_jobs_id['boot_jobs_id'][i], false);
                }
            }
        }
        $('#batch_delete_modal').modal('hide');
    }
</script>
<div class="panel">
    <div class="panel-body">
        <h3 class="title-hero" style="font-size: 24px;">
            虚拟机启动作业
        </h3>
        <div>
            <div id="datatable-row-highlight_wrapper" class="dataTables_wrapper form-inline">
                <div class="row" style="padding: 10px 10px 10px 0; width: 100%;">
                    <div class="col-sm-12" style="padding-right: 0;">
                        <div class="pull-right">
                            <button class="btn btn-default" onclick="refresh()" style="border-radius: 0;"><span class="glyph-icon icon-elusive-arrows-cw"></span></button>
                        </div>
                    </div>
                </div>
                <table id="guests_boot_jobs_list" class="table table-bordered table-hover" cellspacing="0" width="100%" role="grid"
                       style="width: 100%; margin-bottom: 0; border-bottom-width: 0;">
                <thead>
                <tr role="row">
                    <th style="display: none;">UUID</th>
                    <th style="display: none;">启动作业 ID</th>
                    <th><input class="all_selector" title="选取所有" type="checkbox"></th>
                    <th width="180px;">有效时间</th>
                    <th width="180px;">启动作业</th>
                    <th width="180px;">名称</th>
                    <th></th>
                    <th>状态</th>
                    <th>IP</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                {% for uuid, boot_jobs in guests_boot_jobs_ret.data.iteritems() %}
                    {% for boot_job_id in boot_jobs.boot_jobs %}
                    <tr role="row" class="odd">
                        <td style="display: none;">{{ uuid }}</td>
                        <td style="display: none;">{{ boot_job_id }}</td>
                        <td><input title="选中" type="checkbox"></td>
                        <td>
                            <span style="color: #b94a48; {% if boot_jobs.ttl // 60 == 0 %}display: none;{% endif %}">{{ boot_jobs.ttl // 60 }}分</span>
                            <span style="color: #b94a48; {% if boot_jobs.ttl % 60 == 0 %}display: none;{% endif %}">{{ boot_jobs.ttl % 60 }}秒</span>
                        </td>
                        <td>
                            <div>
                                <a href="/operate_rules?boot_job_id={{ boot_job_id }}">
                                    <p style="display: inline-block;">{{ boot_jobs_mapping_by_id[boot_job_id | int].name }}</p>
                                </a>
                            </div>
                        </td>
                        <td>
                            <div>
                                <a href="/guest/detail/{{ uuid }}">
                                    <p style="display: inline-block;">
                                        {{ guests_mapping_by_uuid[uuid].label }}
                                    </p>
                                </a>
                                <div>
                                    <p style="display: inline-block;">{{ guests_mapping_by_uuid[uuid].remark }}</p>
                                </div>
                            </div>
                        </td>
                        <td><span class="{{ os_templates_mapping_by_id[guests_mapping_by_uuid[uuid].os_template_id].icon }}"></span></td>
                        <td>{{ format_guest_status(guests_mapping_by_uuid[uuid].status)|safe }}</td>
                        <td>{{ guests_mapping_by_uuid[uuid].ip }}</td>
                        <td>
                            <div class="dropdown inline-block">
                                <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
                                    更多
                                </a>
                                <ul class="dropdown-menu">
                                    <li>
                                        <a href="javascript:;" data-toggle="modal" data-target="#delete_modal"
                                            onclick="$('#instance_uuid').val($(this).parent().parent().parent().parent().parent().children()[0].textContent);
                                                $('#instance_boot_job_id').val($(this).parent().parent().parent().parent().parent().children()[1].textContent);
                                                $('#delete_instance_desc').text($($(this).parent().parent().parent().parent().parent().children()[5]).find('div a')[0].text);
                                                $('#delete_instance_desc').append('/' + $($(this).parent().parent().parent().parent().parent().children()[4]).find('div a')[0].text)">
                                            删除
                                        </a>
                                    </li>
                                </ul>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                {% endfor %}
                </tbody>
                </table>

                <table class="table table-bordered" style="border-top-width: 0; z-index: 99; position: sticky; bottom: 0;">
                    <tfoot>
                    <tr style="height: 70px;">
                        <th><input type="checkbox" title="选取所有" class="all_selector"></th>
                        <th>
                            <div class="row">
                                <div class="col-sm-6">
                                    <button class="btn btn-default btn-shortcut disabled" data-toggle="modal" data-target="#batch_delete_modal">删除</button>
                                </div>
                                <div class="col-sm-3" style="font-size: 12px; padding-top: 5px; text-align: right;">
                                    共有{{ paging_total }}个，每页显示：
                                    <select id="page_size" name="datatable-row-highlight_length" title="page_size" class="form-control" style="height: 22px; vertical-align: baseline;">
                                        <option value="10" {% if page_size == 10 %} selected {% endif %}>10</option>
                                        <option value="20" {% if page_size == 20 %} selected {% endif %}>20</option>
                                        <option value="50" {% if page_size == 50  %} selected {% endif %}>50</option>
                                    </select>&nbsp;&nbsp;个
                                </div>
                                <div class="col-sm-3" style="text-align: left;">
                                    <div class="dataTables_paginate paging_bootstrap" id="datatable-row-highlight_paginate">
                                        <ul id="pagination" class="pagination">
                                            <li class="{% if page == 1 %} disabled {% endif %}">
                                                <a href="{{ resource_path }}?page={{ page - 1 }}&page_size={{ page_size }}{% if keyword %}&keyword={{ keyword }}{% endif %}">«</a>
                                            </li>
                                            {% for item in pages %}
                                                <li class="{% if item == page %} active {% endif %}">
                                                    <a href="{{ resource_path }}?page={{ item }}&page_size={{ page_size }}{% if keyword %}&keyword={{ keyword }}{% endif %}">{{ item }}</a>
                                                </li>
                                            {% endfor %}
                                            <li class="{% if page == last_page %} disabled {% endif %}">
                                                <a href="{{ resource_path }}?page={{ page + 1 }}&page_size={{ page_size }}{% if keyword %}&keyword={{ keyword }}{% endif %}">»</a>
                                            </li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </th>
                    </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</div>

<input id="instance_uuid" title="实例 UUID" class="form-control" name="uuid" hidden>
<input id="instance_boot_job_id" title="实例启动作业 ID" class="form-control" name="boot_job_id" hidden>

<div class="modal" id="delete_modal" tabindex="-1" role="dialog" style="margin-top: 100px;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">删除启动作业：</h4>
            </div>
            <div class="modal-body">
                <p>你确定要删除该启动作业吗？</p>
                <h3 style="color: orangered;" id="delete_instance_desc"></h3>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-primary" onclick="delete_at();">确定</button>
                <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<div class="modal" id="batch_delete_modal" tabindex="-1" role="dialog" style="margin-top: 100px;">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">批量删除启动作业：</h4>
            </div>
            <div class="modal-body">
                <p>您确定要执行批量删除选择的启动作业吗？</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-sm btn-primary" onclick="batch_delete();">确定</button>
                <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>
{% endblock content %}
