<?php 
include_once('../../../php/sessionStart.php'); 
include_once('../../../php/db/dbExec.php');
include_once('../../../php/timezone.php');

$dtFec=date("Y-m-d");
$nAnio=date("Y");
$nMes=date("m");

$empCod = $_SESSION['empCod'];
$empNom = $_SESSION['empNom'];
$empNit = $_SESSION['empNit'];

# QUERYS

$sMeses = "SELECT * FROM meses";
$sTipomaq = "SELECT * FROM tipomaquina where tm_emp='$empCod' ORDER BY tm_nom";
$sLineapro = "SELECT * FROM lineapro ORDER BY lp_num";
$sBodegapro = "SELECT * FROM bodegapro ORDER BY bp_cod";

# EJECUCION DE QUERYS
$db = new dbExec();
$select["meses"] = $db->query($sMeses);
$select["tipomaquina"] = $db->query($sTipomaq);
$select["tipomaquinam"] = $db->query($sTipomaq);
$select["lineapro"] = $db->query($sLineapro);
$select["bodegapro"] = $db->query($sBodegapro);
$anoTrab=date("Y");
$mesTrab=date("m");
?>
<?php include_once('../includes/htmlOpen.php'); ?>
    <main class="main" style="">
      <?php 
        $li[0] = '<i class="fas fa-file-invoice"></i>';
        $li[1] = $_GET["opcNom"];
        include_once('../../../php/includes/ol.php');
      ?>

      <!-- MODAL DETALLE DOCUMENTO -->
      <div class="modal fade" id="modalDetao" tabindex="-1" role="dialog" aria-labelledby="modalDetaoTitle" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable modal-xl" role="document">
          <div class="modal-content bg-dark">
            <div class="modal-header">
              <ul class="nav nav-pills" id="pills-tab" role="tablist">
                <li class="nav-item">
                  <a class="nav-link active" id="pills-00-tab" data-toggle="pill" href="#pills-00" role="tab" aria-controls="pills-00" aria-selected="true">  </a>
                </li>
<!--                <li class="nav-item">
                  <a class="nav-link" id="pills-01-tab" data-toggle="pill" href="#pills-01" role="tab" aria-controls="pills-01" aria-selected="true">Buscar Operarios</a>
                </li>   --->
              </ul>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span class="text-light" aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">

              <div class="tab-content bg-transparent border-0" id="pills-tabContent">
                <div class="tab-pane fade show active" id="pills-00" role="tabpanel" aria-labelledby="pills-00-tab">
                  
                  <form action="" name="" autocomplete="off" enctype="multipart/form-data">
                    <div class="form-group">
                      <div class="form-row">
                        <div class="col-1">
                          <label class="font-size-md text-success" for="numLineadm">Numero</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numLineadm" maxlength="4">
                        </div>
                        <div class="col-3">
                          <label class="font-size-md text-success" for="txtDescdm">Operación</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtDescdm" maxlength="50">
                        </div>
                        <div class="col-2">
                          <label for="selTipoMaqm" class="font-size-md text-success">Tipo Maquinaria</label>
                          <select class="form-control form-control-sm form-control-as" name="selTipomaqm" id="selTipomaqm">
                            <?php
                              while ($rec = $db->fetchAssoc($select['tipomaquinam'])) {
                                echo  "<option value={$rec['tm_cod']}>".utf8_encode($rec['tm_nom']).'</option>';
                              }
                            ?>
                          </select>
                        </div>
       <!--                 <div class="col-1">
                          <label class="font-size-md text-success" for="numCodemplem">Operario</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numCodemplem" maxlength="8">
                        </div>
                        <div class="col-4">
                          <label class="font-size-md text-success" for="txtCodempleNomm">Nombre</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCodempleNomm" maxlength="80" disabled>
                        </div>   --->
                      </div>
                      <div class="form-row">
                        <div class="col-1">
                          <label class="font-size-md text-success" for="txtCatm">Categoria</label>
                          <input type="text" class="form-control form-control-sm form-control-as" id="txtCatm" maxlength="4">
                        </div>
                        <div class="col-1">
                          <label class="font-size-md text-success" for="numUnim">Unidad</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numUnim" maxlength="4">
                        </div>
                        <div class="col-1">
                          <label class="font-size-md text-success" for="numHoram">Hora</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numHoram" maxlength="6">
                        </div>
                        <div class="col-1">
                          <label class="font-size-md text-success" for="numMetam">Meta</label>
                          <input type="number" class="form-control form-control-sm form-control-as" id="numMetam" maxlength="6">
                        </div>
                        <div class="col-2">
                          <label class="font-size-md text-success" for="numValorm">Valor Unidad ó Par</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-3" id="numValorm" maxlength="13">
                        </div>
                        <div class="col-2">
                          <label class="font-size-md text-success" for="numDiariom">Diario</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numDiariom" maxlength="13">
                        </div>
                        <div class="col-2">
                          <label class="font-size-md text-success" for="numQuincenam">Quincena</label>
                          <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numQuincenam" maxlength="13">
                        </div>
                      </div>
                    </div>
                    <button type="button" class="btn btn-success btn-block" id="btnAgregar">Agregar</button>
                    <button type="button" class="btn btn-success btn-block" id="btnModificar">Modificar</button>
                  </form>
                </div>
