<%= form_for(@transfer, html: { class: "form-horizontal", id: "transfer_form" }) do |f| %>
  <div class="portlet-body form">
    <% if @transfer.errors.any? %>
      <div class="alert alert-danger">
        <strong>Tiene <%= pluralize(@transfer.errors.count, "error") %> no se puede guardar el traspaso</strong><br>
        <ul>
          <% @transfer.errors.values.each do |message| %>
            <li><%= message.first.to_s %></li>
          <% end %>
        </ul>
      </div>
    <% end %>
    <div class="row">
      <!-- boton para resetear datos -->
      <div class="col-md-offset-10 col-md-2">
        <button id="reset_pre_transfers" type="button" class="btn btn-warning" <%= 'disabled' if @pre_transfers.blank? %> onclick="deletePreTransfers()">Restaurar traspaso</button>
      </div>
      <div class="col-md-7">
        <!-- fecha -->
        <div class="form-group">
          <%= f.label :transfer_date, "Fecha", {:class=>"col-md-3 control-label"} do %> Fecha
          <span class="required">*</span>
          <% end %>
            <%= f.hidden_field :transfer_date, {:value=>Date.today} %>
              <div class="col-sm-6" style="padding-left:0px;padding-right:0px;">
                  <div class='input-group date' id='datetimepicker1'>
                      <input type='text' class="form-control" disabled/>
                      <span class="input-group-addon">
                          <span class="glyphicon glyphicon-calendar"></span>
                      </span>
                  </div>
              </div>
        </div>
        <!-- origen -->
        <div class="form-group">
          <%= f.label :origin_id, "Punto de venta", {:class=>"col-md-3 control-label"} do %>Origen
          <span class="required">*</span>
          <% end %>
          <div class="input-group col-md-6 select2-bootstrap-prepend">
            <%= f.select :origin_id, grouped_options_for_select([
              ['Puntos de venta',  Pointsale.activos.collect { |p| [ p.name, ('P-' + p.id.to_s) ] }],
              ['Almacenes', Warehouse.activos.collect { |w| [ w.name, ('W-' + w.id.to_s)] }]], :selected => @origin_id), {:prompt => "Seleccione"}, { :class => 'form-control select2', :disabled => @disable_origin} %>
            <%= f.hidden_field :origin_id, :value => @origin_id, :id => 'origin_id' %>
          </div>
        </div>
        <!-- destino -->
        <div class= "form-group">
          <%= f.label :destiny_id, "Punto de venta", {:class=>"col-md-3 control-label"} do %>Destino
          <span class="required">*</span>
          <% end %>
          <div class="input-group col-md-6 select2-bootstrap-prepend">
            <%= f.select :destiny_id, grouped_options_for_select([
              ['Puntos de venta',  @destiny_pointsales.collect { |p| [ p.name, ('P-' + p.id.to_s)] }],
              ['Almacenes', Warehouse.activos.collect { |w| [ w.name, ('W-' + w.id.to_s)] }]], :selected => @destiny_id), {:prompt => "Seleccione"}, { :class => 'form-control select2', :disabled => @disable_destiny} %>
            <%= f.hidden_field :destiny_id, :value => @destiny_id, :id => 'destiny_id' %>
          </div>
        </div>
      </div>
    </div>

    <!-- agregar productos -->
    <h4 class="form-section">Producto(s) a traspasar</h4>
    <div class="row">
      <div class='col-md-12'>
        <div class="form-group">
          <label class="col-md-2 control-label" for="typeahead"> Producto
            <span class="required">*</span>
          </label>
          <div class="col-md-4">
            <input class="form-control" type="text" id="typeahead">
          </div>
          <button id="products_new" disabled class="btn btn-success" type="button" onclick="addRow()"> Agregar <i class="fa fa-plus"></i> </button>
        </div>
      </div>
    </div>

    <!-- lista de productos -->
    <h4 class="form-section"> </h4>
    <div class="portlet-body">
      <table class="table table-striped table-bordered table-hover tableadvanced" id="products_table">
        <thead>
          <tr>
            <th width="5%">#</th>
            <th width="20%">Imagen</th>
            <th width="20%">SKU</th>
            <th width="15%">Producto</th>
            <th>Stock actual</th>
            <th width="20%">Cantidad</th>
            <th width="10%">Acciones</th>
          </tr>
        </thead>
        <tbody>
          <%= render @pre_transfers %>
        </tbody>
      </table>
    </div>

    <!-- acciones del form -->
    <div class="form-actions">
      <div class="row">
        <div class="col-md-9">
          <!-- < %= f.submit 'Guardar', { class: "btn green", disabled: (@pre_transfers.present? ? false : true), id: "save_transfer" } %> -->
          <button type="button" class="btn green" onclick="addTransfer()" id="save_transfer" <%= 'disabled' if @pre_transfers.blank? %>>Guardar</button>
          <%= link_to 'Cancelar', transfers_path(filter: @filter, current_page: @current_page), { class: "btn default" } %>
        </div>
      </div>
    </div>
  </div>
<% end %>

