
<div class="container col d-flex justify-content-center">
   <div class="row">
      <div class="col-lg-12">
         <div class="card shadow-lg p-3 mb-5 bg-white ">
            <div class="card-header">
               <h3> Apertura de Turno </h3>
            </div>
            <div class="card-body"> 
               <!-- COMIENZO DEL FORMULARIO -->
               <form id="turnoopen01" action="/links/openturno" method="POST" class="needs-validation" novalidate>
                  <div class="form-row">
                     <!-- LABELS E INPUTS DEL LA PRIMERA FILA  -->

                     <!-- LABELS E INPUTS DE  LA FECHA -->

                     <div class="col-md-3 mb-3">
                        <label class="font-weight-bold" for="fecha">Fecha</label>
                        <input name="fecha" type="date" class="form-control" id="id-fecha" placeholder=""
                           value={{ eldia }} required>
                        <div class="valid-feedback"></div>
                        <div class="invalid-feedback">Complete el campo.</div>
                     </div>

                     <div class="col-md-2 mb-3">
                        <label class="font-weight-bold" for="turno">Turno</label>
                        <select name="turno" class="custom-select" required>
                           <option value=""></option>
                           {{#each lista}}
                           {{#each lista_turnos}}
                           <option value={{id_turnos}}>{{horarios}}</option>
                           {{/each}}
                           {{/each}}

                        </select>
                     </div>

                     <div class="col-md-3 mb-3">
                        <label class="font-weight-bold"        for="area">Area</label>
                        <select name="area" class="custom-select"   onchange="cambioarea('0')"  required>
                           <option value=""></option>
                           {{#each lista}}
                           {{#each lista_areas}}
                           <option value={{id_dpto}}>{{nombre}}</option>
                           {{/each}}
                           {{/each}}
                        </select>
                     </div>

                     <div class="col-md-3 mb-3">
                        <label class="font-weight-bold"        for="area">grupo</label>
                        <select name="grupo" class="custom-select"   onchange="cambiogrupo('0')"  required>
                           <option value="999"   >Todos</option>
                           {{#each lista}}
                           {{#each lista_grupos}}                          
                           <option value="{{id_grupo}}"   selected="selected">{{descripcion}}</option>
                           {{/each}}
                           {{/each}}
                        </select>
                     </div>

                    <div class="col-md-3 mb-3">
                      <label class="font-weight-bold" for="desformula">Supervisor</label> 
                      <div class="input-group">
                        <input class="form-control" type="text"    name="supervisorname" readonly value = "{{user.fullname}}">                     
                      </div>
                    </div>

                      <div class="input-group">
                        <input type="hidden"   class="form-control"  name="inputtabladetalle" >                         
                        <input type="hidden"   class="form-control"  name="tipo_de_submit"  value=0 >
                        <input type="hidden"   class="form-control"  name="tablamaquinas"  value=0 >
                        <input type="hidden"  style="text-align:right;" class="form-control" placeholder="" name="indextable" >  
                      </div>

                  </div> <!-- FIN DE LABELS E INPUTS DEL LA PRIMERA FILA  -->
               
                 <div class="form-row">

       <div class="row">
<div style="height: 400px;overflow: scroll;">
            <div class="col-lg-12 mx-auto bg-white rounded shadow">                    

                      <div class="col">
                         <table id="tabla123" class="table table-hover"      class="table-responsive"  class="table table-fit" >
                              <thead>
                                 <tr>
                                    <th style="display:none" >Rowid</th>
                                    <th style="display:none">ID</th>
                                    <th   width="10%">Descripcion</th>
                                    <th   width="15%" >#Orden</th>
                                    <th   width="45%" >Producto</th>
                                    <th   width="15%" >Operador</th>
                                    <td   colspan="2"  class="text-center  font-weight-bold" >Ayudantes</td>
                                    <th   class="text-center" >Acciones</th>
                                 </tr>
                              </thead>
                              <tbody  class="container vertical-scrollable">
                              </tbody>
                        </table>
                      </div>
             </div>               
 </div>

                    </div>

                 </div>
                  <!-- FIN DE la TERCERA linea ROW-->

                  <div class="form-row">
                     <!-- COMIENZO DE la CUARTA linea ROW-->
                            <div class="col-md-8 mb-3">
                              <div class="input-group">                               

                              </div>
                            </div>
                            <div class="col-md-2 mb-3">
                              <div class="input-group">                               
                                 <input type="button" id="btn-grabar" value="Save" name="register" class="btn btn-success accept"/>
                              </div>
                            </div>
                            <div class="col-md-2 mb-3">
                              <div class="input-group">                               
                                <button id="btnCrear"    class="btn btn-danger" onclick= "cambiarstatus(1)"  >Close</button>
                              </div>
                            </div>
                  </div>

               </form>
            </div>
         </div>
      </div>
   </div>
</div>

<script src="/jquery/dist/jquery.js"></script>


<script>

$(document).ready(function() { 
    $('form #btn-grabar').click(function(e) {
        cambiarstatus(0); 
        var ord_sinop = validarordenoperador();
        if ( ord_sinop <=0) {
               // realizo el submit para grabar 
               anexartabla();
              // toastr.success('Registro Grabado exitosamente', 'Producción Indesplast', {timeOut: 2000})     
        } else {
          toastr.error('Falta asignar operador a la maquina', 'Producción Indesplast', {timeOut: 2000})
        }
    });


});
//*******************
$(document).on("click", ".delete", function(){
      var fila = $(this).closest("tr");
    //  var id_mp = parseInt(fila.find('td:eq(2)').text());
    //  var id_maquina = parseInt(fila.find('td:eq(0)').text());
    //  addeliminados(id_mp, id_maquina) ;
      $(this).parents("tr").remove();
		$(".add-new").removeAttr("disabled");
});


//****************************
  function validarordenoperador(){
         var table2 = document.getElementById('tabla123');
         var numero_de_ordenes_sin_operador = 0;
         for(var r = 0; r < (table2.rows.length -1); r++) {
            var orden = document.getElementsByName('numorden')[r].value ;          
            //var orden = 0 ;
            orden = orden.trim();
            var operador =  parseInt('0' + validarslect (document.getElementsByName('operador')[r].value));
             
            if (orden.length > 0)       {
                 if (operador <= 0) {
                     numero_de_ordenes_sin_operador = numero_de_ordenes_sin_operador + 1;
                 }
            }
         } // fin del for

//***
        function validarslect(dataselec) {
           
           if (dataselec == 'selected="selected"') {
                    return '0'
           } {
                    return  dataselec
           }
        }

//***


         return numero_de_ordenes_sin_operador;
  }
//*******************

onload = function() {
    if (!document.getElementsByTagName || !document.createTextNode) return;
    var rows = document.getElementById('tabla123').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            //alert(this.rowIndex + 1);
        }
    }
}


</script>


<script>
   function cambiarstatus(valor) {
      document.getElementsByName('tipo_de_submit')[0].value = valor;
   }
</script>

<script>

   (function () {
      'use strict';
      window.addEventListener('load', function () {
         // Fetch all the forms we want to apply custom Bootstrap validation styles to
         var forms = document.getElementsByClassName('needs-validation');
         // Loop over them and prevent submission
         var validation = Array.prototype.filter.call(forms, function (form) {
            form.addEventListener('submit', function (event) {
               if (form.checkValidity() === false) {
                  if (parseInt(document.getElementsByName('tipo_de_submit')[0].value) <= 0) {
                      event.preventDefault();
                      event.stopPropagation();
                  }
               }
               form.classList.add('was-validated');
            }, false);
         });
      }, false);
   })();


</script>

<script>



function cambioarea(value) {

var id_dpto = parseInt('0' + document.getElementsByName('area')[0].value);
var url1 = "/links/areas/" + id_dpto;

var table = document.getElementById("tabla123");

for(var i = table.rows.length - 1; i > 0; i--)
{
    table.deleteRow(i);
}

$.ajax({
    url: url1,
    type: "GET",
    dataType: "json",
    success: function (data) {
        //console.log(data);
        var trHTML = '';
        $.each(data, function (i, item) {
            trHTML += '<tr> <td style="display:none">' + i + '</td>' + '<td style="display:none">' + item.id_maquina + '</td><td>' + item.descripcion + '<td><div class="input-group"> <input type="text" class="form-control"  id= "orden-' + i + '" name="numorden"   value=  ""  > <div class="input-group-append"> <button href="#" class="btn btn-secondary"  data-toggle="modal" data-target="#modalPlanes" type="button"> <i class="fa fa-search"></i> </button> </div> </div></td>' + '<td><input class="form-control" type="text"  id= "desorden-' + i + '" name="des-orden" readonly></td>' + '<td><select name="operador" class="custom-select" > <option value="" ></option>  <option value=></option>  </select> </td>' + '<td><select name="ayudante1" class="custom-select" > <option value="" ></option> <option value=></option>  </select> </td>' + '<td><select name="ayudante2" class="custom-select" > <option value="" ></option> <option value="" ></option> </select></td> <td class="text-center"> <a class="delete" title="Delete" data-toggle="tooltip"><i class="fas fa-trash"></i></a> </td>  </td></tr>';
        });
        cambiogrupo(0);
       $('#tabla123').append(trHTML);
        // document.getElementsByName('inputtabladetalle')[0].value = trHTML ; 

///**
    var rows = document.getElementById('tabla123').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
    for (i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
           document.getElementsByName('indextable')[0].value = (this.rowIndex - 1 );
        }
    }
//***

    },
    error: function (error) {
        console.log(`Error ${error}`);
    }
   
});
  
}

//**************************
</script>


<script>

function cambiogrupo(value)   {
     var id_grupo = parseInt('0' + document.getElementsByName('grupo')[0].value);
     var url1 = "/links/trabadoresxgrupo/" + id_grupo;
         $.ajax({
            url: url1,
            type: "GET",
            dataType: "json",
            success: function (data) {
               var trHTMLayudante1 = '<select  name="ayudante1" class="custom-select" > <option value="" ></option>';
               var trHTMLayudante2 = '<select  name="ayudante2" class="custom-select" > <option value="" ></option>';
               var selectInnerHTML= '<select id="oper01"  name="operador" class="custom-select" >  <option value="" selected="selected"></option>' ;
               $.each(data, function (i, item) {
                     if (item.rol.trim() == 'Operador') {
                          selectInnerHTML += '<option value="' + item.id_trabajador + '">' + item.persona + '</option>';                                                   
                     } else {
                        trHTMLayudante1 += '<option value="' + item.id_trabajador + '">' + item.persona + '</option>';
                        trHTMLayudante2 +=  '<option value="' + item.id_trabajador + '">' + item.persona + '</option>';
                     }     
               });
               selectInnerHTML +=  '</select>';
               trHTMLayudante1 += '</select>';
               trHTMLayudante2 += '</select>';
               asignarvaloresselect(selectInnerHTML,trHTMLayudante1,trHTMLayudante2)

            },
            error: function (error) {
               console.log(`Error ${error}`);
            }


            
         });

}// fin de la funcion
//**************************//
function asignarvaloresselect(v_operador,v_ayudante1, v_ayudante2) {
   var table3 = document.getElementById('tabla123');
   for(var i = 0; i < table3.rows.length; i++) {
        document.getElementsByName('operador')[i].innerHTML = v_operador ;
        document.getElementsByName('ayudante1')[i].innerHTML = v_ayudante1 ;
        document.getElementsByName('ayudante2')[i].innerHTML = v_ayudante2 ;
   }
}

//*************************//
</script>

<script>

function anexartabla() {
      var TableData;
          TableData = storeTblValues()
          TableData = JSON.stringify(TableData);
      var json =  TableData;
      document.getElementsByName('tablamaquinas')[0].value = json;
      $("#turnoopen01").submit();
};


   // Handle form submission event
   $('#turnoopen01').on('submit', function(e){
      var form = this;
      
      var TableData;
         TableData = storeTblValues()
         TableData = JSON.stringify(TableData);
         var json =  TableData;
         document.getElementsByName('tablamaquinas')[0].value = json;
   });


function storeTblValues()
{
    var TableData = new Array();
    var IdsMaq = new Array();
    var desmaquina = new Array();
         var table2 = document.getElementById('tabla123');
         $("#tabla123 tbody tr").each(function (index) {
            var campo1 = "";
            var campo2 = "";
               $(this).children("td").each(function (index2) {
                  switch (index2) {
                     case 1:
                        campo1 = $(this).text().trim();
                        IdsMaq.push(campo1)
                        break;
                     case 2:
                        campo2 = $(this).text().trim();
                        desmaquina.push(campo2)
                        break;                          
                  }

               });

         });


         for(var r = 0; r < table2.rows.length; r++) {
          if (r < (table2.rows.length) - 1) {
             var orden = document.getElementsByName('numorden')[r].value ;
             TableData.push({
              "Id_maquina" : IdsMaq[r]
            , "orden" : orden
            , "filtro": IdsMaq[r] + '-' +  desmaquina[r]
            , "Operador" : validarslect (document.getElementsByName('operador')[r].value)
            , "Ayudante1" : validarslect (document.getElementsByName('ayudante1')[r].value)
            , "Ayudante2" : validarslect(document.getElementsByName('ayudante2')[r].value)
            , "Des_maquina" : desmaquina[r]
                })                
          }          
        }

        function validarslect(dataselec) {
           
           if (dataselec == 'selected="selected"') {
                    return '0'
           } {
                    return  dataselec
           }
        }

    return TableData;
}




</script>

{{>catalagodeplanes2 }}