<!--                <div class="tab-pane fade" id="pills-01" role="tabpanel" aria-labelledby="pills-01-tab">
                  <?php
              //      $a='00';
              //      $b='01';
              //      include('../busEmpleado3/index.html');
                  ?>
                </div>   --->
              </div>

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

      <div class="container-as">
        <div class="row">
          <div class="col">
            <ul class="nav nav-pills mb-1" id="pills-tab" role="tablist">
              <li class="nav-item">
                <a class="nav-link active" id="pills-0-tab" data-toggle="pill" href="#pills-0" role="tab" aria-controls="pills-0" aria-selected="true">Mantenimiento</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" id="pills-1-tab" data-toggle="pill" href="#pills-1" role="tab" aria-controls="pills-1" aria-selected="true">Buscar Supervisor</a>
              </li>
<!--              <li class="nav-item">
                <a class="nav-link" id="pills-2-tab" data-toggle="pill" href="#pills-2" role="tab" aria-controls="pills-2" aria-selected="true">Buscar Operarios</a>
              </li>   --->
            </ul>
            <div class="tab-content bg-transparent border-0" id="pills-tabContent">
              <div class="tab-pane fade show active" id="pills-0" role="tabpanel" aria-labelledby="pills-0-tab">

                <form action="" name="thisform" autocomplete="off" enctype="multipart/form-data">
                  <div class="form-row">
                    <div class="col-md-10">
                      <div class="form-group">
                        <div class="form-row align-items-center">
                          <div class="col-md-12">
                            <div class="form-row align-items-end">
                              <div class="col-2">
                                <label class="font-size-lg" for="txtCod">Estilo</label>
                                <input type="text" class="form-control form-control-sm form-control-as" id="txtCod" maxlength="30">
                              </div>
                              <div class="col-8">
                                <label class="font-size-lg" for="txtDesc">Tipo de Prenda</label>
                                <input type="text" class="form-control form-control-sm form-control-as" id="txtDesc" maxlength="80">
                              </div>
                            </div>
                            <div class="form-row align-items-end">
                              <div class="col-3">
                                <label for="selBodegapro">Bodega</label>
                                <select class="form-control form-control-sm form-control-as" name="selBodegapro" id="selBodegapro">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['bodegapro'])) {
                                      echo  "<option value={$rec['bp_cod']}>".utf8_encode($rec['bp_nom']).'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                              <div class="col-1">
                                <label for="selLineapro">Linea</label>
                                <select class="form-control form-control-sm form-control-as" name="selLineapro" id="selLineapro">
                                  <?php
                                    while ($rec = $db->fetchAssoc($select['lineapro'])) {
                                      echo  "<option value={$rec['lp_num']}>".$rec['lp_num'].'</option>';
                                    }
                                  ?>
                                </select>
                              </div>
                              <div class="col-1">
                                <label class="font-size-sm" for="numCods">Supervisor</label>
                                <input type="number" class="form-control form-control-sm form-control-as" id="numCods">
                              </div>
                              <div class="col-4">
                                <label class="font-size-sm" for="txtSupervNom">Nombre</label>
                                <input type="text" class="form-control form-control-sm form-control-as" id="txtSupervNom" maxlength="80" disabled>
                              </div>
                              <div class="col-md-2.5">
                                <label for="dtFec">Fecha</label>
                                <input type="date" class="form-control form-control-sm form-control-as" id="dtFec" placeholder="">
                              </div>
                            </div>
                          </div>
                        </div>

                        <div class="form-row">
                        </div>
                      </div>

                      <h3 class="text-light"></h3>
                      <div class="form-group">
                        <h4 class="text-success">DETALLE DE PRECIOS:</h4>
                        <div class="form-row">
                          <div class="col-1">
                            <label class="font-size-md text-success" for="numLinead">Numero</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numLinead" maxlength="4">
                          </div>
                          <div class="col-3">
                            <label class="font-size-md text-success" for="txtDescd">Operación</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtDescd" maxlength="50">
                          </div>
                          <div class="col-2">
                            <label for="selTipoMaq" class="font-size-md text-success">Tipo Maquinaria</label>
                            <select class="form-control form-control-sm form-control-as" name="selTipomaq" id="selTipomaq">
                              <?php
                                while ($rec = $db->fetchAssoc($select['tipomaquina'])) {
                                  echo  "<option value={$rec['tm_cod']}>".utf8_encode($rec['tm_nom']).'</option>';
                                }
                              ?>
                            </select>
                          </div>
    <!--                      <div class="col-1">
                            <label class="font-size-md text-success" for="numCodemple">Operario</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numCodemple">
                          </div>
                          <div class="col-4">
                            <label class="font-size-md text-success" for="txtCodempleNom">Nombre</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCodempleNom" maxlength="80" disabled>
                          </div>    --->
                        </div>
                        <div class="form-row">
                          <div class="col-1">
                            <label class="font-size-md text-success" for="txtCat">Categoria</label>
                            <input type="text" class="form-control form-control-sm form-control-as" id="txtCat" maxlength="4">
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-success" for="numUni">Unidad</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numUni" maxlength="4">
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-success" for="numHora">Hora</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numHora" maxlength="6">
                          </div>
                          <div class="col-1">
                            <label class="font-size-md text-success" for="numMeta">Meta</label>
                            <input type="number" class="form-control form-control-sm form-control-as" id="numMeta" maxlength="6">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numValor">Valor Unidad ó Par</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-3" id="numValor" maxlength="13">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numDiario">Diario</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numDiario" maxlength="13">
                          </div>
                          <div class="col-2">
                            <label class="font-size-md text-success" for="numQuincena">Quincena</label>
                            <input type="number" class="form-control form-control-sm form-control-as dec-2" id="numQuincena" maxlength="13">
                          </div>
                        </div>
                        <div class="form-row align-items-end">
                        </div>
                      </div>

                      <div class="form-group">
                        <div class="form-row">
                          <div class="col-11 text-left">
                            <button type="button" class="btn btn-success" id="btnAdd">
                              <i class="fas fa-plus-circle"></i> Agregar a tabla
                            </button>
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-12 text-right mb-2">
                          </div>
                        </div>
                        <div class="form-row">
                          <div class="col-md-12">
                            <div class="table-responsive">
                              <table class="table table-hover table-bordered table-dark table-sm" id="tblDetao">
                                <thead>
                                  <tr>
                                    <th scope="col" class="text-center ignore" width="20">ACCIONES</th>
                                    <th scope="col" class="text-center" width="10">NUMERO</th>
                                    <th scope="col" class="text-center" width="100">OPERACIÓN</th>
                                    <th scope="col" class="text-center" width="100">MAQUINARIA</th>
                <!--                    <th scope="col" class="text-center" width="40">OPERARIO</th>    --->
                                    <th scope="col" class="text-center" width="50">CAT</th>
                                    <th scope="col" class="text-center" width="50">UNIDAD</th>
                                    <th scope="col" class="text-center" width="50">HORA</th>
                                    <th scope="col" class="text-center" width="50">META</th>
                                    <th scope="col" class="text-center" width="50">VALOR</th>
                                    <th scope="col" class="text-center" width="50">DIARIO</th>
                                    <th scope="col" class="text-center" width="50">QUINCENA</th>
                                  </tr>
                                </thead>
                                <tbody>
                                </tbody>
                                <tfoot>
                                  <th scope="col" class="ignore"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
              <!--                    <th scope="col"></th>       ---->
                                  <th scope="col" class="text-right">Totales</th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col"></th>
                                  <th scope="col" id="dataTValor" class="text-right">0.000</th>
                                  <th scope="col" id="dataTDiario" class="text-right">0.00</th>
                                  <th scope="col" id="dataTQuincena" class="text-right">0.00</th>
                                </tfoot>
                              </table>
                            </div>
                          </div>
                        </div>
                      </div>

                      <h3 class="text-light"></h3>

                      <div class="form-group">
                        <div class="form-row">
                        </div>
                      </div>
                    </div>

                    <div class="col-md-2">
                      <div class="form-group position-fixed-md">

                        <div class="form-row">
                          <div class="col-12 mt-4">
                            <button class="btn btn-warning btn-block" id="btnGuardarImprimir" type="button">Imprimir/Guardar</button>
                          </div>
                          <div class="col-12 mt-4">
                            <button class="btn btn-success btn-block" id="btnGuardar" type="button">Guardar</button>
                          </div>
                          <div class="col-12 mt-4">
                            <button class="btn btn-primary btn-block" id="btnBorrar" type="button">Borrar</button>
                          </div>
                          <div class="col-3 col-md-12"></div>
                        </div>
                      </div>
                    </div>
                  </div>
                </form>
              </div>
              <div class="tab-pane fade" id="pills-1" role="tabpanel" aria-labelledby="pills-1-tab">
                <?php
                  $a='0';
                  $b='1';
                  include('../busEmpleado/index.html');
                ?>
              </div>
<!--              <div class="tab-pane fade" id="pills-2" role="tabpanel" aria-labelledby="pills-2-tab">
                <?php
              //    $a='0';
              //    $b='2';
              //    include('../busEmpleado2/index.html');
                ?>
              </div>    --->
            </div>
          </div>
        </div>
      </div>
    </main>
<?php include_once('../../../php/includes/htmlClose.php'); ?>

<script>
  var pressEnter = false;
  var nuevo = true;
  var nuevoArtic = true;
  var mesCerrado = false;
  var inputCtaMov = "txtCta";
  var totant = 0;
  var inputDocp = "numNum";
  var tblDetaoAnt;
  var tblPolAnt;
  var btnAddEdit = "00";
  var inputEstilo = "txtCod";
  var inputEmple = "numCods";
  var unimed = "XXX";
  var txtestilo ="";
  var ctaInc = false;

  const txtCod = document.thisform.txtCod;
  const txtDesc = document.thisform.txtDesc;
  const numCods = document.thisform.numCods;
  const txtSupervNom = document.thisform.txtSupervNom;

  const numLinead = document.thisform.numLinead;
  const txtDescd = document.thisform.txtDescd;
  const selTipomaq = document.thisform.selTipomaq;
//  const numCodemple = document.thisform.numCodemple;
//  const txtCodempleNom = document.thisform.txtCodempleNom;
  const txtCat = document.thisform.txtCat;
  const numUni = document.thisform.numUni;
  const numHora = document.thisform.numHora;
  const numMeta = document.thisform.numMeta;
  const numValor = document.thisform.numValor;
  const numDiario = document.thisform.numDiario;
  const numQuincena = document.thisform.numQuincena;

  const numLineadm = document.getElementById("numLineadm");
  const txtDescdm = document.getElementById("txtDescdm");
  const selTipomaqm = document.getElementById("selTipomaqm");
//  const numCodemplem = document.getElementById("numCodemplem");
//  const txtCodempleNomm = document.getElementById("txtCodempleNomm");
  const txtCatm = document.getElementById("txtCatm");
  const numUnim = document.getElementById("numUnim");
  const numHoram = document.getElementById("numHoram");
  const numMetam = document.getElementById("numMetam");
  const numValorm = document.getElementById("numValorm");
  const numDiariom = document.getElementById("numDiariom");
  const numQuincenam = document.getElementById("numQuincenam");

  function restriccion(){
    if (isNullPer(txtCod.value)) {
      txtCod.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar El estilo"}});
      return true;
    }
    // PARA VER SI EL DETALLE ESTA VACIO
    if ($("#tblDetao tbody").children().length == 0) {
      alWarning({"msg":{"title":"Detalle Vacío","text":"Es necesario Registrar algun detalle de las operaciones"}});
      return true;
    }
    return false;
  }
  function condicionesobligatorias(){
  }

  function restriccionMesCerrado() {
  }


  function restriccionCamposVacios() {
    if (isNullPer(txtCod.value)) {
      txtCod.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar El estilo"}});
      return true;
    }
    if (isNullPer(txtDesc.value)) {
      txtDesc.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"No puede dejar vacio el nombre de la prenda"}});
      return true;
    }
    return false;
  }

  function restriccionLinead() {
    if (isNullPer(numLinead.value)) {
      numLinead.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Debe ingresar numero de linea"}});
      return true;
    }
    return false;
  }

  function restriccionLineadm() {
    if (isNullPer(numLineadm.value)) {
      numLineadm.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Debe ingresar numero de linea"}});
      return true;
    }
    return false;
  }

