<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> Consumo de Materia Prima por Maquina</h3>
            </div>
            <div class="card-body">
               <!-- COMIENZO DEL FORMULARIO -->
               <form id="consumoturno" action="/links/consumo-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" 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" value={{ eldia }} required>
                     </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"  style="text-align:right;" class="form-control" placeholder="" name="indextable" >                         
                        <input type="hidden"  style="text-align:right;" class="form-control" placeholder="" name="tipo_de_submit"  value=0 >
                      </div>

                      <div class="input-group">
                        <input type="hidden"   class="form-control"  name="inputtabladetalle" > 
                        <input type="hidden"   class="form-control"    name="Id_registro"  value = {{lista.1.newParam.idreg}} > 
                        <input type="hidden"   class="form-control"   name="tablamateriaprima"  value = "" > 
                        <input type="hidden"  class="form-control"   name="unidad"  value = "" > 
                        <input type="hidden"  class="form-control"   name="tabladeeliminados"  value = "" > 
                        <input type="hidden"  class="form-control"   name="idplantilla"  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-2 mb-3">
                            <label class="font-weight-bold" for="cliente">Materia Prima</label>
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="" name="idmateriaprima"     onkeypress="return false;">
                                <div class="input-group-append">
                                <button href="#" class="btn btn-secondary"  id= "btn-mpct" data-toggle="modal" data-target="#modalPlanes"  type="button">     <i class="fa fa-search"></i> 
                                </button>
                                </div>  
                            </div>
                            </div>

                            <div class="col-md-3 mb-3">
                            <label class="font-weight-bold" for="descliente">Descripcion</label> 
                            <div class="input-group">
                                <input class="form-control" type="text" placeholder=""  readonly id="des-materiaprimaid" name="des-materiaprima" > 
                                
                            </div>
                            </div>

                            <div class="col-md-2 mb-3">
                            <label class="font-weight-bold" for="descliente">Cantidad</label> 
                            <div class="input-group">
                                <input type="number"  style="text-align:right;" class="form-control" placeholder="Cantidad" name="cantidad1">                         
                            </div>
                            </div>


                            <div class="col-md-2 mb-3">
                            <label class="font-weight-bold" for="descliente">Accion</label> 
                            <div class="input-group">
                                <button type="button" id="btnCrear" class="btn btn-outline-primary   mt-8"    onclick="addmateriaprima(0)"><i class='fas fa-plus-circle'  ></i> </button> 

                                <button  class="btn btn-outline-info"   id= "btn-plantilla" data-toggle="modal" data-target="#modalplantilla"  type="button"><i class='fas fa-plus-circle'></i> 
                            </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%" >Materia Prima</th>
                                    <th   width="10%" >Unidad</th>
                                    <th   width="20%" >Cantidad</th>
                                    <th   width="10%" >Acumulado</th>
                                    <th  class='text-center'  width="10%">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 >{{Idmp}} </td>
                                       <td>{{Materiaprima}} </td>
                                       <td>{{unidad}} </td>
                                       <td> <input type="number"  style="text-align:right;" class="form-control" placeholder="cantidad" value = "0" name="cantidad"      ></td>
                                       <td> <input type="number"  style="text-align:right;" class="form-control"  readonly value = "{{cantidad}}" name="acumulado"      ></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>
                  <div class="form-row">
                        <div style="display:none" > 
                        <table id="tabledeleted">
                              <thead>
                                 <tr>
                                    <th>ID materia prima</th>
                                    <th>ID maquina</th>
                                 </tr>
                              </thead>   
                              <tbody>

                              </tbody>    
                        </table>
                        </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 addplantilla() {
   event.preventDefault();
   event.stopPropagation();
   var id_materiaprima, descripcion, cantidad, unidad,trHTML,filtro,id_maquina;
   id_materiaprima = ""; 
   descripcion = "" ; 
   cantidad = 0 ;
   unidad = ""; 
   var id = document.getElementsByName('idplantilla')[0].value ; 
   var url1 = "/links/api-materiaprimaplantilla/" + id;

$.ajax({
    url: url1,
    type: "GET",
    dataType: "json",
    success: function (data) {
        var trHTML = '';
        $.each(data, function (i, item) {
           id_materiaprima = item.id_materiaprima; 
           descripcion = item.descripcion;
           cantidad = item.cantidad;
           filtro = document.getElementsByName('maquina')[0].value;
           id_maquina = obtIdmaquina(filtro);
           if (item.unidad == null) {
                unidad =  " " ;
           }else {
              unidad = item.unidad;
           }
           trHTML = '<tr> <td style="display:none">' + id_maquina + '</td><td style="display:none">' + filtro + '</td><td width="5%">' + id_materiaprima + '</td>' + '<td width="45%">' + descripcion +  '</td><td width="10%">'   + unidad  +  '</td> <td> <input type="number"  style="text-align:right;" class="form-control" placeholder="cantidad" value = "' + cantidad + '" name="cantidad"></td> <td width="10%"> <input type="number"  style="text-align:right;" class="form-control"  value = "0" name="acumulado"  readonly ></td><td class="text-center"> <a class="delete" title="Delete" data-toggle="tooltip"><i class="fas fa-trash"></i></a></td></tr> ';
           $('#tabla123').append(trHTML);
        });

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


}
//*************************************************************************

function mostrarcatalogoPlantilla() {

         var url1 = "/links/listar-plantillactl";
         var table9 = $('#tablaplantilla').DataTable();

            table9.clear()
            table9.draw();

            $.ajax({
                type: "GET",
                url: url1,
                datatype: "json",
                traditional: true
            })
            .done(function (data) {
                  var groupColumn = 0;        
                  var table = $('#tablaplantilla').DataTable({

                      data:  data,
                      destroy: true,
              "columns":[
               { "data": "id", "title": "ID" },
               { "data": "descripcion", "title": "Descripción" },
               { "defaultContent": "<div class='text-center'> <div class='btn-group'> <button class='btn btn-info btn-sm btnAceptarPlantilla'>Seleccionar</button> </div> </div>" }
             ],
             pageLength : 10,
             lengthMenu: [[5, 10, 20, -1], [5, 10, 20, 'Todos']],
            "scrollY": 400,
            "scrollX": true,
            "order": [[ groupColumn, 'asc' ]],
            "displayLength": 25
    }); // fin de datatable declaracion                 
            });

}

 
//*********************
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 obtIdmaquina(filtro) {
   var cad = filtro.split("/");
   return cad[0];
}
//******************************
function obtIUnico(filtro) {
   var cad = filtro.split("/");
   return cad[2];
}

//*******************************
function addmateriaprima(value) {
   event.preventDefault();
   event.stopPropagation();
   var id_materiaprima, descripcion, cantidad, unidad,filtro, id_maquina, trHTML;
   id_materiaprima = document.getElementsByName('idmateriaprima')[0].value ; 
   descripcion = document.getElementsByName('des-materiaprima')[0].value ; 
   cantidad = parseFloat('0' + document.getElementsByName('cantidad1')[0].value) ;
   filtro = document.getElementsByName('maquina')[0].value;
   id_maquina = obtIdmaquina(filtro);
   unidad = document.getElementsByName('unidad')[0].value ; 
   if (id_materiaprima.length > 0) {
        trHTML = '<tr> <td style="display:none">' + id_maquina + '</td><td style="display:none">' + filtro + '</td><td width="5%">' + id_materiaprima + '</td>' + '<td width="45%">' + descripcion +  '</td><td width="10%">'   + unidad  +  '</td> <td> <input type="number"  style="text-align:right;" class="form-control" placeholder="cantidad" value = "' + cantidad + '" name="cantidad"></td> <td width="10%"> <input type="number"  style="text-align:right;" class="form-control"  value = "0" name="acumulado"  readonly ></td><td class="text-center"> <a class="delete" title="Delete" data-toggle="tooltip"><i class="fas fa-trash"></i></a></td></tr> ';
        $('#tabla123').append(trHTML);
        document.getElementsByName('idmateriaprima')[0].value = '';
        document.getElementsByName('des-materiaprima')[0].value = ''; 
        document.getElementsByName('cantidad1')[0].value = 0 ; 
   }
}
//*****************************************

function addeliminados( id_mp, id_maquina) {
   var id_materiaprima, id_maq, trHTML;
   id_materiaprima = id_mp; 
   id_maq = id_maquina; 
   trHTML = '<tr><td>' + id_materiaprima + '</td><td>' + id_maq + '</td> </tr>';
   $('#tabledeleted').append(trHTML);
}


//*********************
function mostrarcatalogo() {

         var url1 = "/links/listar-materiaprima9";
         var table9 = $('#tablaproductos').DataTable();

            table9.clear()
            table9.draw();

            $.ajax({
                type: "GET",
                url: url1,
                datatype: "json",
                traditional: true
            })
            .done(function (data) {
                  var groupColumn = 0;        
                  var table = $('#tablaproductos').DataTable({
                      data:  data,
                      destroy: true,
              "columns":[
               { "data": "id", "title": "ID" },
               { "data": "codigo", "title": "Código" },
               { "data": "descripcion", "title": "Descripción" },
               { "data": "unidad", "title": "Unidad" },
               { "defaultContent": "<div class='text-center'> <div class='btn-group'> <button class='btn btn-info btn-sm btnAceptarP'>Seleccionar</button> </div> </div>" }
             ],
             pageLength : 10,
             lengthMenu: [[5, 10, 20, -1], [5, 10, 20, 'Todos']],
            "scrollY": 400,
            "scrollX": true,
            "order": [[ groupColumn, 'asc' ]],
            "displayLength": 25
    }); // fin de datatable declaracion                 
            });

}

//****************
$(document).ready(function() { 

 $('form #btn-mpct').click(function(e) {
    mostrarcatalogo();    
 });
 
$('form #btn-plantilla').click(function(e) {
   mostrarcatalogoPlantilla();
 });


$(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");
});


});

//****************

</script>



<script>

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

</script>

<script> 
   function filtrarmaquina(value) {
      var filtro = document.getElementsByName('maquina')[0].value;
      nombreproducto(filtro)
      $("#tabla123 tbody>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('tablamateriaprima')[0].value = json;
      anexartablaEliminados();
      $("#consumoturno").submit();
};

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


function storeTblValues()
{
    var TableData = new Array();
    var IdsMp = new Array();
    var IdsMaq = new Array();
    var filtosA = new Array();
         var table2 = document.getElementById('tabla123');
         

         $("#tabla123 tbody tr").each(function (index) {
            var campo1 = "";
            var campo2 = "";
            var campos3 ="";
               $(this).children("td").each(function (index2) {
                  switch (index2) {
                     case 0:
                        campo2 = $(this).text().trim();
                        IdsMaq.push(campo2)
                        break;
                     case 1:
                        campo3 = $(this).text().trim();
                        filtosA.push(campo3)
                        break;
                     case 2:
                        campo1 = $(this).text().trim();
                        IdsMp.push(campo1)
                        break;
                  }

               });

         });


         for(var r = 0; r < table2.rows.length; r++) {
          if (r < (table2.rows.length) - 1) {
            TableData.push({
              "Id_maquina" : IdsMaq[r]
            , "Id_materiaprima" : IdsMp[r]
            , "filtro" : filtosA[r]
            , "cantidad" : document.getElementsByName('cantidad')[r].value
                })                
          }          
        }


    return TableData;
}

//**************************************************************************

function anexartablaEliminados() {
      var TableData;
          TableData = storeTblValuesEliminados()
          TableData = JSON.stringify(TableData);
      var json =  TableData;
      document.getElementsByName('tabladeeliminados')[0].value = json;
};

//**************************************************************************

function storeTblValuesEliminados()
{
    var TableData = new Array();
    var IdsMp = new Array();
    var IdsMaqui = new Array();
         var table2 = document.getElementById('tabledeleted');
         $("#tabledeleted tbody tr").each(function (index) {
            var campo1 = "";
            var campos2 ="";
               $(this).children("td").each(function (index2) {
                  switch (index2) {
                     case 0:
                        campo1 = $(this).text().trim();
                        IdsMp.push(campo1)
                        break;
                     case 1:
                        campo2 = $(this).text().trim();
                        IdsMaqui.push(campo2)
                        break;
                  }

               });

         });

        for(var r = 0; r < table2.rows.length; r++) {
          if (r < (table2.rows.length) - 1) {
            TableData.push({
              "Id_materiaprimaD" : IdsMp[r]
              ,"Id_maquinaD" : IdsMaqui[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 actualizara  el consumo de Materia Prima',
            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>

{{>catalogomateria-prima2 }}

{{>catalogo-plantillas }}