<div class="row form-horizontal">
    <div class="col-md-12">
        <h4><%= @product.name %></h4>
        <%= hidden_field_tag 'product_id', @product.id %>

        <% if @product.presentation? && @pointsales.present? %>
            <div class="form-group">
                <label class="col-md-3 control-label">Punto de venta</label>
                <div class="col-md-9">
                    <%= select_tag :pointsale_id, options_from_collection_for_select(@pointsales, :pointsale_id, :name), :include_blank => "Seleccione punto de venta",  class: "form-control select2 first_input", onchange: 'getAvailables()' %>
                    <span class="help-block">Una vez seleccionado el punto de venta la cantidad sugerida a imprimir es el stock de cada variante en el p.v.</span>
                </div>
                <br>
            </div>
        <% elsif !@product.presentation? && @product.pointsales.present? %>
            <div class="form-group">
                <label class="col-md-3 control-label">Punto de venta</label>
                <div class="col-md-9">
                    <%= select_tag :pointsale_id, options_from_collection_for_select(@product.pointsales, :id, :name), :include_blank => "Seleccione punto de venta",  class: "form-control select2 first_input", onchange: 'getAvailables()' %>
                    <span class="help-block">Una vez seleccionado el punto de venta la cantidad sugerida a imprimir es el stock del producto en el p.v.</span>
                </div>
                <br>
            </div>
        <% else %>
            <div class="alert alert-info">
               El producto no está asignado a un punto de venta, se imprimirán las etiquetas con el precio de venta base.
            </div>
        <% end %>

        <% if @product.presentation? %>
            <table id="variant_table_for_labels" class="table table-striped table-bordered table-advance table-hover">
                <thead>
                    <tr>
                        <th>Variante</th>
                        <th>Cantidad a imprimir</th>
                    </tr>
                </thead>
                <tbody>
                    <% @product.children.each do |variant| %>
                        <tr id="row_<%= variant.id %>">
                            <td>
                                <%= variant.display_attributes%>
                            </td>
                            <td>
                                <input type="number" min="0" class="form-control input-small" id="variant_<%= variant.id %>" value="0" pattern="^[0-9]*[1-9][0-9]*$" title="Cantidad de etiquetas a imprimir">
                            </td>
                        </tr>
                    <% end %>
                </tbody>
            </table>
        <% else %>
            <div class="form-group" style="margin-bottom:20px">
                <label class="col-md-3 control-label">Cantidad a imprimir</label>
                <div class="col-md-3" style="padding-top:10px" id="individual_prod_container">
                    <input type="number" id="quantity_to_print" value="0" class="form-control first_input">
                </div>
            </div>
        <% end %>
    </div>
</div>

<div class="form-actions">
    <div class="row">
        <div class="col-md-9">
            <button class="btn green" type="button" onclick="printLabels($(this))">Imprimir</button>
            <button class="btn default" type="button" onclick="cerrarDialog()">Cancelar</button>
        </div>
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function(){
        App.init();
    });

	function printLabels(button) {
        try {
            button.attr('disabled', true);
            var pointsale_id = "";
            var products = [];
            if($('#pointsale_id').length) {
                // está asignado a un P.V sacar pointsale_id
                pointsale_id = $('#pointsale_id').val();
                if(!pointsale_id) { throw "Selecciona punto de venta"; }
            }

            if($('#quantity_to_print').length) {
                // es producto sin variantes
                var product_id = $('#product_id').val();
                var obj = { id: product_id, print: parseFloat($("#quantity_to_print").val()) || 0 };
                products.push(obj);
            } else {
                // tiene variantes
                $('#variant_table_for_labels tbody tr').each(function(row) {
                    var idText = $(this).attr('id');
                    var product_id = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
                    var obj = { id: product_id, print: parseFloat($("#variant_" + product_id).val()) || 0 };
                    products.push(obj);
                });
            }

            var checkForZeroVal = products.some(function(p){
                return p.print > 0;
            });

            if(!checkForZeroVal) { throw "Indica la cantidad a imprimir."; }

            $.ajax({
                type: "POST",
                url: "print_labels",
                dataType: "script",
                data: {
                    products: JSON.stringify(products),
                    pointsale_id: pointsale_id
                },
                success: function(xhr, status, error) {
                    button.attr('disabled', false);
                    toastr["success"]("Etiquetas impresas correctamente.");
                    $('#dialog').modal('toggle');
                }
            });
        } catch(err) {
            button.attr('disabled', false);
            toastr["error"](err);
        }
	}

    function getAvailables() {
        var pointsale_id = $('#pointsale_id').val();
        var product_id = $('#product_id').val();
        var blockUI_target = "";
        var is_presentation_prod = $("#variant_table_for_labels").length ? true : false;
        if(pointsale_id) {
            blockUI_target = is_presentation_prod ? '#variant_table_for_labels' : '#individual_prod_container';

            App.blockUI({
                target: blockUI_target,
                animate: true
            });

            $.ajax({
                type: "get",
                url:  '/get_availables_by_product',
                dataType: 'json',
                data: {
                    pointsale_id: pointsale_id,
                    product_id: product_id
                },
                success: function(data) {
                    var availables = data;
                    if(is_presentation_prod) {
                        $('#variant_table_for_labels tbody tr').each(function(row) {
                            var idText = $(this).attr('id');
                            var product_id = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
                            var available = availables.find(function(a) {
                                return a.product_id == product_id;
                            });
                            if(available) {
                                $('#variant_' + available.product_id).val(parseFloat(available.stock));
                            } else {
                                $('#variant_' + product_id).val(0);
                            }
                        });


                        availables.forEach(function(available) {

                        });

                    } else {
                        $('#quantity_to_print').val(availables[0].stock);
                    }
                    App.unblockUI(blockUI_target);
                }
            });
        } else {
            if(is_presentation_prod) {
                $('#variant_table_for_labels tbody tr').each(function(row) {
                    $(this).find('input').val(0);
                });
            } else {
                $('#quantity_to_print').val(0);
            }
        }
    }

    function cerrarDialog() {
        $('#dialog').modal('toggle');
    }
</script>