/*  function restriccionCoddm() {
    if (isNullPer($("#"+inputArtic).val())) {
      $("#txtDescdm").val("");
      return true;
    }
    return false;
  }  */

  function restriccionModal() {
    if (isNullPer(numLineadm.value)) {
      numLineadm.focus();
      alWarning({"msg":{"title":"Campo Vacío","text":"Debe ingresar numero de Operacion"}});
      return true;
    }
    $('#modalDetao').modal('toggle');
   return false;
  }


  function addRowDetao(linead, descd, tipomaq, tipomaqn, codempled, codemplenomd, catd, unid, horad, metad, valord, diariod, quincenad){
    const row = "<tr>"
                +"<td scope='col' class='ignore'>"
                  +"<div class='btn-group btn-group-sm' role='group' aria-label='Third group'>"
                    +"<button type='button' class='btn btn-danger btn-sm btn-actions' id='btnDel'><i class='fas fa-trash-alt'></i></button>"
                    +"<button type='button' class='btn btn-primary btn-sm btn-actions' id='btnEdit' data-toggle='modal' data-target='#modalDetao'><i class='fas fa-edit'></i></button>"
                  +"</div>"
                +"</td>"
                +"<td id='dataLinead'>"+linead+"</td>"
                +"<td id='dataDescd'>"+descd+"</td>"
                +"<td id='dataTipomaqd' class='d-none'>"+tipomaq+"</td>"
                +"<td id='dataTipomaqnd'>"+tipomaqn+"</td>"
                +"<td id='dataCodempled' class='d-none'>"+codempled+"</td>"
                +"<td id='dataCodempleNomd' class='d-none'>"+codemplenomd+"</td>"
                +"<td id='dataCatd'>"+catd+"</td>"
                +"<td id='dataUnid' class='text-right'>"+unid+"</td>"
                +"<td id='dataHorad' class='text-right'>"+horad+"</td>"
                +"<td id='dataMetad' class='text-right'>"+metad+"</td>"
                +"<td id='dataValord' class='text-right'>"+valord+"</td>"
                +"<td id='dataDiariod' class='text-right'>"+diariod+"</td>"
                +"<td id='dataQuincenad' class='text-right'>"+quincenad+"</td>"
                +"</tr>";
    $("#tblDetao tbody").append(row);
  }

  function guardarDoc(imprimir = false){
    if (restriccion()) {return};
    if (isNullPer(txtDesc.value)) {
        txtDesc.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar El Tipo de Prenda"}});
        return true;
    } 
    if (isNullPer(numCods.value)) {
        numCods.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar El Codigo del Supervisor"}});
        return true;
    } 

    txtestilo=txtCod.value;

    colDetao = ["acciones", "numd", "descd", "tipomaqd", "tipomaqnd", "codempled", "codemplend", "catd", "unid", "horad", "metad", "valord", "diariod", "quincenad"];

    const parametros = new FormData();

    parametros.append("action", "guardar");

    parametros.append("nuevo", nuevo);
    parametros.append("txtCod", txtCod.value);
    parametros.append("txtDesc", txtDesc.value);
    parametros.append("selBodegapro", selBodegapro.value);
    parametros.append("selLineapro", selLineapro.value);
    parametros.append("numCods", numCods.value);
    parametros.append("txtSupervNom", txtSupervNom.value);
    parametros.append("dtFec", dtFec.value);
    parametros.append("tblDetao", tblToJson(colDetao, "tblDetao", 0));

    txtCod.focus();
    
    $.ajax({
      data:  parametros,
      url:   window.location.origin+window.location.pathname+"actions.php",
      type:  "post",
      contentType: false,
      processData: false,
      async: true,
      beforeSend: function () {
        alLoad("Cargando...")
      },
      success: function (jsonPhp) {
        //console.log(jsonPhp);
        setTimeout(function () {
        const jsonJS = JSON.parse(jsonPhp);

        if(jsonJS.error==true){
          alError(jsonJS);
        } else {
          if (imprimir) {
            imprimirDoc(txtestilo);
          }
          limpiar();
          tblClear("tblDetao");
          sumDetao();
          alSuccess(jsonJS);
          //location.reload();
        }

        }), 0;
      }
    });
  }

  function imprimirDoc(txtestilo){

    const gettxtestilo = "?txtestilo="+txtestilo;

    var url = window.location.origin+window.location.pathname+"print.php"+gettxtestilo;

    window.open(url, '_blank');
  }



  function limpiarModalDetao(){
    numLineadm.value = "";
    txtDescdm.value = "";
//    numCodemplem.value = "";
//    txtCodempleNomm.value = "";
    txtCatm.value = "";
    numUnim.value = "";
    numHoram.value = "";
    numMetam.value = "";
    numValorm.value = (0).toFixed(2);
    numDiariom.value = (0).toFixed(2);
    numQuincenam.value = (0).toFixed(2);
  }

  function limpiar(todo = false){
    txtCod.value= "";
    txtDesc.value = "";
    numCods.value = "";
    txtSupervNom.value = "";
  }

  function limpiarDetao(){
    //numLinead.value =""
    txtDescd.value = "";
//    numCodemple.value = "";
//    txtCodempleNom.value = "";
    txtCat.value = "";
    numUni.value = "";
    numHora.value = "";
    numMeta.value = "";
    numValor.value = (0).toFixed(2);
    numDiario.value = (0).toFixed(2);
    numQuincena.value = (0).toFixed(2);
  }


  function sumDetao(){
    $("#tblDetao #dataTValor").text(tblSumCol("tblDetao", "dataValord").toFixed(3));
    $("#tblDetao #dataTDiario").text(tblSumCol("tblDetao", "dataDiariod").toFixed(2));
    $("#tblDetao #dataTQuincena").text(tblSumCol("tblDetao", "dataQuincenad").toFixed(2));
  }

  function calcularValores(txtThis) {
    const subFijo = (txtThis.substr(-1)=='m') ? 'm' : '';

//    const uni = $('#numUni'+subFijo);
//    const hora = $('#numHora'+subFijo);
    const meta = $('#numMeta'+subFijo);
    const valor = $('#numValor'+subFijo);
    const diario = $('#numDiario'+subFijo);
    const quincena = $('#numQuincena'+subFijo);
    diario.val(round((meta.val()*valor.val()),6).toFixed(2));
    quincena.val(round((diario.val()*12),6).toFixed(2));
  }


  $(document).ready(function() {
    $(this).find('input:visible:first').focus();
    //document.thisform.dtFec.value = '<?php echo $dtFec; ?>';
    //document.thisform.dtFvalida.value = '<?php echo $dtFec; ?>';
    txtCod.value="";
    numCods.value = "";
//    numCodemple.value = "";
    dtFec.value = dateToday();

    // SHOW MODAL
    $('#modalDetao').on('shown.bs.modal', function() {
      if (!isMobile()) {
        $(this).find('input:visible:first').focus();
      }
    });


    // SUBMIT FORM
    $('form').submit(function() {
      return false;
    });

    // VALID META
    $("#numValor, #numValorm, #numMeta, #numMetam")
    .change(function() {
      calcularValores($(this).attr('id'));
      sumDetao();
    })

    // VALID PRODUCTO TERMINADO
    $("#txtCod")
    .focus(function() {
      inputEstilo = $(this).attr('id');
      txtCod.value="";
      tblClear("tblDetao");
      sumDetao();
      limpiar();
      limpiarDetao();

    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarEstilo");

      parametros.append("txtCod", txtCod.value);

      //txtNext.focus()

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        async: false,
        success: function (jsonPhp) {
          console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
          } else {
            if (isNullPer(jsonJS.festilos)) {
              nuevo=true;
            } else {
              txtDesc.value = jsonJS.festilos.fes_prenda;
              selBodegapro.value = jsonJS.festilos.fes_bod;
              selLineapro.value = jsonJS.festilos.fes_lineapro;
              numCods.value = jsonJS.festilos.fes_superv;
              txtSupervNom.value = jsonJS.festilos.mae_nom+" "+jsonJS.festilos.mae_ape;
              dtFec.value = jsonJS.festilos.fes_fec;
              jsonJS.festilos_d.forEach(function(i){
                 operarion = "";   //i.mae_nom+" "+i.mae_ape;
                 addRowDetao(i.fesd_linea, i.fesd_desc, i.fesd_maquinaria, i.tm_nom, i.fesd_codemple, operarion, i.fesd_cat, i.fesd_uni, i.fesd_hora, i.fesd_meta, i.fesd_valor, i.fesd_diario, i.fesd_quincena)
              });  
              sumDetao();
              nuevo = false;
            }
          }
        }
      });
    });


    // FOCUS prendas
    $("#txtDesc").focus(function (){
      txtCod.value=txtCod.value.toUpperCase();
      if (isNullPer(txtCod.value)) {
        txtCod.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"No puede dejar vacio el codigo del Estilo"}});
        return true;
      }
    });

    // FOCUS prendas
    $("#numLinead").focus(function (){
      if (restriccionCamposVacios()) {return};
    });

    // FOCUS Descripcion
    $("#txtDescd").focus(function (){
      if (restriccionCamposVacios()) {return};
      if (isNullPer(numLinead.value)) {
        numLinead.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Debe ingresar el numero de operacion que corresponde"}});
        return true;
      }
    });

    // FOCUS DESCRIPCION MODAL
    $("#txtDescdm").focus(function (){
      if (isNullPer(numLineadm.value)) {
        numLineadm.focus();
        alWarning({"msg":{"title":"Campo Vacío","text":"Es necesario ingresar el numero de operacion que corresponde"}});
        return true;
      }
    });

    // VALID CODIGO
    $("form[name='thisform'] #numCods")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-1-tab").click(); }
    })
    .focus(function() {
      inputEmple = $(this).attr('id');
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarEmple");
      parametros.append("numCodEmple", numCods.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
            nuevoEmple = true;
          } else {
            if (jsonJS.maestro === null) {
              nuevoEmple = true;
              numCods.focus();
              alWarning({"msg":{"title":"No Existe","text":"Este Codigo de Empleado no ha sido registrado"}});
               return true;
            } else {
              numCods.value = jsonJS.maestro.mae_cod;
              txtSupervNom.value = jsonJS.maestro.mae_nom+" "+jsonJS.maestro.mae_ape;
              nuevoEmple = false;
            }
          }
        }
      });
    });

    // VALID OPERARIOS
