<div class="page-container">
  <!-- BEGIN CONTENT -->
  <div class="page-content-wrapper">
    <!-- BEGIN CONTENT BODY -->
    <!-- BEGIN PAGE HEAD-->
    <div class="page-head">
      <div class="container-fluid">
        <!-- BEGIN PAGE TITLE -->
        <div class="page-title">
          <h1>Ventas </h1>
        </div>
        <!-- END PAGE TITLE -->
      </div>
    </div>
    <!-- END PAGE HEAD-->
    <!-- BEGIN PAGE CONTENT BODY -->
    <div class="page-content">
      <div class="container-fluid">
        <!-- BEGIN PAGE BREADCRUMBS -->
        <ul class="page-breadcrumb breadcrumb">
          <%= render_breadcrumbs :tag => :li, :separator => ' <i class="fa fa-circle"></i> ' %>
        </ul>
        <!-- END PAGE BREADCRUMBS -->
        <!-- BEGIN PAGE CONTENT INNER -->
        <div class="page-content-inner">
          <div id="notice">
          <% if success %>
            <div class="alert alert-success">
              <p><%= success %></p>
            </div>
          <% elsif warning %>
            <div class="alert alert-warning">
              <p><%= warning %></p>
            </div>
          <% end %>
          </div>
          <div class="row">
            <div class="col-md-12">
              <div class="portlet light ">
                <div class="portlet-title">
                  <div class="caption">
                    <i class="fa fa-list "></i>
                    <span class="caption-subject bold uppercase">Lista de ventas</span>
                  </div>
                  <div class="actions">
                    <% if can? :create, Sale %>
                      <%= link_to new_sale_path, { class: "btn bold green pull-right filtros" } do %> Nueva Venta <i class="fa fa-plus"></i>
                      <% end %>
                    <% end %>
                  </div>
                </div>
                <div class="portlet-body">
                  <div class="form-horizontal" style="margin-bottom:35px">
                    <div class="row">
                      <div class="col-md-11">
                        <%= hidden_field_tag 'title_for_print' %>
                        <div class="form-group">
                          <%= label_tag :begin_date, "Fecha", { class: "col-md-1 control-label" } do %> Desde <% end %>
                          <div class="col-sm-2" style="padding-left:0px;padding-right:0px;">
                            <div class='input-group date' id='begin_date'>
                              <input id="start" type='text' class="form-control" value="<%= l(Date.today.beginning_of_month, format: '%d/%m/%Y') %>" />
                              <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                              </span>
                            </div>
                          </div>
                          <%= label_tag :end_date, "Fecha", { class: "col-md-1 control-label" } do %> Hasta <% end %>
                          <div class="col-sm-2" style="padding-left:0px;padding-right:0px;">
                            <div class='input-group date' id='end_date'>
                              <input id="end" type='text' class="form-control" value="<%= l(Date.today.end_of_month, format: '%d/%m/%Y') %>" />
                              <span class="input-group-addon">
                                <span class="glyphicon glyphicon-calendar"></span>
                              </span>
                            </div>
                          </div>
                          <button class="btn btn-icon-only blue" style="margin-left:25px" onclick="salesByDate()">
                            <i class="fa fa-search"></i>
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                  <input type='hidden' name='filter' id='filter' value='<%= @filter %>' >
                  <input type='hidden' name='current_page' id='current_page' value='<%= @current_page %>' >
                  <table class="table table-striped table-bordered table-hover" id="sales_table">
                    <thead>
                      <tr>
                        <th>#</th>
                        <th>Folio</th>
                        <% if current_user.usertype == 'A' %>
                          <th>Pto. de venta</th>
                        <% end %>
                        <th>Cliente</th>
                        <th>Vendedor</th>
                        <th>Fecha</th>
                        <th>Tipo</th>
                        <th>Productos</th>
                        <th>Status</th>
                        <th>Total</th>
                        <th class="hide_c">Acciones</th>
                      </tr>
                    </thead>
                    <tbody>
                      <% @sales.each_with_index do |sale, key| %>
                      <tr class=<%= (sale.cancelled? ? 'danger' : '') %>>
                        <td><%= sale.id %></td>
                        <td><%= sale.sale_code %> </td>
                        <% if current_user.usertype == 'A' %>
                          <td> <%= sale.get_pointsale.name %> </td>
                        <% end %>
                        <td><%= sale.customer.nick_name %> </td>
                        <td><%= sale.seller.name %> </td>
                        <td><%= l(sale.date_sale, format: '%d/%m/%Y') %></td>
                        <td><%= sale_type(sale) %></td>
                        <td><%= sale.sales_details.sum(:quantity).round %></td>
                        <td><%= sale_status(sale) %></td>
                        <td><%= number_to_currency(sale.total, precision: 2) %></td>
                        <td class="text-center hide_c">
                          <%= link_to sale, { class: "btn btn-icon-only default filtros", title: "Ver venta" } do %>
                            <i class="fa fa-search"></i>
                          <% end %>
                          <%= link_to print_receipt_path(sale.id, format: 'pdf'), { class: "btn btn-icon-only default", target: "blank" } do %>
                            <i class="fa fa-print"></i>
                          <% end %>
                          <% if (can? :delete, Sale) && sale.can_be_cancelled?(@pos_config) %>
                            <%= link_to sale, method: :delete, class: "btn btn-icon-only btn-danger", title: "Cancelar venta", data: { confirm: '¿Está seguro que desea cancelar la venta?' } do %> <i class="fa fa-ban"></i><% end %>
                          <% end %>
                        </td>
                      </tr>
                      <% end %>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- END PAGE CONTENT INNER -->
      </div>
    </div>
    <!-- END PAGE CONTENT BODY -->
    <!-- END CONTENT BODY -->
  </div>
  <!-- END CONTENT -->
