<%= form_for(@special_price, :remote => true, :html => {:class=>"form-horizontal"}) do |f| %>
<div class="portlet-body form">
   <div id="error_explanation"></div>
  <div class="form-body">
    <div class="row">
      <div class="col-md-12">
        <!-- cliente -->

        <div class="note note-success">
          <h4 class="block">Instrucciones:</h4>
          <p> Al seleccionar un cliente se mostrará en la tabla los productos que tiene asignados con precio especial.</br>
          Tras buscar y seleccionar un producto, se agrega automaticamente al cliente y se debe asignar ya sea el precio o el porcentaje de descuento que tendra al momento de la venta.</p>
        </div>
        <div class="form-group">
            <%= f.label :customer_id, "Cliente", {:class=>"col-md-2 control-label"} do %> Cliente
            <span class="required">*</span>
            <% end %>
            <div class="input-group col-md-5 select2-bootstrap-prepend">
              <%= f.collection_select :customer_id, Customer.vigentes, :id, :nick_name, {:prompt => "Seleccione"}, {:class => "form-control select2", :disabled => @disabled_select} %>
              <%= f.hidden_field :customer_id, {:id => 'customer'} %>
              <%= f.hidden_field :product_id, {:id => 'product'} %>
            </div>
          </div>
        </div>
        <!-- agregar productos -->
        <h4 class="form-section"> Agregar producto</h4>

        <div class="row">

          <div class='col-md-12'>

            <div class="form-group">
              <%= label_tag 'destiny', {:class=>"col-md-2 control-label"} do %> ¿El producto tiene variantes?
              <span class="required">*</span>
              <% end %>
              <div class="col-md-3" style="padding-left:0px;padding-right:0px">
                <%= check_box_tag('product_has_variants', 'no', false,
                  {
                    class: "make-switch",
                    disabled: false,
                    data: {
                      on_color: "success",
                      off_color: "warning",
                      on_text: "SI",
                      off_text: "NO"
                    }
                  }) %>
              </div>
            </div>

            <div class="form-group">
              <label class="col-md-2 control-label" for="typeahead"> Producto
                <span class="required">*</span>
              </label>
              <div class="col-md-4" style="padding-left:0px">
                <input class="form-control" type="text" id="typeahead" data-option-url="/URL/%QUERY">
              </div>
              <button id="products_new" disabled class="btn btn-success" type="button" onclick="addRow()"> Agregar <i class="fa fa-plus"></i> </button>
            </div>
            <div class="alert alert-info col-md-offset-2 col-md-8">
              <strong>Aviso:</strong> Para agregar un producto a la lista puede scannear su código de barras ó buscar por nombre o SKU.
            </div>
          </div>
        </div>
        <!-- lista de productos -->
        <h4 class="form-section"> Lista de productos</h4>
        <div class="portlet-body">
          <table class="table table-striped table-bordered table-hover tableadvanced" id="products_table">
            <thead>
              <tr>
                <th>#</th>
                <th>SKU</th>
                <th>Producto</th>
                <th>Imagen</th>
                <th>Precio de venta</th>
                <th>Descuento en cantidad</th>
                <th>% de descuento</th>
                <th width="15%">Acciones</th>
              </tr>
            </thead>
            <tbody>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>
<% end %>
<script type="text/javascript">

  var selectedProduct;
  var timeout = null;

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

  });

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

  $('#special_price_customer_id').on('change', function() {
    $('#customer').val($(this).val());
    $.ajax({
        type: "GET",
        url: "/get_special_price_by_customer/" + $(this).val(),
        dataType: "script",
        success: function(xhr, status, error) {
        }
    });
  });

  var bloodhound = new Bloodhound({
    datumTokenizer: function (d) {
      return Bloodhound.tokenizers.whitespace(d.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
      url: "/URL/" + "%QUERY",
      wildcard: '%QUERY',
      replace: function(url, uriEncodedQuery) {
        has_variants = $('#product_has_variants').bootstrapSwitch('state');
        type = has_variants ? 'find_products_sp' : 'find_products'
        return url.replace('URL', type).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>')
      }
  });

  function addRow() {
    if(selectedProduct) {
      $('#product').val(selectedProduct.id);
      $('#price').val();
      $('#percent').val();

      $('#new_special_price').submit();
      $('#typeahead').typeahead('val','');
      $('#products_new').attr('disabled', true);
    }
  }


  // this is the event that is fired when a user clicks on a suggestion
  $('#typeahead').bind('typeahead:selected', function(event, datum, name) {
    selectedProduct = datum;
    if($('#customer').val()) {
      $('#products_new').attr('disabled', false);
    } else {
      toastr["error"]("Error, Se debe seleccionar un cliente.");
    }
  });

  function updateProductPrice(input) {
    if(input.val()) {
      clearTimeout(timeout);
      timeout = setTimeout(function () {

        var idText = input.closest('tr').attr('id');
        var specialPriceId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
        input.closest('tr').find('td:eq(6) input').val("");
        var priceSale = parseFloat(input.closest('tr').find('td:eq(4) input').val());
        var newPrice = parseFloat(input.val());
        if (newPrice > priceSale) {
          toastr["error"]("El descuento no puede ser mayor al precio de venta del producto.");
        } else {
          $.ajax({
              type: "PUT",
              url: "/special_prices/" + specialPriceId,
              dataType: "json",
              data: {special_price: {price: newPrice}},
              success: function(xhr, status, error) {
                toastr["success"]("Precio especial actualizado.");
              }
          });
        }
      }, 300);
    }
  }

  function updateProductPercent(input) {
    if(input.val()) {
      clearTimeout(timeout);
      timeout = setTimeout(function () {

        var idText = input.closest('tr').attr('id');
        var specialPriceId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
        input.closest('tr').find('td:eq(5) input').val("");
        var percent = parseFloat(input.val());
        if(percent > 100) {
          toastr["error"]("El porcentaje de descuento no puede ser mayor a 100%");
        } else {
          $.ajax({
              type: "PUT",
              url: "/special_prices/" + specialPriceId,
              dataType: "json",
              data: {special_price: {percent: input.val()}},
              success: function(xhr, status, error) {
                toastr["success"]("Precio especial actualizado.");
              }
          });
        }
      }, 300);
    }
  }

  function deleteRow(input) {
    var table = $('#products_table').DataTable();

    var idText = input.closest('tr').attr('id');
    var specialPriceId = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
    input.closest('tr').find('td:eq(6) input').val("");
    $.ajax({
      type: "DELETE",
      url: "/special_prices/" + specialPriceId,
      dataType: "json",
      success: function(xhr, status, error) {
        table.row(input.closest('tr')).remove().draw();
        toastr["warning"]("Precio especial eliminado.");
      }
    });
  }

  function findProductByBarcode(barcode) {
    var customer = $('#special_price_customer_id').val();
    if(customer) {
      $.ajax({
        type: "get",
        url:  '/add_special_price_by_barcode/' + barcode + "/" + customer,
        dataType: 'script',
        success: function(data) {
        },
      });
    } else {
      toastr["error"]("Se debe seccionar cliente.");
    }
  }
</script>
