<?php include('./header.php'); ?>
<style type="text/css">
   .logo img {
      width: 150px;
   }

   .container .form-outer {
      width: 100%;
      overflow: hidden;
   }

   .form-outer .formulario {
      display: flex;
      width: 400%;
   }

   .form-outer .formulario .page {
      width: 25%;
      transition: margin-left 0.3s ease-in-out;
   }

   .form-outer .formulario .page .field {
      display: flex;
   }

   .form-outer .formulario .page .field button:hover {
      background-color: #66009f;
      border-color: #66009f;
   }

   .form-outer .formulario .page .field button {
      background-color: #560085;
      border-color: #560085;
   }

   .formulario .page .btns button.prev {
      margin-right: 3px !important;
      font-size: 17px;
   }

   .formulario .page .btns button.next {
      margin-left: 3px !important;
   }

   .container .progress-barra {
      display: flex;
      justify-content: space-between;
   }

   .container .progress-barra .step {
      position: relative;
      text-align: center;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
   }

   .progress-barra .step p {
      font-size: 14px;
      font-weight: 500;
      color: #666;
      margin-bottom: 8px;
      transition: 0.2s;
   }

   .progress-barra .step p.active {
      color: #560085;
   }

   .progress-barra .step .bullet {
      position: relative;
      height: 35px;
      width: 35px;
      border: 2px solid #666;
      display: inline-block;
      border-radius: 50%;
      transition: 0.2s;
      display: flex;
      align-items: center;
      justify-content: center;
   }

   .progress-barra .step .bullet.active {
      border-color: #560085;
      background: #560085;
   }

   .progress-barra .step .bullet span {
      font-weight: 500;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
   }

   .progress-barra .step .bullet.active span {
      display: none;
   }

   .progress-barra .step:last-child .bullet:before,
   .progress-barra .step:last-child .bullet:after {
      display: none;
   }

   .progress-barra .step .bullet:before,
   .progress-barra .step .bullet:after {
      position: absolute;
      content: '';
      right: -31.5rem;
      height: 3px;
      width: 31rem;
      background: #666;
   }

   .progress-barra .step .bullet.active:after {
      background: #560085;
      transform: scaleX(0);
      transform-origin: left;
      animation: animate 0.3s linear forwards;
   }

   @keyframes animate {
      100% {
         transform: scaleX(1);
      }
   }

   .progress-barra .step .check {
      position: absolute;
      font-size: 15px;
      color: #666;
      display: none;
   }

   .progress-barra .step .check.active {
      display: block;
      color: #fff;
   }
</style>

<link rel="stylesheet" href="template/plugins/toastr/toastr.min.css">

