{% extends "baseAdmin.html" %}
{% load static %}
{% block titulo %}
  .:: Configuracion de Comiciones
{% endblock titulo %}
{% block content1 %} 
<link href="{% static 'Handson1/css/pikaday.css' %}" rel="stylesheet">
<script src="{% static 'Handson1/js/pikaday.js' %}"></script>
<script  src="{% static 'Handson1/js/ZeroClipboard.js' %}"></script>
<script  src="{% static 'Handson1/js/handsontable.js' %}"></script>
<link  href="{% static 'Handson1/css/handsontable.css' %}" rel="stylesheet">

 <link href="{% static 'Bootstrap/css/sweet-alert.css' %}" rel="stylesheet">
 <script src="{% static 'Bootstrap/js/sweet-alert.js' %}"></script>
<script type="text/javascript">
  //$("#navCajaPrincipal").attr('class','dropdown active');
  //$("#navEstadoCajas").attr('class','active');
</script>
<div class="container">
  <div class="row">
    <div class="col-md-12 col-sm-12" >
        <div class="panel panel-default">
          <div class="panel-heading"> <strong>COMFIGURACION DE COMISIONES</strong></div>
          <div class="panel-body">
            <div class="row">
              <div class="col-md-2 col-md-offset-1">
                <button type="button" class="btn btn-block btn-info btn-sm" id="btnRefrescar"><span class="fa fa-refresh"></span> Actualizar</button>
              </div>
            </div>
            <p></p>
            <div class="row">
              <div class="col-md-10 col-md-offset-1">
                <div class="alert alert-warning alert-dismissible" role="alert" align="left">
                  <button type="button" class="close" data-dismiss="alert" aria-label="Close" style=" font-size:30px;"><span aria-hidden="true">&times;</span></button>
                  <strong>Recuerde!</strong> <br>Si esta configurando <b>Cajas Independientes</b><br> <b>(*)</b>  Verificar (o cambiar) el nombre de la caja en <a href="/Admin/ConsultaGeneralCajas/" class="btn btn-primary btn-xs" role="button">Oficinas > Ver Oficinas</a>, para evitar errores en la configuracion.<br>
                  <b>(**)</b> Los <b>nombres de las cajas independientes</b> apareceran como destinos en la ventana de <u>crear Transferencia</u>.
                </div>
              </div>
            </div>
            <p></p>
            <div class="row">
              <div class="col-md-10 col-md-offset-1">
                <div class="alert alert-warning alert-dismissible" role="alert" align="left">
                  <button type="button" class="close" data-dismiss="alert" aria-label="Close" style=" font-size:30px;"><span aria-hidden="true">&times;</span></button>
                  <strong>Recuerde!</strong> <br>Para los montos de <b>Comision</b> , <b>Banco de la nacion</b>,<b>BCP</b> y <b>Otros bancos</b> <br> <b>(*)</b>  Los montos deben ser <b>mayores que 1</b>; Sino se considerara como porcentaje (%)<br>
                  <b>(**)</b> <b>Giro</b>, se considera giro cuando la transferencia es para bancos y el destino es un DNI (8 digitos)<br>
                  <b>(***)</b> <b>Deposito</b>, se considera deposito cuando la transferencia es para bancos y el destino es una CUENTA (mayor a 8 digitos)<br>
                </div>
              </div>
            </div>
            <p></p>
            <div class="row">
              <div class="col-md-6">
                <div class="row">
                  <h4 style="margin-left:15px;"> ORIGEN</h4>
                </div>
                <div class="row">
                  <div class="col-md-5">
                    <select class="form-control" name="OficinaOri" id="ComboOficinaOri" placeholder="Oficina Origen">
                      <option value="nulo"></option>     
                    </select> 
                  </div>
                  <div class="col-md-5">
                    <div class="select">
                      <select class="form-control" name="CajaOri" id="ComboCajaOri">  
                      </select> 
                    </div>
                  </div>
                  <div class="col-md-2">
                    <button type="button" class="btn btn-block btn-primary" id="btnAgregarOri"><span class="glyphicon  glyphicon-ok" aria-hidden="true"></span></button>
                  </div>
                </div>
                <p></p>
                <div class="row">
                  <div class="col-md-12">
                    <div class="panel panel-default">
                      <div class="panel-body" id="campoOrigenes">
                        <!--
                        <div class="alert alert-warning alert-dismissible listaBases" role="alert">
                          <button type="button" class="close btnCerrarAlrt" data-dismiss="alert" aria-label="Close" id="1"><span aria-hidden="true">&times;</span></button>
                          <strong>Warning!</strong> Better check yourself, you're not looking too good.
                        </div>
                        <div class="alert alert-success alert-dismissible listaBases" role="alert">
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                          <strong>Warning!</strong> Better check yourself, you're not looking too good.
                        </div>
                        <div class="alert alert-warning alert-dismissible listaBases" role="alert">
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                          <strong>Warning!</strong> Better check yourself, you're not looking too good.
                        </div>
                        -->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="col-md-5 col-md-offset-1">
                <div class="row">
                  <h4  style="margin-left:15px;">DESTINO</h4>
                </div>
                <div class="row">
                  <div class="col-md-6">
                    <div class="">
                        <select class="form-control" name="OficinaDst" id="ComboOficina" placeholder="Of. Destino">   
                        </select>
                    </div>
                  </div>
                  <div class="col-md-2">
                    <button type="button" class="btn btn-block btn-primary" id="btnAgregarDes"><span class="glyphicon  glyphicon-ok" aria-hidden="true"></span></button>
                  </div>
                </div>
                <p></p>
                <div class="row">
                  <div class="col-md-11">
                    <div class="panel panel-default">
                      <div class="panel-body" id="campoDestinos">
                        <!--
                        <div class="alert alert-warning alert-dismissible listaBases" role="alert">
                          <button type="button" class="close btnCerrarAlrt" data-dismiss="alert" aria-label="Close" id="1"><span aria-hidden="true">&times;</span></button>
                          <strong>Warning!</strong> Better check yourself, good.
                        </div>
                        <div class="alert alert-success alert-dismissible listaBases" role="alert">
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                          <strong>Warning!</strong> Better check yourself,  good.
                        </div>
                        <div class="alert alert-warning alert-dismissible listaBases" role="alert">
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                          <strong>Warning!</strong> Better check yourself, good.
                        </div>
                      -->
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="row">
              <div class="checkbox"  style="margin-left:15px;">
                  <label class="">
                    <input id="ts4" type="checkbox" value="success-inverse1"> Eliminar todas las comisiones antes de Añadir
                  </label>
              </div> 
            </div>
            <div class="row">
              <h4  style="margin-left:15px;">TABLA DE COMISIONES</h4>
              <div class="col-md-2">
                <input type="search" class="form-control" id="buscar" placeholder="buscar en celda">
              </div>
            </div>

             <div class="row">
                <div class="col-md-12">
                  <div id="example1" style="width: auto; height: 400px; overflow: hidden;"></div>
                </div>
             </div>
             <br>
             <div class="row">
                <div class="col-md-2 col-md-offset-5">
                  <input class="btn btn-danger btn-block" type="button"id="guardar" value="Guardar">
                </div>
             </div>
             <br>
          </div>
        </div>
    </div>
  </div>