</div>
<script>
  var closePrintView = function(e) {
    if(e.which == 27) {
      printViewClosed();
      $('.hide_c').removeClass("hidden");
    }
  };

  function printViewClosed() {
    $("#sales_table").dataTable().fnSetColumnVis('.hide_c', true);
    $(window).unbind('keyup', closePrintView);
  }

  $(document).on("page:change", function() {
    App.init();
     $('#start').datetimepicker({
      icons: {
        date: "fa fa-calendar"
      },
      format: "DD/MM/YYYY"
    });

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

    var startDate = moment($("#start").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY');
    var endDate = moment($("#end").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY');
    $('#title_for_print').val('Ventas del ' + startDate + ' al ' + endDate);


    $.fn.dataTableExt.oStdClasses.sFilterInput = "form-control input-medium input-inline";

    $.extend(true, $.fn.DataTable.TableTools.classes, {
      "container": " pull-right margin-bottom-10",
      "buttons": {
        "normal": "btn btn-primary margin-right-10",
        "disabled": "disabled"
      },
      "collection": {
        "container": "DTTT_dropdown dropdown-menu tabletools-dropdown-menu "
      }
    });

    var table = $('#sales_table').dataTable({
      // T = tabletools; l = length changing; f = filtering input; t = table; i = table info; p = pagination
      "dom": "<'row' <'col-md-12'T>><'row'<'col-md-6 col-sm-12'l><'col-md-6 col-sm-12'f><'col-md-6 col-sm-12'>r><'table-scrollable't><'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>",
      "tableTools": {
        "aButtons": [{ // 1
          "sExtends": "collection",
          "sButtonText": "Acciones",
          "aButtons": [ // 2
            { "sExtends": "print",
              // "columnDefs": [{
              //   "targets": 'hide_c',
              //   "visible": false
              // }],
              "sButtonText": "Imprimir",
              "sInfo": 'Presiona "CTR+P" para imprmir o "ESC" para salir',
              "sMessage": function() {
                return "<h2>Lista de ventas desde el " + $("#start").val() + " al " + $("#end").val() + "</h2>";
              },
              "fnClick": function(nButton, oConfig) {
                table.fnSetColumnVis('.hide_c', false);
                $(window).keyup(closePrintView);
                this.fnPrint(true, oConfig);
              }
            },
            // { "sExtends": "pdf",
            //   "sPdfOrientation": "landscape",
              // "columnDefs": [{
                // "targets": 'hide_c',
                // "visible": false
              // }],
            //   "sButtonText": "PDF"
            // }
          ] // 2
        }] // 1
      },
        "fixedHeader": true,
        "language": {
          "aria": {
            "sortAscending": ": activate to sort column ascending",
            "sortDescending": ": activate to sort column descending"
          },
          "emptyTable": "No hay informacion en la tabla",
          "info": "Mostrando del _START_ al _END_ de _TOTAL_ registros",
          "infoEmpty": "No se encontraron coincidencias",
          "infoFiltered": "(filtrado un total de _MAX_ registros)",
          "lengthMenu": "Mostrar _MENU_ registros",
          "search": "Buscar:",
          "zeroRecords": "No se encontraron coincidencias",
          "paginate": {
            "sPrevious": "Ant",
            "sNext": "Sig"
          }
        },
        "order": [
            // [0, 'asc']
        ],
        "lengthMenu": [
          [20, 50, 75, 100, -1],
          [20, 50, 75, 100, "Todos"] // change per page values here
        ],
        "pageLength": 20,
        "bServerSide": false
    });
  });

  function salesByDate() {
    if ($("#start").val() && $("#end").val()) {
      var start = moment($("#start").data("date"), "DD-MM-YYYY").format('YYYY-MM-DD HH:mm:ss');
      var end = moment($("#end").data("date"), "DD-MM-YYYY").format('YYYY-MM-DD HH:mm:ss');
    } else {
      var start = "";
      var end = "";
    }

    App.blockUI({
      target: $("#sales_table"),
      animate: true
    });

    $.ajax({
      type: "get",
      url: '/find_sales_by_date/' + start + '/' + end,
      dataType: 'script',
      success: function(data) {
        window.setTimeout(function() {
          App.unblockUI($("#sales_table"));
          var startDate = moment($("#start").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY')
          var endDate = moment($("#end").data("date"), "DD-MM-YYYY").format('DD/MM/YYYY');
          $('#title_for_print').val('Ventas del ' + startDate + ' al ' + endDate);
        }, 100);
      }
    });
  }
</script>
