<div class="container">
   <div class="row">
      <div class="col-lg-12">
         <div class="card shadow-lg p-3 mb-5 bg-white ">
            <div class="card-header">
               <h3> Actividades  por Maquina</h3>
            </div>
            <div class="card-body">
               <!-- COMIENZO DEL FORMULARIO -->
               <form id="actividadesturno" action="/links/actividad-turno" 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="maquina">Maquina</label>
                        <select name="maquina"   id= "idmaquina1" class="custom-select"   onchange="filtrarmaquina('0')"  required>
                           {{#each lista}}
                           {{#each lista_maquinas}}
                           <option value="{{filtro}}"   selected="selected">{{descripcion}}</option>
                           {{/each}}
                           {{/each}}
                        </select>
                     </div>

                     <div class="col-md-2 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 }} readonly>
                        <div class="valid-feedback"></div>
                        
                     </div>

                     <div class="col-md-3 mb-3">
                        <label class="font-weight-bold" for="turno">Turno</label>                       
                        <input class="form-control" type="text" placeholder="" id="turno"   value = "{{lista.1.newParam.el_turno}}"    name="des-area" readonly>                     

                     </div>

                     <div class="col-md-3 mb-3">
                        <label class="font-weight-bold"        for="area">Area</label>
                        <input class="form-control" type="text" placeholder="" id="area"   value = "{{lista.1.newParam.area}}"   name="des-area" readonly>                     
                     </div>


                      
                      <div class="input-group">                       
                        <input type="hidden"  name="indextable" >                         
                        <input type="hidden"  name="tipo_de_submit"  value=0 >
                      </div>

                      <div class="input-group">
                        <input type="hidden"     name="inputtabladetalle" > 
                        <input type="hidden"     name="Id_registro"  value = {{lista.1.newParam.idreg}} > 
                        <input type="hidden"     name="tablaActividades"  value = "" > 
                      </div>

                  </div> <!-- FIN DE LABELS E INPUTS DEL LA PRIMERA FILA  -->

                  <div class="form-row">
                     <div class="col-md-10 mb-3">
                        <input class="form-control" type="text" placeholder="Producto" id="producto"      name="producto" readonly>                     
                     </div>
                  </div>


                  <div class="form-row">
                     <div class="col-md-4 mb-3">
                        <label class="font-weight-bold"  for="actividades">Actividades</label>
                        <select name="idactividad"  id="idactividad1" class="custom-select"   onchange="filtrarmaquina('0')"  required>
                           {{#each lista}}
                           {{#each lista_actividades}}
                           <option value="{{id_actividad}}"   selected="selected">{{descripcion}}</option>
                           {{/each}}
                           {{/each}}
                        </select>
                     </div>

                            <div class="col-md-3 mb-3">
                            <label class="font-weight-bold" for="descliente">Valor</label> 
                            <div class="input-group">
                                <input class="form-control" type="text" placeholder=""   id="valorid" name="valor" >                                                    
                            </div>
                            </div>


                            <div class="col-md-3 mb-3">
                            <label class="font-weight-bold" for="descliente">Agregar</label> 
                            <div class="input-group">
                                <input type="button" id="btn-agregar" value="Agregar actividad" name="agregar"     class="btn btn-primary accept"/>
                            </div>
                            </div>


                  </div> <!-- FIN DE LABELS E INPUTS DEL LA SEGUNDA FILA  -->

                 <div class="form-row">
                    <div style="height: 400px;overflow: scroll;"> 
                      <div class="col">
                         <table id="tabla123" class="table table-hover"   class="table table-responsive" class="table table-fit" >
                              <thead>
                                 <tr>
                                    <th style="display:none">ID maquina</th>
                                    <th style="display:none">filtro</th>
                                    <th >ID</th>
                                    <th   width="40%" >Descripcion</th>
                                    <th   width="10%" >Hora</th>
                                    <th   width="20%" >Valor</th>
                                    <th width="20%">Acciones</th>

                                 </tr>
                              </thead>                                 
                              <tbody>
                                    {{#each lista}}
                                    {{#each lista_detalle}}
                                    <tr>
                                       <td style="display:none">{{id_maquina}} </td>
                                       <td style="display:none" > {{filtro}} </td>
                                       <td >{{id_actividad}} </td>
                                       <td>{{descripcion}} </td>
                                       <td>{{fecha_hora}} </td>
                                       <td> {{valor}} </td>
                                       <td class="text-center"> <a class="delete" title="Delete" data-toggle="tooltip"><i class="fas fa-trash"></i></a> </td> 
                                    </tr>
                                    {{/each}}
                                    {{/each}}
                              </tbody>
                        </table>
                      </div>
                    </div>
                 </div>


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

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

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


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

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




<script>

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

</script>

<script>

//*********************
function obtIdmaquina(filtro) {
   var cad = filtro.split("/");
   return cad[0];
}
//******************************
function obtIUnico(filtro) {
   var cad = filtro.split("/");
   return cad[2];
}

//*********************
function nombreproducto (filtro) {
        var id_maquina = obtIdmaquina(filtro);
        var id_unico = obtIUnico(filtro)
        var Id_registro =  document.getElementsByName('Id_registro')[0].value;
        var descripcion = "";
        var parametro = Id_registro + '&' + id_maquina + '&' + id_unico
        var url1 = "/links/nombre-productoxmaquina/" + parametro;
         $.ajax({
            url: url1,
            type: "GET",
            dataType: "json",
            success: function (data) {
               $.each(data, function (i, item) {
                   descripcion = item.descripcion_articulo;                 
               });
               document.getElementsByName('producto')[0].value = descripcion;
            },
            error: function (error) {
               console.log(`Error ${error}`);
            }   
});
}
//*************************************************
   function filtrarmaquina(value) {
      var filtro = document.getElementsByName('maquina')[0].value;
      nombreproducto(filtro);
      $("#tabla123 tr").filter(function () {
          $(this).toggle($(this).text().indexOf(filtro) > -1)
        });

   }
</script>

<script>

   (function () {
      'use strict';
      window.addEventListener('load', function () {
         // Fetch all the forms we want to apply custom Bootstrap validation styles to
         return false;
         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>

   // Handle form submission event
function anexartabla(val) {
      var TableData;
          TableData = storeTblValues()
          TableData = JSON.stringify(TableData);
      var json =  TableData;
      document.getElementsByName('tablaActividades')[0].value = json;
      $("#actividadesturno").submit();
};

   $('#actividadesturno').on('submit', function(e){
      var TableData;
          TableData = storeTblValues()
          TableData = JSON.stringify(TableData);
      var json =  TableData;
      document.getElementsByName('tablaActividades')[0].value = json;
   });


function storeTblValues()
{
    var TableData = new Array();
    var Idsmaquina = new Array();
    var filtros = new Array();
    var Idsactividades = new Array();
    var horas = new Array();
    var valores = new Array();
    var table2 = document.getElementById('tabla123');         
         $("#tabla123 tbody tr").each(function (index) {
            var campo1 = "";
            var campo2 = "";
            var campo3 = "";
            var campo4 = "";
            var campo5 = "";
               $(this).children("td").each(function (index2) {
                  switch (index2) {
                     case 0:
                        campo1 = $(this).text().trim();
                        Idsmaquina.push(campo1);
                        break;
                     case 1:
                        campo2 = $(this).text().trim();
                        filtros.push(campo2);
                        break;
                     case 2:
                        campo3 = $(this).text().trim();
                        Idsactividades.push(campo3);
                        break;
                     case 4:
                        campo4 = $(this).text().trim();
                        horas.push(campo4);
                        break;
                     case 5:
                        campo5 = $(this).text().trim();
                        valores.push(campo5);
                        break;
                  }

               });

         });


         for(var r = 0; r < table2.rows.length; r++) {
          if (r < (table2.rows.length) - 1) {
            TableData.push({
              "Id_maquina" : Idsmaquina[r]
            , "Filtro" : filtros[r]
            , "Id_actividad" : Idsactividades[r]
            , "Fechahora" : horas[r]
            , "Valor" : valores[r]
                })                
          }          
        }


    return TableData;
}




</script>

<script>

$(document).ready(function() { 
filtrarmaquina(0);
 $('form #btn-ok').click(function(e) {
        cambiarstatus(0);        
      //  let $form = $(this).closest('turnoopen01');

        const swalWithBootstrapButtons = Swal.mixin({
            customClass: {
                confirmButton: 'btn btn-success',
                cancelButton: 'btn btn-danger'
            },
            buttonsStyling: false,
        })

  swalWithBootstrapButtons.fire({
            title: 'Se actualizaran las Actividades ',
            text: "Verifique",
          //  type: 'warning',
            showCancelButton: true,
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            reverseButtons: true
        }).then((result) => {
            if (result.value) {
                swalWithBootstrapButtons.fire(
                        'Finished',
                        'Success',
                        'success',
                    );   
                 anexartabla(0);
            } else if (
                result.dismiss === Swal.DismissReason.cancel
            ) {
                swalWithBootstrapButtons.fire(
                    'Canceled',
                    'realiza las correcciones necesarias',
                   'error'
                );
            }
        });

 });
});

</script>

<script>
//******************
function adjust(v){
   if(v>9){
      return v.toString();
   }else{
     return '0'+v.toString();
   }
}
//*******************

function addactividad(value) {
   var trHTML;
   var id_actividad = document.getElementsByName('idactividad')[0].value ; 
   var actividad = document.getElementById('idactividad1') ; 
   var descripcion =  actividad.options[actividad.selectedIndex].text;
   var valor = document.getElementsByName('valor')[0].value ;
   var id_maquina = document.getElementsByName('maquina')[0].value ; 
   var maquina = document.getElementById('idmaquina1') ; 
   var desMaquina = maquina.options[maquina.selectedIndex].text;
   var filtro = id_maquina + '-' + desMaquina;

var today = new Date();
var date = adjust(today.getDate()) + '-' + adjust(today.getMonth()+1) + '-' + today.getFullYear()
var time = adjust(today.getHours()) + ":" + adjust(today.getMinutes());
var dateTime = `${date}T${time}`;

   if (valor.length <= 0) {
      valor = 'N/A'
   }

   if (id_actividad.length > 0) {
       trHTML = '<tr> <td style="display:none">' + id_maquina + '</td>' + '<td style="display:none">' + filtro +  '</td><td>' + id_actividad + '<td>' + descripcion +  '</td><td>'  + dateTime + '</td><td>' + valor + '</td><td> <a class="delete" title="Delete" data-toggle="tooltip"><i class="fas fa-trash"></i></a>  </td></tr>  ';     
        $('#tabla123').append(trHTML);
        document.getElementsByName('valor')[0].value = '';
   }
}


</script>

<script>

$(document).ready(function() { 

 $('form #btn-agregar').click(function(e) {
        addactividad(0);     
 });

$(document).on("click", ".delete", function(){
        $(this).parents("tr").remove();
		$(".add-new").removeAttr("disabled");
   });


});


</script>