<body class="hold-transition layout-top-nav">
   <div class="wrapper">
      <div class="preloader flex-column justify-content-center align-items-center">
      </div>
      <!-- Content Wrapper. Contains page content -->
      <div class="content-wrapper">
         <!-- Content Header (Page header) -->
         <div class="content-header">
            <div class="container-fluid">
            </div><!-- /.container-fluid -->
         </div>
         <!-- /.content-header -->

         <section class="content">
            <div class="container-fluid">
               <div class="row">
                  <!-- SELECT2 EXAMPLE -->
                  <div class="col-md-12">
                     <div class="card card-default">
                        <div class="card-body button-nav">
                           <div class="row float-right">
                              <div class="col-md-12">
                                 <!-- <button class="btn btn-opcao" id="btn-import">Importar Excel</button> -->
                                 <button class="btn btn-opcao" id="btn-preview" disabled>Pré-visualizar</button>
                                 <button class="btn btn-opcao">Importar</button>
                                 <button class="btn btn-opcao botao-activo" id="btn">Nova Requisição</button>
                              </div>
                              <!-- /.col -->
                           </div>
                           <!-- /.row -->
                        </div>
                        <!-- /.card-body -->
                     </div>
                  </div>
                  <div class="col-md-12">
                     <div class="card card-default">
                        <div class="card-header">
                           <h3 class="card-title">Requisição/Aprovação</h3>
                           <div class="card-tools">
                              <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                 <i class="fas fa-minus"></i>
                              </button>
                              <button type="button" class="btn btn-tool" data-card-widget="remove">
                                 <i class="fas fa-times"></i>
                              </button>
                           </div>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body">
                           <table id="tabelaDocumento" class="table table-bordered table-striped" style="line-height: 0.8;">
                              <thead>
                                 <tr style="text-align: center;">
                                    <th>Ref.</th>
                                    <th>Requisição</th>
                                    <th>Proprietário</th>
                                    <th>Aprovador</th>
                                    <!-- <th>Movimento</th> -->
                                    <th>Total</th>
                                    <th>Data</th>
                                    <th>Estado</th>
                                    <th title="Opções"><i class="fa-solid fa-screwdriver-wrench"></i></th>
                                 </tr>
                              </thead>
                              <tbody id="corpoTabela" style="text-align: center;">

                              </tbody>
                           </table>
                        </div>
                        <!-- /.card-body -->
                        <div class="card-footer">
                           Listagem Requisições/Aprovações.
                        </div>
                     </div>
                  </div>
               </div>
               <!-- /.card -->
            </div>
            <!-- /.container-fluid -->
         </section>
         <div class="modal fade" id="modal-documento">
            <div class="modal-dialog modal-xl">
               <div class="modal-content">
                  <div class="modal-header">
                     <div class="container">
                        <button type="button" class="close" data-dismiss="modal" aria-label="close">
                           <small aria-hidden="true">
                              <small class="fas fa-close"></small>
                           </small>
                        </button>
                     </div>
                  </div>
                  <div class="modal-body">
                     <div class="container">
                        <div class="card-body form-outer" style="padding: 0;">
                           <div class="formulario">
                              <div class="page slidePage">
                                 <div class="row">
                                    <div class="col-12">
                                       <h5 style="margin-bottom: 1rem; justify-content: center;"><span id="doOpcao">Requisição/Aprovação</span> - <span id="codigo">RA0/1</span></h5>
                                    </div>
                                    <div class="col-md-10 mx-auto">
                                       <div class="form-group d-flex align-items-center justify-content-center" style="margin-top: .4rem;">
                                          <div class="custom-control custom-switch">
                                             <input type="checkbox" class="custom-control-input" id="current_or_another" value="0">
                                             <label class="custom-control-label" for="current_or_another" style="cursor: pointer;">Prefiro definir o Proprietário</label>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                                 <div class="row">
                                    <div class="col-md-5">
                                       <div class="row">
                                          <div class="col-12">
                                             <div class="form-group current_owner" style="margin-bottom: 0;">
                                                <small class="required">Proprietário</small>
                                                <input type="text" class="form-control" id="currentOwner" name="currentOwner" placeholder="Proprietário" title="Proprietário" required readonly>
                                                <small>Mensagem de erro</small>
                                             </div>
                                             <div class="form-group d-none another_owner" style="margin-bottom: 0;">
                                                <small class="required">Proprietário</small>
                                                <select class="form-control select2" style="width: 100%;" id="anotherOwner" name="anotherOwner">
                                                   <option value="0">Selecione o Proprietário</option>
                                                </select>
                                                <small>Mensagem de erro</small>
                                             </div>
                                          </div>

                                          <div class="col-12">
                                             <div class="form-group" style="margin-bottom: 0;">
                                                <small class="required">Aprovador</small>
                                                <select class="form-control select2" style="width: 100%;" id="idAprovador" name="idAprovador">
                                                   <option value="0">Selecione o Aprovador</option>
                                                </select>
                                                <small>Mensagem de erro</small>
                                             </div>
                                          </div>

                                          <div class="col-12">
                                             <div class="form-group" style="margin-bottom: 0;">
                                                <small class="required">Requisição</small>
                                                <input type="text" class="form-control" id="requisicao" name="nome" placeholder="Requisição" title="Código da Rúbrica" required>
                                                <small>Mensagem de erro</small>
                                             </div>
                                          </div>

                                          <div class="col-12">
                                             <div class="form-group" style="margin-bottom: 0;">
                                                <small class="required">Movimento Tesouraria</small>
                                                <select class="form-control select2" style="width: 100%;" id="idClasseMovimento" name="idClasseMovimento">
                                                   <option value="0">Selecione o Movimento para Adicionar</option>
                                                </select>
                                                <small>Mensagem de erro</small>
                                             </div>
                                          </div>

                                          <!-- <div class="col-12">
                                             <div class="form-group" style="margin-bottom: 0;">
                                                <small class="required">Total</small>
                                                <input type="text" class="form-control" id="totalRequisicaoAprovacao" name="totalRequisicaoAprovacao" placeholder="Total" title="Total" required>
                                                <small>Mensagem de erro</small>
                                             </div>
                                          </div> -->

                                          <div class="col-12"></div>

                                       </div>
                                    </div>
                                    <div class="col-md-2" style="display: flex; flex-direction: column; justify-content: center;">
                                       <div class="form-group">
                                          <button type="button" class="btn btn-block btn-primary btn-lg" id="btn-adicionar" style="margin-top: 0; display: flex; justify-content: center; align-items: center;">Adicionar<i class="fa-solid fa-circle-right" style="color: #fff; font-size: 1.5rem; margin-left: 1rem;"></i></button>
                                       </div>
                                       <div class="form-group">
                                          <button type="button" class="btn btn-block btn-primary btn-lg" id="btn-remover" style="margin-top: 0; display: flex; justify-content: center; align-items: center;">Remover<i class="fa-solid fa-circle-left" style="color: #fff; font-size: 1.5rem; margin-left: 1rem;"></i></button>
                                       </div>
                                    </div>
                                    <div class="col-md-5">
                                       <h5>Documentos</h5>
                                       <small style="visibility: hidden;">small</small>
                                       <table class="table table-sm" id="tabelaDocumentoExistente">
                                          <thead>
                                             <tr>
                                                <th style="width: 35%;">Nº do Movimento</th>
                                                <th style="width: 30%;">Data</th>
                                                <th style="width: 35%;">Total</th>
                                             </tr>
                                          </thead>
                                          <tbody id="bodyTabelaDocumentoExistente">
                                          </tbody>
                                       </table>
                                    </div>
                                 </div>

                                 <div class="row">
                                    <div class="col-12">
                                       <div class="form-group margem">
                                          <small>Mensagem de erro</small>
                                          <div class="form-group field btns">
                                             <button name="btn-submit" id="addReqAp" class="btn btn-block btn-primary" style="margin-top: 0;" disabled>
                                                Adicionar
                                             </button>
                                          </div>
                                       </div>
                                    </div>
                                 </div>
                              </div>
                           </div>
                        </div>
                     </div>
                  </div>
                  <div class="modal-footer">
                     <div class="col-md-12" style="opacity: 1;" id="footerPagamento">
                        <!-- <h4 style="display: flex; align-items: center; justify-content: space-between;"><span id="totalEntregue">ENTREGUE</span><span id="entregueSpan">0,00 Kzs</span></h4> -->
                        <h4 style="display: flex; align-items: center; justify-content: space-between;"><span class="text-danger" id="totalText">TOTAL</span><span id="totalSpan">0,00 Kzs</span></h4>
                     </div>
                  </div>
               </div>
               <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
         </div>


      </div>
      <div class="modal fade" id="modal-import">
         <div class="modal-dialog modal-default">
            <div class="modal-content">
               <div class="modal-header" style="padding: 0.5rem;">
                  <h3 class="card-title p-3">Importação Excel</h3>
               </div>
               <div class="modal-body" style="padding-bottom: 0px;">
                  <div class="row">
                     <div class="col-md-12">
                        <div class="form-group" style="margin-bottom: 0;">
                           <label for="exampleInputFile">Pesquisar Ficheiro</label>
                           <div class="input-group">
                              <div class="custom-file">
                                 <input type="file" class="custom-file-input" id="exampleInputFile">
                                 <label class="custom-file-label" for="exampleInputFile">Procurar</label>
                              </div>
                              <div class="input-group-append">
                                 <span class="input-group-text" id="btnImportExcel">Carregar</span>
                              </div>
                           </div>
                           <small>Mensagem de erro</small>
                        </div>
                     </div>
                  </div>
               </div>

            </div>
            <!-- /.modal-content -->
         </div>
         <!-- /.modal-dialog -->
      </div>
      <div class="modal fade" id="modal-detalhes">
         <div class="modal-dialog modal-xl">
            <div class="modal-content">
               <div class="modal-header">
                  <h4 class="modal-title">Detalhes da Requisição</h4>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                     <span aria-hidden="true">&times;</span>
                  </button>
               </div>
               <div class="modal-body">
                  <div class="invoice p-3 mb-3" style="height: 30rem; overflow-y: scroll;">
                     <!-- title row -->
                     <div class="row">
                        <div class="col-12">
                           <h4>
                              <span id="detalheCabecalho"></span>
                              <small class="float-right" id="detalheDataActual"></small>
                           </h4>
                        </div>
                        <!-- /.col -->
                     </div>
                     <!-- info row -->
                     <div class="row invoice-info">
                        <div class="col-sm-6 invoice-col">
                           <span>Código Requisição - <strong id="detalheCodigo"></strong></span><br>
                           <span>Requisição - </span><strong><span id="detalheDocumento"></span></strong><br>
                           <span>Estado - </span><strong><span id="detalheSerie"></span></strong><br>
                           <span>Data Criação - </span><strong><span id="detalhePrazoPagamento"></span></strong><br>
                           <span>Total - </span><strong><span id="detalheVendedor"></span></strong>
                        </div>
                        <!-- /.col -->
                        <div class="col-sm-6 invoice-col">
                           <strong><span>Entidades</span></strong><br>
                           <span>Proprietário - </span><strong><span id="detalheIdEntidade"></span></strong><br>
                           <span>Aprovador - </span><strong><span id="detalheNome"></span></strong><br>
                           <span>Criado por - </span><strong><span id="detalheMorada"></span></strong><br>
                        </div>
                     </div>
                     <!-- /.row -->

                     <!-- Table row -->
                     <div class="row" style="margin-top: 1.5rem;">
                        <div class="col-12 table-responsive">
                           <table class="table table-striped" id="" style="text-align: center;">
                              <thead>
                                 <tr>
                                    <th title="Referência da Requisição">Referência</th>
                                    <th title="Descrição">Movimento Tesoraria</th>
                                    <th title="Movimento Tesouraria">Classe Movimento</th>
                                    <th title="Aprovador">Responsável</th>
                                    <th title="Total">Total</th>
                                    <th title="Proprietário">Data Criação</th>
                                 </tr>
                              </thead>
                              <tbody id="corpoTabelaDetalhes">
                                 
                              </tbody>
                           </table>
                        </div>
                        <!-- /.col -->
                     </div>
                     <!-- /.row -->

                     <div class="row" style="display: none;">
                        <!-- accepted payments column -->
                        <div class="col-6">
                           <p class="lead">Modos de Pagamento:</p>
                           <p class="text-muted well well-sm shadow-none" style="margin-top: 10px;" id="detalheModoPagamento">
                           </p>
                        </div>
                        <!-- /.col -->
                        <div class="col-6">
                           <p class="lead">Montante</p>

                           <div class="table-responsive">
                              <table class="table" id="detalheTabelaMontante">
                              </table>
                           </div>
                        </div>
                        <!-- /.col -->
                     </div>
                  </div>
               </div>
                     <div class="row">
                        <div class="modal-footer justify-content-between">
                            <button type="button" value="" class="btn btn-default" id="cancelar_req">Cancelar</button>
                            <button type="button" value="" class="btn btn-primary" id="aprovar_req">Confirmar</button>
                        </div>
                     </div>
            </div>
            <!-- /.modal-content -->
         </div>
         <!-- /.modal-dialog -->
      </div>

      <!-- /.content-wrapper -->
      <?php include('footer.php'); ?>