/*    $("#numCodemple")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-2-tab").click(); }
    })
    .focus(function() {
      inputEmple = $(this).attr('id');
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarEmple");
      parametros.append("numCodEmple", numCodemple.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
            nuevoEmple = true;
          } else {
            if (jsonJS.maestro === null) {
              nuevoEmple = true;
              numCodemple.focus();
              alWarning({"msg":{"title":"No Existe","text":"Este Codigo de Empleado no ha sido registrado"}});
               return true;
            } else {
              numCodemple.value = jsonJS.maestro.mae_cod;
              txtCodempleNom.value = jsonJS.maestro.mae_nom+" "+jsonJS.maestro.mae_ape;
              nuevoEmple = false;
            }
          }
        }
      });
    });              */

    // VALID OPERARIOS MODAL
/*    $("#numCodemplem")
    .keypress(function(e) {
      const keycode = e.keyCode || e.which;
      if (keycode == '13') {pressEnter = true;}
    })
    .keydown(function(e){
      if(ctrlBus(e)) { document.getElementById("pills-01-tab").click(); }
    })
    .focus(function() {
      inputEmple = $(this).attr('id');
    })
    .change(function (){
      txtThis = this;
      const parametros = new FormData();
      parametros.append("action", "consultarEmple");
      parametros.append("numCodEmple", numCodemplem.value);

      $.ajax({
        data:  parametros,
        url:   window.location.origin+window.location.pathname+"actions.php",
        type:  "post",
        contentType: false,
        processData: false,
        success: function (jsonPhp) {
          //console.log(jsonPhp);
          const jsonJS = JSON.parse(jsonPhp);

          if(jsonJS.error == true){
            alError(jsonJS);
            nuevoEmple = true;
          } else {
            if (jsonJS.maestro === null) {
              nuevoEmple = true;
              numCodemplem.focus();
              alWarning({"msg":{"title":"No Existe","text":"Este Codigo de Empleado no ha sido registrado"}});
               return true;
            } else {
              numCodemplem.value = jsonJS.maestro.mae_cod;
              txtCodempleNomm.value = jsonJS.maestro.mae_nom+" "+jsonJS.maestro.mae_ape;
              nuevoEmple = false;
            }
          }
        }
      });
    });         */


    // CLICK BORRAR
    $("#btnBorrar").click(function (){
      const numDoc = txtCod.value;

      txtCod.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "borrar");
        parametros.append("txtCod", numDoc);

        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Cargando...")
          },
          success: function (jsonPhp) {
            //console.log(jsonPhp);
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              txtCod.value = "";
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

/*
    // CLICK ANULAR
    $("#btnAnular").click(function (){
      const numDoc = numNum.value;
      const serieo = selSerieo.value;

      numNum.focus();

      const fnT = function(){

        const parametros = new FormData();
        parametros.append("action", "anular");
        parametros.append("selSerieo", serieo);
        parametros.append("selSerieoNom", $('#selSerieo').find('option:selected').text());
        parametros.append("numNum", numDoc);
        parametros.append("tblDetaoAnt", tblDetaoAnt);


        $.ajax({
          data:  parametros,
          url:   window.location.origin+window.location.pathname+"actions.php",
          type:  "post",
          contentType: false,
          processData: false,
          beforeSend: function () {
            alLoad("Cargando...")
          },
          success: function (jsonPhp) {
            //console.log(jsonPhp);
            const jsonJS = JSON.parse(jsonPhp);

            if(jsonJS.error==true){
              alError(jsonJS);
            } else {
              numNum.value = "";
              limpiar();
              tblClear("tblDetao");
              sumDetao();
              alSuccess(jsonJS);
            }
          }
        });
      }

      const fnF = function(){
        return true;
      }

      usuClave(fnT, fnF);
    });

    */


    // CLICK GUARDAR
    $("#btnGuardar").click(function (){
      restriccion();
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para la formula"}});
        return;
      }
      guardarDoc();
    });

    // CLICK GRABAR E IMPRIMIR
    $("#btnGuardarImprimir").click(function (){
      if (condicionesobligatorias()) {return};
      if ($("#tblDetao tbody").children().length == 0) {
        alWarning({"msg":{"title":"NO HA REGISTRADO DETALLE","text":"Primero debe registrar detalle para la formula"}});
        return;
      }
      guardarDoc(true);
    });
  });  

  // CLICK ADD
  $("body").on("click", "#btnAdd", function () {
    if (restriccionCamposVacios()) {return};
    if (condicionesobligatorias()) {return};
    if (isNullPer(numLinead.value)) {
      alWarning({"msg":{"title":"CAMPO OBLIGATORIO EN DETALLE","text":"No ha ingresado el Numerio de Operacion"}});
      return;
    }
    if (isNullPer(txtDescd.value)) {
      alWarning({"msg":{"title":"CAMPO OBLIGATORIO EN DETALLE","text":"No ha ingresado Descripcion de la operacion en el detalle"}});
      return;
    }
    tipomaqn = $("#selTipomaq option:selected").text();
    addRowDetao(numLinead.value, txtDescd.value, selTipomaq.value, tipomaqn, 0, "", txtCat.value, numUni.value, numHora.value, numMeta.value, isNullNumber(numValor.value).toFixed(3), isNullNumber(numDiario.value).toFixed(2), isNullNumber(numQuincena.value).toFixed(2));
    sumDetao();
    limpiarDetao();
    numLinead.value=Number(numLinead.value)+1;
    numLinead.focus();
  });

  // CLICK DEL
  $("body").on("click", "#btnDel", function() {
    const row = $(this).parents("tr");
    alDelete(function fn(){
      row.remove();
      sumDetao();
    });
  });

  // CLICK EDIT
  $("body").on("click", "#btnEdit", function() {
    $('#pills-00-tab').text("Modificar");
    $('#btnAgregar').hide();
    $('#btnModificar').show();

    const dataLinead = $(this).parents("tr").find("#dataLinead");
    const dataDescd = $(this).parents("tr").find("#dataDescd");
    const dataTipomaqd = $(this).parents("tr").find("#dataTipomaqd");
    const dataTipomaqnd = $(this).parents("tr").find("#dataTipomaqnd");
    const dataCodempled = $(this).parents("tr").find("#dataCodempled");
    const dataCodempleNomd = $(this).parents("tr").find("#dataCodempleNomd");
    const dataCatd = $(this).parents("tr").find("#dataCatd");
    const dataUnid = $(this).parents("tr").find("#dataUnid");
    const dataHorad = $(this).parents("tr").find("#dataHorad");
    const dataMetad = $(this).parents("tr").find("#dataMetad");
    const dataValord = $(this).parents("tr").find("#dataValord");
    const dataDiariod = $(this).parents("tr").find("#dataDiariod");
    const dataQuincenad = $(this).parents("tr").find("#dataQuincenad");

    numLineadm.value = dataLinead.text();
    txtDescdm.value = dataDescd.text();
    selTipomaqm.value = dataTipomaqd.text();
//    numCodemplem.value = dataCodempled.text();
//    txtCodempleNomm.value = dataCodempleNomd.text();
    txtCatm.value = dataCatd.text();
    numUnim.value = dataUnid.text();
    numHoram.value = dataHorad.text();
    numMetam.value = dataMetad.text();
    numValorm.value = dataValord.text();
    numDiariom.value = dataDiariod.text();
    numQuincenam.value = dataQuincenad.text();

    $("body").on("click", "#btnModificar", function() {
      if (restriccionModal()) {return};
      dataLinead.text(numLineadm.value);
      dataDescd.text(txtDescdm.value);
      dataTipomaqd.text(selTipomaqm.value);
      dataTipomaqnd.text($("#selTipomaqm option:selected").text());
      dataCodempled.text(0);
      dataCodempleNomd.text("");
      dataCatd.text(txtCatm.value);
      dataUnid.text(numUnim.value);
      dataHorad.text(numHoram.value);
      dataMetad.text(numMetam.value);
      dataValord.text(isNullNumber(numValorm.value).toFixed(3));
      dataDiariod.text(isNullNumber(numDiariom.value).toFixed(2));
      dataQuincenad.text(isNullNumber(numQuincenam.value).toFixed(2));
      limpiarModalDetao();
      sumDetao();
    });
  });



  // MODALDetao HIDDEN
  $('#modalDetao').on('hidden.bs.modal', function (e) {
    $("body").off("click", "#btnModificar");
  });


  // FOCUS PILL
  $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {
    if (!isMobile()) {
      const target = e.target.attributes.href.value;
      const relatedTarget = e.relatedTarget.attributes.href.value;

      if (target != "#pills-0") {
        $(target+' input:visible:first').focus();
      } else {
        (relatedTarget == "#pills-1") ? dtFec.focus() : 0;
        (relatedTarget == "#pills-2") ? txtCat.focus() : 0;
        (relatedTarget == "#pills-01") ? txtCatm.focus() : 0;
      }
      //$(target+' input:visible:first').focus();
    }
  });

</script>
