{% extends "kfet/base_col_1.html" %}
{% load static widget_tweaks %}


{% block title %}Nouvel inventaire{% endblock %}
{% block header-title %}Création d'un inventaire{% endblock %}

{% block main-size %}col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2{% endblock %}

{% block main %}

<form id='inventoryform' action="" method="post">
  <div class="table-responsive">
  <table class="table table-hover table-condensed table-condensed-input text-center">
    <thead>
      <tr>
        <td>Article</td>
        <td>Quantité par caisse</td>
        <td>Stock théorique</td>
        <td>Caisses en réserve</td>
        <td>Caisses en arrière</td>
        <td>Vrac</td>
        <td>Stock total</td>
        <td>Compte terminé</td>
      </tr>
    </thead>
    <tbody>
      {% for form in formset %}
		{% ifchanged form.is_sold %}
        <tr class='section'>
			  <td>{% if form.is_sold %} Vendu {% else %} Non vendu {% endif %}</td>
          <td colspan="7"></td>
        </tr>
      {% endifchanged %}
      {% ifchanged form.category %}
        <tr class='section'>
          <td>{{ form.category_name }}</td>
          <td colspan="7"></td>
        </tr>
      {% endifchanged %}
      <tr>
        {{ form.article }}
        <td class='name text-left'>{{ form.name }}</td>
        <td class='box_capacity'>{{ form.box_capacity }}</td>
        <td>
          <span class='current_stock'>{{ form.stock_old }}</span><span class='stock_diff'></span>
        </td>
        <td class='box_cellar nopadding'>
          <input type='number' class='form-control' step='1'>
        </td>
        <td class='box_bar nopadding'>
          <input type='number' class='form-control' step='1'>
        </td>
        <td class='misc nopadding'>
          <input type='number' class='form-control' step='1'>
        </td>
        <td class='stock_new nopadding'>
          {{ form.stock_new | attr:"readonly"| add_class:"form-control" }}
        </td>
        <td class='finished'>
          <div class="inventory_update">
            <button type='button' class='btn-sm btn-primary'>MàJ</button>
          </div>
          <div class="inventory_done">
            <input type='checkbox' class='form_control'>
          </div>
        </td>
      </tr>
      {% endfor %}
      <tr class="section">
        <td>Totaux</td>
        <td colspan="2"></td>
        <td class="total_box_cellar"></td>
        <td class="total_box_bar"></td>
        <td colspan="3"></td>
      </tr>
    </tbody>
  </table>
  </div>
  {{ formset.management_form }}
  {% if not perms.kfet.add_inventory %}
  <div class='auth-form form-horizontal'>
    {% include "kfet/form_authentication_snippet.html" %}
  </div>
  {% endif %}
  <input type="submit" value="Enregistrer" class="btn btn-primary btn-lg btn-block">
  {% csrf_token %}
</form>

<script type="text/javascript">
function init_total(type) {
    update_total(type);
    $('.'+type+' input').on('input', () => update_total(type));
}

function update_total(type) {
    var total = 0;
    $('.'+type+' input').each(function() {
        total += +$(this).val();
    });
    $('.total_'+type).text(total);
}

$(document).ready(function() {
    'use strict';

    var conflicts = new Set();

    /**
     * Autofill new stock from other inputs
     */

    $('input[type="number"]').on('input', function() {
        var $line = $(this).closest('tr');
        var box_capacity = +$line.find('.box_capacity').text();
        var box_cellar = $line.find('.box_cellar input').val();
        var box_bar = $line.find('.box_bar input').val();
        var misc = $line.find('.misc input').val();
        if (box_cellar || box_bar || misc)
            $line.find('.stock_new input').val(
                box_capacity*((+box_cellar) +(+box_bar))+(+misc));
        else
            $line.find('.stock_new input').val('');
    });

    /*
     * Remove warning and update stock
     */

    function update_stock($line, update_count) {
        $line.removeClass('inventory_modified');
        $line.find('.inventory_update').hide();
        $line.find('.inventory_done').show();

        var old_stock = +$line.find('.current_stock').text()
        var stock_diff = +$line.find('.stock_diff').text();
        $line.find('.current_stock').text(old_stock + stock_diff);
        $line.find('.stock_diff').text('');

        if ($line.find('.stock_new input').val() && update_count) {
            var old_misc = +$line.find('.misc input').val();
            $line.find('.misc input').val(old_misc + stock_diff)
                                     .trigger('input');
        }

        var id = $line.find('input[type="hidden"]').val();
        conflicts.delete(parseInt(id));
    }

    $('.finished input').change(function() {
        var $line = $(this).closest('tr');
        update_stock($line, false);
    });

    $('.inventory_update button').click(function() {
        var $line = $(this).closest('tr');
        update_stock($line, true);
    });

    /**
     * Total row
     */

    init_total('box_cellar');
    init_total('box_bar');

    /**
     * Websocket
     */

    OperationWebSocket.add_handler(function(data) {
        for (let article of data['articles']) {
            var $line = $('input[value="'+article.id+'"]').parent();
            if ($line.find('.finished input').is(":checked")) {
                conflicts.add(article.id);
                //Display warning
                $line.addClass('inventory_modified');

                //Realigning input and displaying update button
                $line.find('.inventory_update').show();
                $line.find('.inventory_done').hide();

                //Displaying stock changes
                var stock = $line.find('.current_stock').text();
                $line.find('.stock_diff').text(article.stock - stock);
            } else {
                // If we haven't counted the article yet, we simply update the expected stock
                $line.find('.current_stock').text(article.stock);
            }
        }
    });

    $('input[type="submit"]').on("click", function(e) {
        e.preventDefault();

        var content;

        if (conflicts.size) {
            content = '';
            content += "Conflits possibles :"
            content += '<ul>';
            for (let id of conflicts) {
                var $line = $('input[value="'+id+'"]').closest('tr');
                var name = $line.find('.name').text();
                var stock_diff = $line.find('.stock_diff').text();
                content += '<li>'+name+' ('+stock_diff+')</li>';
            }
            content += '</ul>'
        } else {
            // Prevent erroneous enter key confirmations
            // Kinda complicated to filter if click or enter key...
            content="Voulez-vous confirmer l'inventaire ?";
        }

        $.confirm({
            title: "Confirmer l'inventaire",
            content: content,
            backgroundDismiss: true,
            animation: 'top',
            closeAnimation: 'bottom',
            keyboardEnabled: true,
            confirm: function() {
                $('#inventoryform').submit();
            },
            onOpen: function() {
                var that = this;
                this.$content.find('input').on('keydown', function(e) {
                    if (e.keyCode == 13)
                        that.$confirmButton.click();
                });
            },
        });

    });


});
</script>

{% endblock %}
