{% extends "common.html" %}
{% block title %}{{title}}{% endblock %}
{% block head %}
  {{ super() }}
{% endblock %}

{% block page %}{{title}}{% endblock %}
{% block content %}
<script type="text/javascript">
    $(function() {
        $('body').on("click", ".Request", function () {
            var action = "";
            var request_id = $(this).attr('id');
            var loader_alert = $('#statusAlert');
            if ($(this).hasClass('editShooting')) {
                location.href = location.href.split('?')[0] + '?mode=form' + "&request_id=" + request_id;
                return false
            }
            else if ($(this).hasClass('deleteShooting')){
                action = "delete_shooting";
            }
            else {
                action = "turn_shooting";
            }

            $.ajax({
              url: '/update_shooting',
              data: JSON.stringify({request_id: request_id, action: action }),
              type: 'POST',
              success: function (response) {
                  var answer = JSON.parse(response);
                  if (!jQuery.isEmptyObject(answer.error)) {
                      loader_alert.addClass('alert-danger').removeClass('alert-info');
                      loader_alert.html("<strong>" + answer.error + "</strong>");
                  } else {
                      loader_alert.addClass('alert-success').removeClass('alert-info').removeClass('alert-danger');
                      loader_alert.html('Параметры стрельбы успешно изменены');
                  }
                  updateStatus();
              },
              error: function (error) {
                  console.log('error!');
                  console.log(error);
              }
            });
        });

        $('form .form-group.requests_info_find_by').hide();

        $('#store_requests_info').change(function () {
            if (this.checked) {
                $('form .form-group.requests_info_find_by').show();
            } else {
                $('form .form-group.requests_info_find_by').hide();
            }
        });

        $('.form-horizontal').submit(function () {
            var shootingType;
            var formFields = $(this).serializeArray();
            var loader_alert = $('#statusAlert');

            if ($(this).hasClass('custom-shooting-form')) {
                shootingType = 'custom';
            }
            else {
                shootingType = 'regular';
            }

            $('.loader').show();
            loader_alert.html('Ваш запрос обрабатывается');

            $.ajax({
                url: '/request',
                data: 'request_type=' + shootingType + '_shooting&' + $(this).serialize(),
                type: 'POST',
                timeout: 6000000,
                beforeSend: function () {
                    $('#statusAlert').removeClass('alert-danger').removeClass('alert-success').addClass('alert-info');
                    $('#statusAlert').show();
                    $.each(formFields, function (index, value) {
                        if (value.name != csrf_token) {
                            $('.' + shootingType + '-shooting-form .' + value.name).removeClass('has-danger');
                            $('.' + shootingType + '-shooting-form .' + value.name + ' .textError').empty();
                        }
                    });
                },
                success: function (response) {
                    var answer = JSON.parse(response);
                    if (!jQuery.isEmptyObject(answer.form_errors)) {
                        console.log(answer.form_errors);
                        loader_alert.addClass('alert-danger').removeClass('alert-info');
                        loader_alert.html("Во время проверки формы произошли ошибки. Исправьте их и попробуйте снова");
                        $.each(answer.form_errors, function (class_id, text) {
                            $('.' + shootingType + '-shooting-form .' + class_id).addClass('has-danger');
                            $('.' + shootingType + '-shooting-form .' + class_id + ' .textError').html(
                                "<div class='col-form-label text-danger'>" + text + "</div>").show();
                        });
                    } else if (!jQuery.isEmptyObject(answer.error)) {
                        loader_alert.addClass('alert-danger').removeClass('alert-info');
                        loader_alert.html("<strong>" + answer.error + "</strong>");
                    } else {
                        loader_alert.addClass('alert-success').removeClass('alert-info');
                        loader_alert.html("<strong>" + answer.task + "</strong>");
                    }
                },
                error: function (error) {
                    console.log('error!');
                    console.log(error);
                }
            });
            return false
        });
    });
</script>
<div class="loader alert alert-info" style="display: none" id="statusAlert">
    <p>Заявка обрабатывается, ожидайте. Если сообщение висит слишком долго, значит что-то пошло не так.</p>
</div>
<ul id="typeSelector" class="nav nav-tabs">
    <li class="nav-item">
        <a class="nav-link" href="#custom" data-toggle="tab">custom</a>
    </li>
    <li class="nav-item">
        <a class="nav-link active" href="#regular" data-toggle="tab">regular</a>
    </li>
</ul>
<div class="tab-content">
    <div class="tab-pane fade" id="custom">
        {{ macro.render_shooting_form(custom_form) }}
    </div>
    <div class="tab-pane fade show active" id="regular">
        {% if mode == 'form' %}
          {{ macro.render_regular_shooting_form(regular_form) }}
        {% endif %}
        {% if mode == 'table' %}
        <script>
                var loader_alert = $('#statusAlert');
                $('.loader').show();
                loader_alert.html('Таблица стрельб загружается, пожалуйста, подождите');
        </script>
        <div id="shootingTable">
        </div>
        <script>
        var shooting_table = $('#shootingTable');
        var loader_alert = $('#statusAlert');
        $.ajax({
              url: '/shoot_to_service',
              type: 'POST',
              success: function (response) {
                  var answer = JSON.parse(response);
                  shooting_table.html(answer.shooting_table);
                  $('.loader').hide();
              },
              error: function (error) {
                  loader_alert.addClass('alert-danger').removeClass('alert-info');
                  loader_alert.html('Загрузка не удалась');
                  console.log('error!');
                  console.log(error);
              }
            });
        </script>
        {% endif %}
    </div>
</div>
<script>
        let source_service_error = $('.custom-shooting-form .' + 'ammo_file' + ' .textError');
        let ammo_file_div = $('.custom-shooting-form .' + 'ammo_file');
        $(document).on('keyup','#ammo_file',function(){
        if (this.value.length > 1 && !ammo_file_div.hasClass('has-danger')){
            source_service_error.html("<div class='col-form-label text-warning'>" + "Обратите внимание, что таска не умеет подменять сервис для обстрела в готовых патронах" + "</div>").show();
        }
        else {
            if (!ammo_file_div.hasClass('has-danger'))
                source_service_error.html("").show();
        }
        });
</script>
<footer class="navbar-fixed-bottom navbar-light">
    <br>
    <p class="text-left"><a href="https://wiki.yandex-team.ru/jandekspoisk/saas/Saas-FAQ/#strelbyvsaasservisy">Подробнее о проведении нагрузочных учений</a></p>
</footer>
{% endblock %}