<script type="text/javascript">
  var selectedProduct;
  var timeout = null;

  function addTransfer() {
    var origin = $('#origin_id').val();
    var destiny = $('#destiny_id').val();
    if((origin && destiny) && (origin != destiny)) {
      $("#transfer_form").submit();
    } else {
      toastr["error"]("Falta seleccionar datos del formulario, o el origen y el destino son los mismos.");
    }
  }

  $(document).on("page:change", function() {
    App.init();
    enumeratePreTransfers();

    $('#datetimepicker1').datetimepicker({
      icons: {
        date: "fa fa-calendar"
      },
      format: "DD/MM/YYYY",
      defaultDate: new Date()
    });
  });

  var bloodhound = new Bloodhound({
    datumTokenizer: function (d) {
      return Bloodhound.tokenizers.whitespace(d.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: "/find_from_stock_by_pointsale?pointsale_id=ID&query=%QUERY",
      wildcard: '%QUERY',
      replace: function(url, uriEncodedQuery) {
          origin = $('#origin_id').val();
          return url.replace('ID', origin).replace('%QUERY', uriEncodedQuery)
      }
    }
  });

  bloodhound.initialize();
  $('#typeahead').typeahead(
    {
      minLength: 3
    },
    {
      displayKey: 'name',
      source: bloodhound.ttAdapter(),
      limit: Infinity,
      templates: {
        empty: [
          '<div class="empty-message">',
            'No se encontró ningun producto. Favor de verificar',
          '</div>'
        ].join('\n'),
         suggestion: Handlebars.compile(
            '<div class="media">' +
              '<div class="pull-left">' +
                  '<div class="media-object">' +
                      '<img src="{{small_img}}" width="50" height="50"/>' +
                  '</div>' +
              '</div>' +
              '<div class="media-body">' +
                  '<h4 class="media-heading"><strong>{{sku}}</strong> | {{name}}</h4>' +
                  '<p>{{barcode}}</p>' +
                  '<p>{{description}}</p>' +
                  '<p>{{display_attributes}}</p>' +
              '</div>' +
            '</div>')
      }
  });

  $('body').barcodeListener().on('barcode.valid', function(e, code) {
    findProductByBarcode(code);
  });

  $('#transfer_destiny_id').on('change', function() {
    $('#destiny_id').val($(this).val());
  });

  $('#transfer_origin_id').on('change', function() {
    $('#origin_id').val($(this).val());
  });

  $('#typeahead').bind('typeahead:selected', function(event, datum, name) {
    selectedProduct = datum;
    $('#products_new').attr('disabled', false);
  });

  function addRow() {
    if(selectedProduct) {
      $('#pre_transfer_origin_id').val($('#origin_id').val());
      $('#pre_transfer_destiny_id').val($('#transfer_destiny_id').val());
      $('#pre_transfer_product_id').val(selectedProduct.id);
      $('#pre_transfer_quantity').val(1);
      $('#new_pre_transfer').submit();
      $('#typeahead').typeahead('val','');
      $('#products_new').attr('disabled', true);
    }
  }

  function deleteRow(input) {
    var table = $('#products_table').DataTable();
    var idText = input.closest('tr').attr('id');
    var preTransferId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
    $.ajax({
      type: "DELETE",
      url: "/pre_transfers/" + preTransferId,
      dataType: "json",
      data: "",
      success: function(xhr, status, error) {
        table.row(input.closest('tr')).remove().draw();
      }
    });
  }

  function enumeratePreTransfers() {
    if($('#reset_pre_transfers').prop("disabled") == false) {
      var table = $('#products_table').dataTable();
      var counter = 1;
      $('#products_table tbody tr').each(function() {
        $(this).find('td:eq(0)').html($(this).find('td:eq(0)').html().replace('#', counter));
        counter++;
      });
    }
  }

  function deletePreTransfers() {
    $.ajax({
      type: "get",
      url:  '/delete_pre_transfers',
      dataType: 'json',
      success: function(xhr, status, error){
        $('#products_table').dataTable().fnClearTable();
        $("#transfer_destiny_id").select2().select2("val", null);
        <% if current_user.usertype == 'A' %>
          $("#transfer_origin_id").attr('disabled', false);
          $("#transfer_origin_id").select2().select2("val", null);
        <% end %>
        $("#transfer_destiny_id").attr('disabled', false);
        $("#reset_pre_transfers").attr('disabled', true);
      }
    });
  }

  function updateQuantity(input) {
    if(input.val() > 0) {
      clearTimeout(timeout);
      timeout = setTimeout(function () {
        var idText = input.closest('tr').attr('id');
        var preTransferId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
        $.ajax({
            type: "PUT",
            url: "/pre_transfers/" + preTransferId,
            dataType: "json",
            data: {pre_transfer: {quantity: input.val()}},
            success: function(xhr, status, error) {
              $("#save_transfer").attr("disabled", false);
            },
            statusCode: {
              422: function() {
                $("#save_transfer").attr("disabled", true);
                toastr["error"]("Error, El stock es insuficiente.");
              }
            }
        });
      }, 700);
    } else {
      $("#save_transfer").attr("disabled", true);
      toastr["error"]("La cantidad debe ser mayor a 0");
    }
  }

  function findProductByBarcode(barcode) {
    var origin = $('#origin_id').val();
    var destiny = $('#destiny_id').val();
    if((origin && destiny) && (origin != destiny)) {
      $.ajax({
        type: "get",
        url:  '/add_pre_transfer_by_barcode/' + barcode + "/" + origin + "/" + destiny,
        dataType: 'script',
        success: function(data) {
        },
      });
    } else {
      toastr["error"]("Falta seleccionar datos del formulario, o el origen y el destino son los mismos.");
    }
  }
</script>