</body>

<script src="../pos/javascript/function.js"></script>
<script src="template/plugins/toastr/toastr.min.js"></script>

</html>
<script>
   let definirProprietarioRubrica = -1;
   let storeMovimentoData = [];
   let addToObject = [];
   let AllUsers;
   let totalRequisicao = 0.00;




   $(document).ready(function() {

      $('#btn-adicionar').click(function(e) {
         e.preventDefault();
         var added = false;
         var tabelaAdd = $('#bodyTabelaDocumentoExistente');
         if (addToObject.length > 0) {
            $.each($('#tabelaDocumentoExistente tbody tr'), (index, tr) => {
               if (addToObject[0]["nMovimento"] == $(tr).find('td')[0].textContent) {
                  toastr.error('Este movimento já foi adicionado');
                  added = true;
                  return;
               }
            });
            var row = `
               <tr>
                  <td>${addToObject[0]['nMovimento']}</td>
                  <td>${addToObject[0]['data']}</td>
                  <td>${parseFloat(addToObject[0]["total"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
               </tr>
            `;
            if (!added) {
               totalRequisicao += parseFloat(addToObject[0]["total"]);
               totalRequisicao = totalRequisicao.toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

               $(totalSpan).text(totalRequisicao + " Kz");
               tabelaAdd.append(row);
               $('#idClasseMovimento').val(0).trigger('change');

               row = '';
               addToObject = [];
               if (checkTotalRow()) {
                  $('#addReqAp').removeAttr('disabled');
               } else {
                  $('#addReqAp').attr('disabled', true);
               }
            } else {
               $('#idClasseMovimento').focus();
            }
         } else {
            $('#idClasseMovimento').focus();
            toastr.error('Antes seleciona um Movimento');
         }
      });

      $('#bodyTabelaDocumentoExistente').on('click', 'tr', function() {
         $(this).addClass('selected');
      });

      $('#btn-remover').click(function(e) {
         e.preventDefault();
         var trSelecionado = $('#tabelaDocumentoExistente tbody tr.selected');
         var pos = parseInt(trSelecionado.find('td')[0].textContent);
         if (storeMovimentoData[pos]) {
            trSelecionado.remove();
            if (checkTotalRow()) {
               $('#addReqAp').removeAttr('disabled');
            } else {
               $('#addReqAp').attr('disabled', true);
            }
         }
      });

   });

   $('#tabelaDocumento').on('click', '.btn-more', function(e) {
      e.preventDefault();
      var id = $(this).closest('tr').find('td')[0].innerText;
      $("#cancelar_req").val(id);
      $("#aprovar_req").val(id);
      funcaoQuerySelect("../pos/includes/querySelect.inc.php", "post", "json", {
         idRequisicao: id
       }, "viewlinharequiscao", function success(data) {
           console.log(data)

           var tabelalinha = ''
           var tipomov = ''
           var precoreq = 0

            detalheCodigo.innerText = "REQ-"+data[0]["idRequisicao"]
            detalheDocumento.innerText = data[0]["requisicao"]
            detalheSerie.innerText = data[0]["estado"]
            detalhePrazoPagamento.innerText = data[0]["createdAt"]
            detalheIdEntidade.innerText = data[0]["proprietario"]
            detalheNome.innerText = data[0]["aprovador"]
            detalheMorada.innerText = data[0]["responsavelreq"]

            if (data[0]["idEstado"] != 1) {
               $("#cancelar_req").css('display','none');
               $("#aprovar_req").css('display','none');
            }

         for (var key in data) {
            if (data[key]["tipomovimento"] == 1) {
               tipomov = 'Crédito'
            }else{
               tipomov = 'Débito' 
            }
                  precoreq = Number(precoreq) + Number(data[key]["preco"]);
                  tabelalinha = `<tr>
                                    <td>${data[key]["idMovimentoTesoraria"]}</td>
                                    <td>${data[key]["movimento"]}</td>
                                    <td>${tipomov}</td>
                                    <td>${data[key]["linharesponsavel"]}</td>
                                    <td>${parseFloat(data[key]["preco"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
                                    <td>${data[key]["criacaolinha"]}</td>
                                 </tr>`
           
         }
            detalheVendedor.innerText = parseFloat(precoreq).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
         $('#corpoTabelaDetalhes').html(tabelalinha);

       }, function error(data) {

       }, function done(data) {
         $('#modal-detalhes').modal('show');

    });
   });

   function checkTotalRow() {
      var tr = $('#tabelaDocumentoExistente tbody tr');

      return tr.length > 0;
   }


   $(document).ready(function() {

      $('#btn').click(function(e) {
         e.preventDefault();
         funcaoSelect("../pos/includes/select.inc.php", "post", "json", "usuario", function success(users) {
            AllUsers = users;
            $('#idAprovador').select2({
               placeholder: 'Selecione um aprovador',
               data: AllUsers.map(function(owner) {
                  return {
                     id: owner.idUsuario,
                     text: owner.nome
                  };
               })
            });
            var activeUserId = <?php echo $_SESSION["usuarioId"]; ?>;
            users.forEach(user => {
               if (user.idUsuario == activeUserId) {
                  currentOwner.value = user.nome;
                  currentOwner.setAttribute('data-target', 'user-' + user.idUsuario);
               }
            });

         }, (error) => {}, (done) => {
            funcaoSelect("../pos/includes/select.inc.php", "post", "json", "movimentotesoraria", function success(movimentsData) {

               console.log('MOVIMENTOS ALL: ', movimentsData);

               $('#idClasseMovimento').select2({
                  data: movimentsData.map(function(mov) {
                     storeMovimentoData[mov.idMovimentoTesoraria] = {
                        nMovimento: mov.idMovimentoTesoraria,
                        data: mov.createdAt,
                        total: mov.preco
                     };
                     return {
                        id: mov.idMovimentoTesoraria,
                        text: mov.movimento
                     }
                  })
               });
            }, (err) => {}, (done) => {});
         });
         // alert('Not Available at the Moment');
         $('#modal-documento').modal('show');
      });


      $('#idClasseMovimento').change(function(e) {
         addToObject.push(storeMovimentoData[$(this).val()]);


         console.log("TTTT: ", addToObject);

      });


      $('#current_or_another').change(function(e) {
         if (e.target.checked) {
            $('#anotherOwner').select2({
               placeholder: 'Selecione um proprietário',
               data: AllUsers.map(function(owner) {
                  return {
                     id: owner.idUsuario,
                     text: owner.nome
                  };
               })
            });
            $('.current_owner').addClass('d-none');
            $('.another_owner').removeClass('d-none');

            definirProprietarioRubrica = 1;
         } else {
            $('.current_owner').removeClass('d-none');
            $('.another_owner').addClass('d-none');
         }

      });

   });


   let buildData = [];
   funcaoSelect("../pos/includes/select.inc.php", "post", "json", "viewrequisicao", function success(requestData) {
      $("#tabelaDocumento").DataTable({
         select: 'single',
         "aaData": requestData,
         "columns": [{
            data: "idRequisicao"
         }, {
            data: "requisicao"
         }, {
            data: "proprietario"
         }, {
            data: "aprovador"
         }, {
            data: "total"
         }, {
            data: "createdAt"
         }, {
            data: "estado"
         }, {
            data: null,
            render: function(data, type, row) {
               return `
                        <div id="dropdownOpcoes" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" style="display:flex; align-items: center; justify-content: space-around;"><button class="btn btn-outline-primary opcoes" style="padding: .2rem .7rem; line-height: 1; border: none;"><i class="fa-solid fa-ellipsis-vertical"></i></button></div>
                        <ul aria-labelledby="dropdownOpcoes" class="dropdown-menu border-0 shadow">
                          <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item btn-more" style="padding: .8rem; border-radius: 5px;">Informações</a></li>
                          <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item btn-update" style="padding: .8rem; border-radius: 5px;">Editar</a></li>
                          <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item btn-delete" style="padding: .8rem; border-radius: 5px;">Eliminar</a></li>
                        </ul>`;
            }
         }],
         columnDefs: [{
            targets: -1,
            orderable: false
         }],
         "responsive": true,
         "lengthChange": false,
         "autoWidth": false,
         "language": idiomaPortugues,
         lengthMenu: [
            [7, 25, 50, -1],
            [10, 25, 50, 'All']
         ],
         "buttons": ["copy", "csv", "excel", "pdf", "print", "colvis"]
      }).buttons().container().appendTo('#tabelaDocumento .col-md-6:eq(0)');
   }, function error(data) {
      erro(data);
   }, function done(data) {});

   let currentObjectDatacancel = {
                    idEstado: 4
            }
   let currentObjectDataaprov = {
                    idEstado: 3
            }

   $('#cancelar_req').click(function(){
      funcaoUpdate("../pos/includes/update.inc.php", "post", "json", "requisicao", currentObjectDatacancel, {
                    idRequisicao: $("#cancelar_req").val()
                  }, function success(data) {
                    swal.fire({
                      title: "Aprovado!",
                      text: "Requisição Aprovada com Sucesso",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: '#560085',
                      icon: "success",
                    });
                    setTimeout(()=>{
                           window.location.href ="formRequisicaoAprovacao.php"
                     }, 5000)
                  }, function error(data) {
                    console.log("Erro: ", data);
                    swal.fire({
                      title: "Erro ao actualizar!",
                      text: "Erro ao actualizar Dados Submetidos!",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: '#560085',
                      icon: "error",
                    });
                  }, function done(data) {

                });
   });

   $('#aprovar_req').click(function(){
     funcaoUpdate("../pos/includes/update.inc.php", "post", "json", "requisicao", currentObjectDataaprov, {
                    idRequisicao: $("#cancelar_req").val()
                  }, function success(data) {
                    swal.fire({
                      title: "Aprovado!",
                      text: "Requisição Aprovada com Sucesso",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: '#560085',
                      icon: "success",
                    });
                    setTimeout(()=>{
                           window.location.href ="formRequisicaoAprovacao.php"
                     }, 5000)
                  }, function error(data) {

                    console.log("Erro: ", data);
                    swal.fire({
                      title: "Erro ao actualizar!",
                      text: "Erro ao actualizar Dados Submetidos!",
                      confirmButtonText: 'Confirmar',
                      confirmButtonColor: '#560085',
                      icon: "error",
                    });
                  }, function done(data) {

                });
   });


   $(addReqAp).click(function(e) {

      $('#tabelaDocumentoExistente tbody tr')
      e.preventDefault();

      if (requisicao.value.length == 0) {
         $(requisicao).next().text('Campo obrigatório');
         return;
      }


      let currentObjectData = {
         idUsuario: <?php echo $_SESSION["usuarioId"]; ?>,
         requisicao: requisicao.value,
         // idClassMovimento: parseInt(idClasseMovimento.value), // Campo Indefinido na Tabela Requisicao
         idProprietario: definirProprietarioRubrica != 1 ? parseInt(currentOwner.getAttribute('data-target').split('-')[1]) : parseInt(anotherOwner.value),
         idAprovador: parseInt(idAprovador.value),
         total: totalRequisicao.replace(" ", "").replace(",", "."), //parseFloat(totalRequisicaoAprovacao.value ?? 0.00),
         idEstado: 1 // Por defeito vai Pendente
      }

      funcaoInsert("../pos/includes/insert.inc.php", "post", "json", 'requisicao', currentObjectData, function success(data) {
         console.log("RETORNOS1: ", data);
      }, function error(data) {
         console.log(data)
         swal.fire({
            title: "Erro ao cadastrar!",
            text: "Erro ao cadastrar coordenadas! ", //+ nome.value + " !",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "error",
         });
      }, function done(data) {
         let countSucesso = -1;

         storeMovimentoData.forEach(movimento => {
            funcaoInsert("../pos/includes/insert.inc.php", "post", "json", "linharequisicao", {
               idRequisicao: data,
               idMovimentoTesoraria: movimento.nMovimento
            }, function success(data) {}, (err) => {
               console.log("ERRRRRRRRRRRRRRR: ", err);
               swal.fire({
                  title: "Erro ao cadastrar!",
                  text: "Erro ao cadastrar a requisicao! ", //+ nome.value + " !",
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: '#560085',
                  icon: "error",
               });
               return;
            }, (data) => {});
         });

         swal.fire({
            title: "Cadatrado",
            text: "Os dados Submetidos foram cadastrados com sucesso!",
            icon: "success",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
         }).then((result) => {
            if (result.isConfirmed) {
               definirProprietarioRubrica = -1;
               reloadFrame("formRequisicaoAprovacao.php");
               // window.location.href = "formRequisicaoAprovacao.php";
            }
         });
      });
   });


   function detalhes(id) {

      // TODO: 

      
   }
</script>
<script src="./validation/parametroArtigo.js"></script>