</div>

<style type="text/css">
  .listaBases{
    padding: 3px;
    margin-bottom: 1px;    
    padding-right: 35px;
  }
</style>
<script  type="text/javascript" charset="utf-8">
    var ors=[];
    var dts=[];
    var Aux='';
    var fila=0;
    var auto=["123456","1111"];
    $(document).ready(function (){
      //var dniValidator = /^(([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]([0-9][0-9][0-9])?)?)$/;
      var $container = $("#example1");
      //var aux1='<button type="button"style="color: #fff;background-color: #337ab7;border-color: #2e6da4;"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>';
      //var aux2='<button type="button"style="color: #fff;background-color: #5cb85c;border-color: #4cae4c;">Imprimir</button>';

      $container.handsontable({
        //data: data,
        startRows: 2,
        startCols: 10,
        rowHeaders: true,
        search: true,
        colHeaders: [ 'Monto Minimo','Monto Maxsimo', 'Comicion (DT)','BN (Giros)','BN (Depositos)','Continental (Giros)','Continental (Depositos)','BCP (Giros)','BCP (Depositos)','otros'],
        columns: [
                  {
                    type: 'numeric',
                    format: '0,0.00'
                  },
                  {
                    type: 'numeric',
                    format: '0,0.00'
                  },
                  {
                    
                  },
                  {
                    
                  },
                  {
                    
                  },
                  {
                    
                  },
                  {
                    
                  },
                  {
                    
                  },
                  {
                    
                  },
                  {
                    
                  }

                ],
        minSpareRows: 1,
        contextMenu: true
      });
      var hotInstance = $("#example1").handsontable('getInstance');
      function onlyExactMatch(queryStr, value) {
        return queryStr.toString() === value.toString();
      }
      document.querySelector('#guardar').onclick = function(){
        swal({
          title: "Guardar Configuracion",
          type: "warning",
          showCancelButton: true,
          confirmButtonClass: 'btn-danger',
          confirmButtonText: 'Guardar',
          closeOnConfirm: false,
          //closeOnCancel: false
        },
          function(){
            //EnviarCompra();
            /*
            console.log(hotInstance.getData());
            console.log(ors);
            console.log(dts);
            */
            var elimina="no"
            if($("#ts4").prop("checked")){
              elimina="si";
            }
            ajax_guardarComiciones(elimina);
            //alert(JSON.stringify(hotInstance.getData()));
        });
      };
      
      $("#buscar").keyup(function(){
        var queryResult = hotInstance.search.query(this.value);
        //console.log(queryResult);
        hotInstance.render();
      });
      hotInstance.updateSettings({
        afterSelection: function (e) {
          var pos = hotInstance.getSelected();
          if(pos[1]==2){
            console.log("hola");
            /*
            var t= hotInstance.getDataAtCell(pos[0],5);

            if(t!=null){
              swal({
                title: "Imprimir?",
                text: "",
                type: "warning",
                showCancelButton: true,
                confirmButtonClass: 'btn-warning',
                confirmButtonText: 'Imprimir',
                closeOnConfirm: true,
                //closeOnCancel: false
                },
                function(){
                  prepararImpresion(hotInstance.getDataAtCell(pos[0],0),hotInstance.getDataAtCell(pos[0],1),hotInstance.getDataAtCell(pos[0],2),hotInstance.getDataAtCell(pos[0],3),hotInstance.getDataAtCell(pos[0],4),hotInstance.getDataAtCell(pos[0],5));
                  $("#platillaI").printArea();
                });
            }
            */
          }
        }
      }
    );

  //------------------------------------------------------------
  //ajax
  ajax_oficina_ori();
  function ajax_oficina_ori(){
    $.ajax({
      url:'/oficinas_version3_ajax/',//origen globales
      type:'GET',
      dataType:'json',
      success: function(data){
      var html ="";
        $("#ComboOficinaOri").html('');
        for(var i=0;i<data.length;i++){
            html += '<option value="'+data[i].pk+'">'+data[i].nombre_oficina+'</option>';
        }
        $('#ComboOficinaOri').html(html);
        $('#ComboOficinaOri').selectize();
        ajax_cajaOrg($('#ComboOficinaOri').val());
      }
    });
  };
  $("#ComboOficinaOri").change(function(){
    ajax_cajaOrg($('#ComboOficinaOri').val());
  })
  function ajax_cajaOrg(pko){
    if (pko.toString().substring(0,1)=='b'){
      $("#ComboCajaOrg").html('');
      $("#ComboCajaOri").hide();
    }
    else{
      $.ajax({
        data:{'idOfi':pko},
        url:'/CajasPersonal_ajax/',
        type:'GET',
        dataType:'json',
        success: function(data){
          var html ="";
          $("#ComboCajaOri").html('');
          $("#ComboCajaOri").show();
          for(var i=0;i<data.length;i++){
            html += '<option value="'+data[i].pk+'">'+data[i].nombre+' - '+data[i].op+'</option>';
          }
          $('#ComboCajaOri').html(html);
        }
      });
    }
  };
  //destino
  ajax_oficina();
  function ajax_oficina(){
    $.ajax({
      url:'/oficinas_version3_config_aja/',//destino globales
      type:'GET',
      dataType:'json',
      success: function(data){
      var html ="";
        $("#ComboOficina").html('');
        for(var i=0;i<data.length;i++){
            html += '<option value="'+data[i].pk+'">'+data[i].nombre_oficina+'</option>';
        }
        $('#ComboOficina').html(html);
        $('#ComboOficina').selectize();
      }
    });
  };
  $("#btnAgregarOri").click(function(){
    var html='';
    if($('#ComboOficinaOri').val().toString().substring(0,1)=='c'){
       swal("","Nose puede agregar una caja independiente como origen", "warning");
    }
    else{
      //------------
      if ($('#ComboOficinaOri').val().toString().substring(0,1)=='b'){
        if(ors.indexOf($('#ComboOficinaOri').val())==-1){
          ors.push($('#ComboOficinaOri').val());
          html='<div class="alert alert-success alert-dismissible listaBases" role="alert"><button type="button" class="close btnEliminarOri" id="'+$('#ComboOficinaOri').val()+'" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>' +$('#ComboOficinaOri').text()+'</strong></div>';
        }
        else{
          swal("","Base u Oficina ya esta en la lista", "warning");
        }
        
      }
      else{
        var idA= $('#ComboOficinaOri').val().toString()+":"+ $('#ComboCajaOri').val().toString();
        if(ors.indexOf(idA)==-1){
          ors.push(idA);
          html='<div class="alert alert-success alert-dismissible listaBases" role="alert"><button type="button" class="close btnEliminarOri" id="'+idA+'" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>' +$('#ComboOficinaOri option:selected').text()+'</strong> '+$('#ComboCajaOri option:selected').text()+'</div>';
        }
        else{
          swal("","Base u Oficina ya esta en la lista", "warning");
        }
      }
      //--------------
    }
    $("#campoOrigenes").append(html);
    //----- consulta-----
    if(ors.length>0 && dts.length>0){
      ListarConfiguraciones()
    }
  });
  $("#btnAgregarDes").click(function(){
    /*
    if($('#ComboOficina').val().toString().substring(0,1)=='c'){
      swal("","Agregando Caja Independiente", "warning");
    }
    else{*/

      //---------------
      if(dts.indexOf($('#ComboOficina').val())==-1){
        dts.push($('#ComboOficina').val());
        var html='<div class="alert alert-warning alert-dismissible listaBases" role="alert"><button type="button" class="close btnEliminarDst" id="'+$('#ComboOficina').val()+'" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>' +$('#ComboOficina').text()+'</strong></div>';
      }
      else{
        swal("","Base u Oficina ya esta en la lista", "warning");
      }
      //-------------
    //}
    $("#campoDestinos").append(html);
    //----- consulta-----
    if(ors.length>0 && dts.length>0){
      ListarConfiguraciones()
    }

  });
  //----------------------------------------------
  //
  $(document).on("click",".btnEliminarOri",function(){
    //alert($(this).prop("id"));
    var idE= $(this).prop("id");
    ors.splice(ors.indexOf(idE), 1);
  });
  $(document).on("click",".btnEliminarDst",function(){
    //alert($(this).prop("id"));
    var idEd= $(this).prop("id");
    dts.splice(dts.indexOf(idEd), 1);
  });
  //------------------
  function preprocesarData(a){
    for (var i = 0; i < a.length-1; i++) {
      if(a[i][0]==null ||a[i][1]==null || a[i][2]==null){
        swal("","Revice la configuracion", "error");
      }
    }
    a.splice(a.length-1, 1);
    return a;
  }
  function ajax_guardarComiciones(el){
    //var dataTable=hotInstance.getData()
      //dataTable.pop();
      $.ajax({
        url:'/Guardar_Comisiones_general_ajax/',
        data:{'ori':JSON.stringify(ors),'des':JSON.stringify(dts),'data':JSON.stringify(preprocesarData(hotInstance.getData())),'eliminar':el},
        type:'GET',
        dataType:'text',
        success: function(data){
          console.log(data);
         if(data=='exito'){
          swal("Exito","las comiciones se guardaron", "success");
         }
         else{
          //bootbox.alert(data);
          swal("Error",data, "error");
         }
        }
      });
    };
  //------
  function ajustarTabla(n){
    var t=hotInstance.countRows();
      for(var i=0;i<t;i++){
        hotInstance.alter('remove_row',0);
      }  
      for(var j=0;j<n;j++){
        hotInstance.alter('insert_row',0);
      } 
  }
  //--------
  function ListarConfiguraciones(){
    $.ajax({
      url:'/listado_configuracionComiciones_Admin_ajax/',
      data:{'ori':ors[0],'des':dts[0]},
      type:'GET',
      dataType:'json',
      success: function(data){
        ajustarTabla(data.length);
        var html='';
        for(var i=0;i<data.length;i++){
          hotInstance.setDataAtCell(i,0,data[i].montomin);
          hotInstance.setDataAtCell(i,1,data[i].montomax);
          hotInstance.setDataAtCell(i,2,data[i].comision);
          hotInstance.setDataAtCell(i,3,data[i].banco_nacion);
          hotInstance.setDataAtCell(i,4,data[i].banco_nacion_de);
          hotInstance.setDataAtCell(i,5,data[i].continental);
          hotInstance.setDataAtCell(i,6,data[i].continental_de);
          hotInstance.setDataAtCell(i,7,data[i].bcp);
          hotInstance.setDataAtCell(i,8,data[i].bcp_de);
          hotInstance.setDataAtCell(i,9,data[i].otros_bancos);
        }                        
      }
    });
  }
  //--------------------
  $("#btnRefrescar").click(function(){
    if(ors.length>0 && dts.length>0){
      ListarConfiguraciones()
    }
  });
  //--------------------
});
</script>

{% endblock content1 %}