<?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: #4a0073;
    border-color: #4a0073;
  }

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

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

  .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: 600;
    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: 600;
    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: -14.5rem;
    height: 3px;
    width: 14rem;
    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;
  }

  .tooltip-container {
    position: relative;
    float: right;
    margin-left: 10px;
  }

  .tooltip-content {
    margin-left: 1rem;
    margin-top: 2.5rem;
    display: none;
    position: fixed;
    padding: 10px;
    z-index: 9999;
  }


  .tooltip-content label {
    display: block;
    margin-bottom: 5px;
  }

  .tooltip-content input {
    width: 100%;
    box-sizing: border-box;
    margin-bottom: 10px;
  }

  .tooltip-show {
    display: block;
  }
</style>

<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">
                      <li class="nav-item dropdown btn">
                        <a id="btn-preview" href="#" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Pré-visualizar</a>
                        <ul aria-labelledby="btn-preview" class="dropdown-menu border-0 shadow">
                          <li><button id="./formLayoutA4.php" class="dropdown-item btn-layout" disabled>Documento A4</button></li>
                          <li><button id="./formLayoutTicket.php" class="dropdown-item btn-layout" disabled>Documento Ticket</button></li>
                        </ul>
                      </li>
                      <button class="btn btn-opcao">Importar</button>
                      <button class="btn btn-opcao botao-activo" id="btn">Nova Factura Recibo</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">Documentos</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-hover table-bordered table-striped">
                    <thead>
                      <tr style="text-align: center;">
                        <th title="Código do Documento">Documento</th>
                        <th title="Valor Entregue">Valor Entregue</th>
                        <th title="Troco">Troco</th>
                        <th title="Data Documento">Data Documento</th>
                        <th title="Usuário-Vendedor">Vendedor</th>
                        <th title="Total do Documento">Total</th>
                        <th title="Nome do Entidade">Entidade</th>
                        <th title="Estado do Documento">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 Facturas-Recibo.
                </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">
                <div class="progress-barra">
                  <div class="step">
                    <p style="margin: 0;">Geral</p>
                    <div class="bullet">
                      <span style="color: #666;">1</span>
                      <div class="check fas fa-check"></div>
                    </div>
                  </div>
                  <div class="step">
                    <p style="margin: 0;">Artigos</p>
                    <div class="bullet">
                      <span style="color: #666;">2</span>
                      <div class="check fas fa-check"></div>
                    </div>
                  </div>
                  <div class="step">
                    <p style="margin: 0;">Confirmação</p>
                    <div class="bullet">
                      <span style="color: #666;">3</span>
                      <div class="check fas fa-check"></div>
                    </div>
                  </div>
                  <div class="step">
                    <p style="margin: 0;">Pagamento</p>
                    <div class="bullet">
                      <span style="color: #666;">4</span>
                      <div class="check fas fa-check"></div>
                    </div>
                  </div>
                </div>
              </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" style="position: relative;">
                      <div class="row">
                        <div class="col-md-6">
                          <h5 style="margin-bottom: 1rem; justify-content: center;">Documento - <span id="codigo"></span></h5>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Tipo de Documento</small>
                            <select class="form-control select2" style="width: 100%;" id="tipoDocumento" name="tipoDocumento">
                            </select>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="not-required">Série</small>
                            <input type="text" class="form-control" id="serie" name="serie" placeholder="Série" title="Série" disabled>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Prazo de Pagamento</small>
                            <select class="form-control select2" style="width: 100%;" id="prazoPagamento" name="prazoPagamento">
                            </select>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="not-required">Vendedor</small>
                            <input type="text" class="form-control" id="vendedorFactura" name="vendedorFactura" placeholder="Vendedor" title="Vendedor" disabled>
                          </div>
                        </div>
                        <div class="col-md-6">
                          <h5 style="margin-bottom: 1rem; justify-content: center;">Entidade</h5>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Entidade</small>
                            <div class="input-group input-group">
                              <input type="text" class="form-control" id="entidade" name="entidade" placeholder="Pesquisar Entidade" title="Pesquisar Entidade">
                              <div class="input-group-append">
                                <button type="button" id="btn-search-entidade" class="btn btn btn-default" style="line-height: 0 ;">
                                  <i class="fa fa-search"></i>
                                </button>
                              </div>
                            </div>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="required">Nome</small>
                            <input type="text" class="form-control" id="nomeEntidade" name="nomeEntidade" placeholder="Nome" title="Nome do Entidade" disabled>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="not-required">Morada</small>
                            <input type="text" class="form-control" id="moradaEntidade" name="moradaEntidade" placeholder="Morada do Entidade" title="Morada do Entidade" disabled>
                            <small>Mensagem de erro</small>
                          </div>
                          <div class="form-group" style="margin-bottom: 0;">
                            <small class="not-required">NIF do Entidade</small>
                            <input type="text" class="form-control" id="nifEntidade" name="nifEntidade" placeholder="NIF do Entidade" title="NIF (Número de Identificação Fiscal) do Entidade" disabled>
                          </div>
                        </div>
                        <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; bottom: 0; position: absolute;">
                          <div class="form-group margem">
                            <small>Mensagem de erro</small>
                            <div class="form-group field btns">
                              <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary nextBtn nextButton" style="margin-top: 0;">
                                Seguinte
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="page" style="position: relative;">

                      <div class="row">
                        <div class="col-md-12">
                          <h6>
                            <div class="tooltip-container">
                              <button class="float-right" id="outrasOpcoes" style="border: none; color: #560085; background: #5600851c;padding: .5rem;border-radius: 10px;font-weight: 600;margin-top: 0.5rem;text-align: center; cursor: pointer;padding: .375rem .75rem;font-size: .8rem;line-height: 1.5;border-radius: .5rem">Outras Opções</button>
                              <div class="col-12 col-sm-6 tooltip-content">
                                <div class="card card-primary card-outline card-outline-tabs" style="width: 45%;">
                                  <div class="card-header p-0 border-bottom-0">
                                    <ul class="nav nav-tabs" id="custom-tabs-four-tab" role="tablist">
                                      <li class="nav-item">
                                        <a class="nav-link active" id="custom-tabs-four-total-tab" data-toggle="pill" href="#custom-tabs-four-total" role="tab" aria-controls="custom-tabs-four-total" aria-selected="true">Totais</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" id="custom-tabs-four-imposto-tab" data-toggle="pill" href="#custom-tabs-four-imposto" role="tab" aria-controls="custom-tabs-four-imposto" aria-selected="false">Impostos</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" id="custom-tabs-four-saldo-tab" data-toggle="pill" href="#custom-tabs-four-saldo" role="tab" aria-controls="custom-tabs-four-saldo" aria-selected="false">Saldo</a>
                                      </li>
                                      <li class="nav-item">
                                        <a class="nav-link" id="custom-tabs-four-observacao-tab" data-toggle="pill" href="#custom-tabs-four-observacao" role="tab" aria-controls="custom-tabs-four-observacao" aria-selected="false">Observações</a>
                                      </li>
                                    </ul>
                                  </div>
                                  <div class="card-body">
                                    <div class="tab-content" id="custom-tabs-four-tabContent">
                                      <div class="tab-pane fade show active" id="custom-tabs-four-total" role="tabpanel" aria-labelledby="custom-tabs-four-total-tab">
                                        <div class="row">
                                          <div class="col-md-6">
                                            <p>Total Bruto</p>
                                            <p>Desconto de Linha</p>
                                          </div>
                                          <div class="col-md-6">
                                            <p style="text-align: right;" id="opcaoTotalBruto">0,00</p>
                                            <p style="text-align: right;" id="opcaoDescontoLinha">0,00</p>
                                          </div>
                                          <div class="col-md-6">
                                            <div class="form-group" style="margin-bottom: 0;">
                                              <small class="not-required">Desconto Global %</small>
                                              <input type="text" class="form-control" id="descontoGlobalPorcentagem" placeholder="0,00%" title="Desconto Global Porcentagem">
                                            </div>
                                          </div>
                                          <div class="col-md-6">
                                            <div class="form-group" style="margin-bottom: 0;">
                                              <small class="not-required">Desconto Global</small>
                                              <input type="text" class="form-control" id="descontoGlobalValor" name="descontoGlobalValor" placeholder="0,00" title="Desconto Global Por Valor">
                                            </div>
                                          </div>
                                          <div class="col-md-6">
                                            <p>Total Líquido</p>
                                            <p>Total Impostos</p>
                                            <p>Total Documento</p>
                                            <p>Total Retenção</p>
                                          </div>
                                          <div class="col-md-6">
                                            <p style="text-align: right;" id="opcaoTotalLiquido">0,00</p>
                                            <p style="text-align: right;" id="opcaoTotalImposto" id="opcaoTotalImposto">0,00</p>
                                            <p style="text-align: right;" id="opcaoTotalDocumento">0,00</p>
                                            <p style="text-align: right;">0,00</p>
                                          </div>
                                          <div class="col-md-12">
                                            <div class="form-group" style="margin-bottom: 0;">
                                              <small class="not-required">Arredondamento</small>
                                              <input type="text" class="form-control" id="arredondamento" placeholder="0,00" title="Arredondamento">
                                            </div>
                                          </div>
                                          <div class="col-md-6">
                                            <p>Valor a Pagar</p>
                                          </div>
                                          <div class="col-md-6">
                                            <p style="text-align: right;" id="opcaoValorPagar">0,00</p>
                                          </div>
                                        </div>
                                      </div>
                                      <div class="tab-pane fade" id="custom-tabs-four-imposto" role="tabpanel" aria-labelledby="custom-tabs-four-imposto-tab">
                                        <div class="row">
                                          <div class="col-md-12">
                                            <table class="table table-sm" style="text-align: center;">
                                              <thead>
                                                <tr>
                                                  <th title="Taxa %"><small>Taxa %</small></th>
                                                  <th title="Incidência"><small>Incidência</small></th>
                                                  <th title="Impostos"><small>Impostos</small></th>
                                                  <th title="Valor"><small>Valor</small></th>
                                                </tr>
                                              </thead>
                                              <tbody id="impostoOpcao">
                                              </tbody>
                                            </table>
                                          </div>
                                        </div>
                                      </div>
                                      <div class="tab-pane fade" id="custom-tabs-four-saldo" role="tabpanel" aria-labelledby="custom-tabs-four-saldo-tab">
                                        <div class="row">
                                          <div class="col-md-12">
                                            <table class="table table-sm">
                                              <thead>
                                                <tr>
                                                  <th title="Total"><small>Total</small></th>
                                                  <th title="Não Vencido"><small>N.Vencido</small></th>
                                                  <th title="Até 30 Dias"><small>30 Dias</small></th>
                                                  <th title="De 31 até 60 Dias"><small>31-60 Dias</small></th>
                                                  <th title="De 61 até 90 Dias"><small>61-90 Dias</small></th>
                                                  <th title="Mais de 90 Dias"><small>+90 Dias</small></th>
                                                </tr>
                                              </thead>
                                              <tbody>
                                              </tbody>
                                            </table>
                                          </div>
                                        </div>
                                      </div>
                                      <div class="tab-pane fade" id="custom-tabs-four-observacao" role="tabpanel" aria-labelledby="custom-tabs-four-observacao-tab">
                                        <div class="row">
                                          <div class="col-md-12">
                                            <div class="form-group" style="margin-bottom: 0;">
                                              <small class="not-required">Observações</small>
                                              <textarea class="form-control" name="" id="" cols="30" rows="10"></textarea>
                                            </div>
                                          </div>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                  <!-- /.card -->
                                </div>
                              </div>
                            </div>

                          </h6>
                          <table id="tabelaArtigo" class="table table-hover table-bordered table-striped">
                            <thead style="border-bottom-left-radius: 0;">
                              <tr style="text-align: center;">
                                <th title="Referência do Artigo">Referência</th>
                                <th title="Descrição">Descrição</th>
                                <th title="Quantidade">Qtd.</th>
                                <th title="Preço do Artigo">Preço</th>
                                <th title="Desconto">Desc.</th>
                                <th title="Imposto">Imposto</th>
                                <th title="Total">Total</th>
                                <th title="Opções"><i class="fa-solid fa-screwdriver-wrench"></i></th>
                              </tr>
                            </thead>
                            <tbody style="text-align: center;">
                            </tbody>
                          </table>
                        </div>
                        <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; bottom: 0; position: absolute;">
                          <div class="form-group field btns">
                            <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary prev-1 prev prevButton" style="margin-top: 0;">
                              Anterior
                            </button>
                            <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary next-1 next nextButton" style="margin-top: 0;">
                              Seguinte
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div class="page" style="position: relative;">
                      <h5 style="margin-bottom: 1rem; justify-content: center;">Confirmação</h5>
                      <div class="row">
                            <div class="col-12">
                              <div class="invoice p-3 mb-3" style="height: 18rem; overflow-y: scroll;">
                                <!-- title row -->
                                <div class="row">
                                  <div class="col-12">
                                    <h4>
                                      <span id="descCabecalho"></span>
                                      <small class="float-right" id="descDataActual"></small>
                                    </h4>
                                  </div>
                                  <!-- /.col -->
                                </div>
                                <!-- info row -->
                                <div class="row invoice-info">
                                  <div class="col-sm-6 invoice-col">
                                    <strong>Código Documento - <span id="descCodigo"></span></strong><br>
                                    <span>Documento - </span><strong><span id="descDocumento"></span></strong><br>
                                    <span>Série - </span><strong><span id="descSerie"></span></strong><br>
                                    <span>Prazo de Pagamento - </span><strong><span id="descPrazoPagamento"></span></strong><br>
                                    <span>Vendedor - </span><strong><span id="descVendedor"></span></strong>
                                  </div>
                                  <!-- /.col -->
                                  <div class="col-sm-6 invoice-col">
                                    <strong><span>Entidade</span></strong><br>
                                    <span>Identificador Entidade - </span><strong><span id="descIdEntidade"></span></strong><br>
                                    <span>Nome - </span><strong><span id="descNome"></span></strong><br>
                                    <span>Morada - </span><strong><span id="descMorada"></span></strong><br>
                                    <span>NIF - </span><strong><span id="descNif"></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-hover table-striped" style="text-align: center;" id="tabelaConfirmacao">
                                      <thead>
                                        <tr>
                                          <th title="Referência do Artigo">Referência</th>
                                          <th title="Descrição">Descrição</th>
                                          <th title="Quantidade">Qtd.</th>
                                          <th title="Preço do Artigo">Preço</th>
                                          <th title="Desconto">Desc.</th>
                                          <th title="Imposto">Imposto</th>
                                          <th title="Total">Total</th>
                                        </tr>
                                      </thead>
                                      <tbody id="tabelaConfirmacaoBody">
                                      </tbody>
                                    </table>
                                  </div>
                                  <!-- /.col -->
                                </div>
                              </div>
                              <!-- /.invoice -->
                            </div><!-- /.col -->
                            <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; bottom: 0; position: absolute;">
                              <div class="form-group field btns">
                                <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary prev-2 prev prevButton" style="margin-top: 0;">
                                  Anterior
                                </button>
                                <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary next-2 next nextButton" style="margin-top: 0; margin-left: 3px !important;">
                                  Seguinte
                                </button>
                              </div>
                            </div>
                          </div>
                    </div>
                    <div class="page" style="position: relative;">
                      <h5 style="margin-bottom: 1rem; justify-content: center;">Pagamento</h5>
                      <div class="row" style="margin-top: 1.5rem;">
                        <div class="col-md-12" style="margin-bottom: 2rem;">
                          <div class="card-body table-responsive p-0" style="height: 19rem; border: 0;">
                            <table class="table table-hover text-wrap" id="tabelaModoPagamento">
                              <tbody id="modoPagamentoBody">
                              </tbody>
                            </table>
                          </div>
                        </div>
                      </div>
                      <div class="col-md-12" style="padding: 14px 7.5px 0 7.5px; bottom: 0; position: absolute;">
                        <div class="form-group field btns">
                          <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary prev-3 prev prevButton" style="margin-top: 0;">
                            Anterior
                          </button>
                          <button name="btn-submit" id="btn-submit" class="btn btn-block btn-primary submit nextButton" style="margin-top: 0; margin-left: 3px !important;">
                            Gravar Documento
                          </button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="col-md-12" style="opacity: 0;" 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 class="modal fade" id="modal-entidade">
        <div class="modal-dialog modal-xl">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">Entidades</h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <table id="tabelaEntidade" class="table table-hover table-bordered table-striped">
                <thead>
                  <tr style="text-align: center;">
                    <th title="Identificador da Entidade">Id. Entidade</th>
                    <th title="Nome">Nome</th>
                    <th title="Nome Comercial">Nome Comercial</th>
                    <th title="Bilhete de Identidade do Entidade">B.I</th>
                    <th title="NIF do Entidade">NIF</th>
                    <th title="Localidade do Entidade">Localidade</th>
                    <th title="Data de Nascimento do Entidade">Data Nasc.</th>
                    <th title="Morada do Entidade">Morada</th>
                    <th title="Tipo">Tipo</th>
                    <th title="Estado do Entidade">Estado</th>
                  </tr>
                </thead>
                <tbody style="text-align: center;">
                </tbody>
              </table>
            </div>
            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
              <button type="button" class="btn btn-primary">Confirmar</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
      <div class="modal fade" id="modal-artigo">
        <div class="modal-dialog modal-xl">
          <div class="modal-content">
            <div class="modal-header">
              <h4 class="modal-title">Artigos</h4>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <table id="tabelaArtigoListagem" class="table table-hover table-bordered table-striped">
                <thead>
                  <tr style="text-align: center;">
                    <th title="Referência">Referência</th>
                    <th title="Descrição do Artigo">Descrição</th>
                    <th title="Família">Família</th>
                    <th title="Preço do Artigo (S/Imp)">Preço (S/Imp)</th>
                    <th title="Preço do Artigo (C/Imp)">Preço (C/Imp)</th>
                    <th title="Qtd. Stock">Qtd. Stock</th>
                  </tr>
                </thead>
                <tbody style="text-align: center;">
                </tbody>
              </table>
            </div>
            <div class="modal-footer justify-content-between">
              <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
              <button type="button" class="btn btn-primary">Confirmar</button>
            </div>
          </div>
          <!-- /.modal-content -->
        </div>
        <!-- /.modal-dialog -->
      </div>
    </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 do Documento</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">
                  <strong>Código Documento - <span id="detalheCodigo"></span></strong><br>
                  <span>Documento - </span><strong><span id="detalheDocumento"></span></strong><br>
                  <span>Série - </span><strong><span id="detalheSerie"></span></strong><br>
                  <span>Prazo de Pagamento - </span><strong><span id="detalhePrazoPagamento"></span></strong><br>
                  <span>Vendedor - </span><strong><span id="detalheVendedor"></span></strong>
                </div>
                <!-- /.col -->
                <div class="col-sm-6 invoice-col">
                  <strong><span>Entidade</span></strong><br>
                  <span>Identificador Entidade - </span><strong><span id="detalheIdEntidade"></span></strong><br>
                  <span>Nome - </span><strong><span id="detalheNome"></span></strong><br>
                  <span>Morada - </span><strong><span id="detalheMorada"></span></strong><br>
                  <span>NIF - </span><strong><span id="detalheNif"></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" style="text-align: center;">
                    <thead>
                      <tr>
                        <th title="Referência do Artigo">Referência</th>
                        <th title="Descrição">Descrição</th>
                        <th title="Quantidade">Qtd.</th>
                        <th title="Preço do Artigo">Preço</th>
                        <th title="Desconto">Desc.</th>
                        <th title="Imposto">Imposto</th>
                        <th title="Total">Total</th>
                      </tr>
                    </thead>
                    <tbody id="corpoTabelaDetalhes">
                    </tbody>
                  </table>
                </div>
                <!-- /.col -->
              </div>
              <!-- /.row -->

              <div class="row">
                <!-- 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>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <div class="modal fade" id="modal-layout">
      <div class="modal-dialog modal-xl">
        <div class="modal-content">
          <div class="modal-header">
            <h4 class="modal-title">Documento</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="row">
              <div class="col-md-12">
                <iframe id="layoutDocumento" frameborder="0" width="100%" style="height: 60vh;"></iframe>
              </div>
            </div>
          </div>
          <div class="modal-footer justify-content-between">
            <button type="button" class="btn btn-default" data-dismiss="modal">Fechar</button>
            <button type="button" class="btn btn-primary" id="btn-print">Imprimir</button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.content-wrapper -->
    <?php include('footer.php'); ?>
</body>

</html>
<script src="./validation/formFacturaRecibo.js"></script>
<script>
  let idEntidade;
  let valorLinha;
  let totalDoc;
  let pendenteVerify;
  let totalImposto = [];
  let linhaPrecoEntidade;
  let codigoReport;
  let nomeReport;
  let tipoDoc;
  let tipoEntidade;
  let idDoc;

  let btnOpcao = document.querySelectorAll(".btn-opcao");
  botaoOutrasOpcoes(btnOpcao);

  function loadTabelaDocumento(tipoDocumento) {
    let id = {
      idTipoDoc: tipoDocumento
    }

    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", id, "viewartigomodopagamentodocumento", function success(data) {
      $("#tabelaDocumento").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "codigoDocumento"
        }, {
          data: "entregue",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "troco",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "dataDoc"
        }, {
          data: "nomeU"
        }, {
          data: "total",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "nomeE"
        }, {
          data: null,
          render: function(data, type, row) {
            if (data["entregue"] >= data["total"]) {
              return "<small class='badge badge-success'>Pago</small>";
            } else {
              if (data["entregue"] == 0) {
                return "<small class='badge badge-danger'>Por Pagar</small>";
              } else {
                return "<small class='badge badge-warning'>Pago Parcialmente</small>";
              }
            }
          }
        }, {
          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-cancel" style="padding: .8rem; border-radius: 5px;">Anular</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item" style="padding: .8rem; border-radius: 5px;">Duplicar</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item" style="padding: .8rem; border-radius: 5px;">Anular e Duplicar</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"],
        order: [
          [3, 'asc']
        ]
      }).buttons().container().appendTo('#tabelaDocumento_wrapper .col-md-6:eq(0)');
    }, function error(data) {

    }, function done(data) {

    });
  }

  function loadEntidade(tipoEntidade) {
    let id = {
      idTipoEntidade: tipoEntidade
    }
    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", id, "viewEntidade", function success(data) {}, function error(data) {

    }, function done(data) {
      $("#tabelaEntidade").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "idEntidade"
        }, {
          data: "nome"
        }, {
          data: "nomeComercial"
        }, {
          data: "bi",
          visible: false
        }, {
          data: "nif",
          visible: false,
        }, {
          data: "localidade",
          visible: false
        }, {
          data: "dataNasc",
          visible: false
        }, {
          data: "morada",
          visible: false
        }, {
          data: "tipoEntidadeNome"
        }, {
          data: "estado",
          visible: false,
          render: function(data) {
            if (data == 0) {
              return "<small class='badge badge-success'>Activo</small>";
            } else if (data == 1) {
              return "<small class='badge badge-danger'>Inactivo</small>";
            }
          }
        }],
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "language": idiomaPortugues,
        lengthMenu: [
          [7, 25, 50, -1],
          [10, 25, 50, 'All']
        ]
      }).buttons().container().appendTo('#tabelaEntidade_wrapper .col-md-6:eq(0)');
    });
  }

  /*
  OFICIAL
  function createDocumento() {
    Swal.fire({
      icon: 'info',
      title: 'Emitir Documento?',
      text: 'Tem a certeza que quer emitir essa Documento?',
      allowOutsideClick: false,
      showCancelButton: true,
      confirmButtonText: 'Confirmar',
      confirmButtonColor: '#560085',
      cancelButtonText: 'Cancelar',
      cancelButtonColor: '#560085',
    }).then((result) => {
      if (result.isConfirmed) {
        let idUsuario = <?php echo $_SESSION["usuarioId"]; ?>;
        let tipoDocumento = tipoDocumento.value;
        let entidade = entidade.value;
        let prazoPagamento = prazoPagamento.value;
        let entregueSpan = parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let totalDocumento = totalDoc;
        let totalSpan = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let opcaoTotalLiquido = parseFloat(opcaoTotalLiquido.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let opcaoTotalImposto = parseFloat(opcaoTotalImposto.innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let descontoGlobalValor = parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.'));

        createDoc(idUsuario, tipoDocumento, entidade, prazoPagamento, entregueSpan, totalDocumento, totalSpan, opcaoTotalLiquido, opcaoTotalImposto, descontoGlovalValor, function success(data) {
          let tabela = document.getElementById("tabelaArtigo");
          for (i = 1; i < tabela.rows.length; i++) {
            let inputSearchArtigo = tabela.rows[i].querySelector('.inputSearchArtigo').value;
            let qtd = tabela.rows[i].querySelector('.qtd').value;
            let preco = tabela.rows[i].querySelector('.preco').value;
            let desconto = tabela.rows[i].querySelector('.desconto').value;
            let imposto = tabela.rows[i].querySelector('.imposto').value;
            let total = tabela.rows[i].querySelector('.total').value;
            let taxa = $(tabela.rows[i].querySelector('.imposto')).select2('data')[0].element.dataset.taxa;

            if (inputSearchArtigo != "" && qtd != "" && preco != "" && desconto != "" && imposto != "" && total != "") {
              createArtigoDocumento(data, parseInt(inputSearchArtigo), tabela.rows[i].querySelector('.descricao').value, parseInt(qtd), parseFloat(preco.replace(/\ /g, '').replace(/\,/g, '.')), parseFloat(desconto.replace(/\ /g, '').replace(/\,/g, '.')), parseFloat(imposto.replace(/\ /g, '').replace(/\,/g, '.')), parseFloat($(tabela.rows[i].querySelector('.imposto')).select2('data')[0].element.dataset.taxa.replace(/\ /g, '').replace(/\,/g, '.')), parseFloat(total.replace(/\ /g, '').replace(/\,/g, '.')));
            }
          }

          let table = document.getElementById("tabelaModoPagamento");
          for (i = 0; i < table.rows.length; i++) {
            if (table.rows[i].querySelector('.mp').value != "") {
              createModoPagamento(parseInt(table.rows[i].cells[0].innerText), data, parseFloat(table.rows[i].querySelector('.mp').value.replace(/\ /g, '').replace(/\,/g, '.')), function success(data) {

                },
                function error(data) {

                },
                function done(data) {

                });
            }
          }
        }, function error(data) {
          swal.fire({
            title: "Erro ao Emitir Documento!",
            text: "Erro ao Emitir Factura-Recibo!",
            confirmButtonText: 'Confirmar',
            confirmButtonColor: '#560085',
            icon: "error",
          });
        }, function done(data) {
          insertLinhaDocumento(data, function success(data) {
            for (let i = 0; i < data.length; i++) {
              var novaLinha = {
                codigoDocumento: data[i]["codigoDocumento"],
                entregue: data[i]["entregue"],
                troco: data[i]["troco"],
                dataDoc: data[i]["dataDoc"],
                nomeU: data[i]["nomeU"],
                total: data[i]["total"],
                nomeE: data[i]["nomeE"],
              };
              $('#tabelaDocumento').DataTable().row.add(novaLinha).draw(false);
            }
          }, function error(data) {

          }, function done(data) {

          });
        });
      } else {
        reload();
        loadNovoId();
        totalDocumento();
      }
    });
  }*/

  function createLayout(idDocumento, nomeDocumento, tipoLayout) {
    $.ajax({
      url: "includes/create/layout.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idDocumento: idDocumento,
        nomeDocumento: nomeDocumento,
        tipoLayout: tipoLayout
      }
    });
  }

  function reload() {
    swal.fire({
      title: "Cadastro efectuado com sucesso!",
      text: "Documento cadastro",
      confirmButtonText: 'Confirmar',
      confirmButtonColor: '#560085',
      icon: "success",
    });

    $('#modal-documento').modal('hide');
    resetForm();
    loadNovoId();
    $('#prazoPagamento').val(1);
    $('#prazoPagamento').select2().trigger('change');
    document.querySelector("#prazoPagamento").parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    prazoPagamento.classList.remove("select2-danger");
    entidade.value = "";
    entidade.parentElement.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    entidade.className = "form-control";
    nomeEntidade.value = "";
    nomeEntidade.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    nomeEntidade.className = "form-control";
    moradaEntidade.value = "";
    moradaEntidade.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
    moradaEntidade.className = "form-control";
    nifEntidade.value = "";
    nifEntidade.className = "form-control";
    $('#tabelaArtigo').DataTable().clear().draw();
    footerPagamento.style.opacity = 0;
    document.querySelector(".nextBtn").removeAttribute('disabled');
    addRow();
    let tabelaPagamento = tabelaModoPagamento.querySelectorAll('input');
    for (let i = 0; i < tabelaPagamento.length; i++) {
      tabelaPagamento[i].value = "";
    }
  }

  function loadNovoId() {
    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
      tipoDocumento: "<?php echo $_GET['tipoDocumento']; ?>",
      natureza: "<?php echo $_GET['natureza']; ?>"
    }, "tipoDoc", function success(data) {
      funcaoCount("includes/count.inc.php", "post", "json", "documento", {
        idTIpoDoc: data[0]['tipoDoc']
      }, function success(data) {
        codigo.innerText = parseInt(data[0]["COUNT(*)"]) + 1;
      }, function error(data) {

      }, function done(data) {

      });
    }, function error(data) {

    }, function done(data) {

    });
  }

  $(document).ready(function() {
    loadNovoId();
    funcaoReadModoPagamento(function success(data) {
      let select = "";
      for (let i = 0; i < data.length; i++) {
        select += `
          <tr id="${data[i]['idModoPagamento']}">
            <td style="border: 0; width: 10%; vertical-align: middle;">${data[i]['idModoPagamento']}</td>
            <td style="border: 0; width: 70%; vertical-align: middle;">${data[i]['nome']}</td>
            <td style="border: 0; width: 20%;" vertical-align: middle;>
              <input type="text" class="form-control mp" placeholder="0,00">
            </td>
          </tr>`;
      }
      $("#modoPagamentoBody").html(select);
      modoPagamentoFormatedNumber();
    }, function error(data) {

    }, function done(data) {

    });
  });

  function modoPagamentoFormatedNumber() {
    let modoPagamento = document.getElementsByClassName("mp");
    for (let i = 0; i < modoPagamento.length; i++) {
      modoPagamento[i].addEventListener("keyup", function() {
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;

        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        sumModoPagamento(document.querySelectorAll(".mp"), entregueSpan, totalSpan, totalText, totalEntregue, totalDoc);
        recalcular();
      });
    }
  };

  $(document).on("keypress", "#entidade", function(e) {
    if (e.which === 13) {
      e.preventDefault();
      searchEntidade(entidade.value, tipoEntidade);
    }
  });

  $(document).on("focusout", "#entidade", function(e) {
    e.preventDefault();
    searchEntidade(entidade.value, tipoEntidade);
  });

  $(document).on("click", "#btn-search-entidade", function(e) {
    e.preventDefault();
    $('#modal-entidade').modal('show');
  });

  $(document).on("click", "#btn-print", function(e) {
    var iframe = document.getElementById('layoutDocumento');
    iframe.contentWindow.print();
  });

  /*function outrasOpcoes() {
    let totalOpcao = 0;
    let descontoOpcao = 0;
    let totalLiquidoOpcao = 0;
    let totalImpostoOpcao = 0;
    let total = document.querySelectorAll(".total");
    let preco = document.querySelectorAll(".preco");
    let qtd = document.querySelectorAll(".qtd");
    let desconto = document.querySelectorAll(".desconto");
    let imposto = document.querySelectorAll(".imposto");
    for (let i = 0; i < total.length; i++) {
      if (total[i].value != "") {
        totalOpcao += (parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.')));

        totalLiquidoOpcao += parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.'));

        totalImpostoOpcao += (parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(imposto[i].value.replace(/\ /g, '').replace(/\,/g, '.')) / 100));
      }

      if (total[i].value != "" && preco[i].value != "") {
        descontoOpcao += ((parseFloat(preco[i].value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(qtd[i].value.replace(/\ /g, '').replace(/\,/g, '.'))) - parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')));
      }
    }
    opcaoTotalBruto.innerText = parseFloat(totalOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoDescontoLinha.innerText = parseFloat(descontoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalLiquido.innerText = parseFloat(totalLiquidoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalImposto.innerText = parseFloat(totalImpostoOpcao).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    opcaoTotalDocumento.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    let dados = "";
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector('.inputSearchArtigo').value != "") {
        dados += `
      <tr>
        <td class="tdTaxa"><small>${parseFloat(tabela.rows[i].querySelector('.imposto').value).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</small></td>
        <td class="tdIncidencia"><small>${parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
        <td class="tdImposto"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
        <td class="tdValor"><small>${(parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) + (parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')) * (parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</small></td>
      </tr>
    `;
      }
    }
    $('#impostoOpcao').html(dados);

    let taxaSet = new Set();

    for (let i = 0; i < $("#impostoOpcao tr").length; i++) {
      let td = $("#impostoOpcao tr")[i].querySelector('.tdTaxa');
      let tr = $("#impostoOpcao tr")[i];

      if (taxaSet.has(td.innerText)) {
        let incidenciaAtual = parseFloat(tr.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        let novoValorIncidencia = incidenciaAtual + parseFloat(td.parentElement.querySelector('.tdIncidencia').innerText.replace(/\ /g, '').replace(/\,/g, '.'));
        tr.querySelector('.tdIncidencia').innerHTML = `<small>${novoValorIncidencia.toFixed(2)}</small>`;
        td.parentElement.remove();
      } else {
        taxaSet.add(td.innerText);
      }
    }

    opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

    $(document).on('keyup', '#arredondamento', function(e) {
      if (arredondamento.value != "") {
        opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao) + parseFloat(arredondamento.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      } else {
        opcaoValorPagar.innerText = (parseFloat(totalLiquidoOpcao) + parseFloat(totalImpostoOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    });

    $(document).on('keyup', '#descontoGlobalValor', function(e) {
      if (descontoGlobalValor.value != "") {
        opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

        descontoGlobalPorcentagem.value = ((parseFloat(descontoGlobalValor.value.replace(/\ /g, '').replace(/\,/g, '.')) / parseFloat(totalOpcao)) * 100).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    });

    $(document).on('keyup', '#descontoGlobalPorcentagem', function(e) {
      if (descontoGlobalPorcentagem.value != "") {
        opcaoTotalLiquido.innerText = (parseFloat(totalLiquidoOpcao) - parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.'))).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");

        descontoGlobalValor.value = ((parseFloat(descontoGlobalPorcentagem.value.replace(/\ /g, '').replace(/\,/g, '.')) / 100) * parseFloat(totalOpcao)).toFixed(2).replace(/\ /g, '').replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
      }
    });
  }*/

  function totalDocumento() {
    let all = 0;
    let total = document.querySelectorAll(".total");
    for (let i = 0; i < total.length; i++) {
      if (total[i].value != "") {

        all += (((parseFloat(total[i].closest('tr').querySelector('.imposto').value) / 100) * parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.'))) + parseFloat(total[i].value.replace(/\ /g, '').replace(/\,/g, '.')));

        //(parseFloat(entregueSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')) + 
      }
    }
    totalSpan.innerText = all;
    totalDoc = all;
    console.log("Total Documento all: ", all);
    totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
    sumModoPagamento(document.querySelectorAll(".mp"), entregueSpan, totalSpan, totalText, totalEntregue, totalDoc);
    ////();
    outrasOpcoes(document.querySelectorAll(".total"), document.querySelectorAll(".preco"), document.querySelectorAll(".qtd"), document.querySelectorAll(".desconto"), document.querySelectorAll(".imposto"), opcaoTotalBruto, opcaoDescontoLinha, opcaoTotalLiquido, opcaoTotalImposto, opcaoTotalDocumento, opcaoValorPagar, arredondamento, descontoGlobalValor, descontoGlobalPorcentagem, document.getElementById("tabelaArtigo"));
  }

  $(document).on("click", ".next-1", function(e) {
    e.preventDefault();
    ////();
  });

  /*
  OFICIAL
  function //() {
    descCodigo.innerText = codigo.innerText;
    descDocumento.innerText = $("#tipoDocumento option:selected").text();
    descSerie.innerText = serie.value;
    descPrazoPagamento.innerText = $("#prazoPagamento option:selected").text();
    descVendedor.innerText = vendedorFactura.value;
    descIdEntidade.innerText = entidade.value;
    descNome.innerText = nomeEntidade.value;
    descMorada.innerText = moradaEntidade.value;
    descNif.innerText = nifEntidade.value;
    descDataActual.innerText = "<?php echo "Data Actual: " . date("d-m-Y"); ?>";
    descCabecalho.innerText = "<?php echo $rows[1]['valor']; ?>";
    let tabela = document.getElementById("tabelaArtigo");
    let rows = "";
    for (i = 1; i < tabela.rows.length; i++) {
      if (tabela.rows[i].querySelector(".inputSearchArtigo").value != "" && tabela.rows[i].querySelector(".descricao").value != "" && tabela.rows[i].querySelector(".qtd").value != "" && tabela.rows[i].querySelector(".preco").value != "" && tabela.rows[i].querySelector(".desconto").value != "" && tabela.rows[i].querySelector(".total").value != "") {
        console.log("Linhas:", tabela.rows[i].querySelector(".inputSearchArtigo"));
        rows += `
        <tr>
          <td>${tabela.rows[i].querySelector(".inputSearchArtigo").value}</td>
          <td>${tabela.rows[i].querySelector(".descricao").value}</td>
          <td>${tabela.rows[i].querySelector(".qtd").value}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".preco").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".desconto").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".imposto").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</td>
          <td>${parseFloat(tabela.rows[i].querySelector(".total").value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
        </tr>`;
      }
    }
    $("#tabelaConfirmacaoBody").html(rows);
  }*/

  /*function funcaoQueryArtigo(id, linhaPreco) {
    $.ajax({
      url: "includes/read/queryArtigoList.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idArtigo: id,
        linhaPreco: linhaPreco
      },
      success: function(data) {
        if (data != null) {
          for (var key in data) {
            parametro.val(data[key]["idArtigo"]);
            parametro.closest('tr').find('.descricao').val(data[key]["nome"]);
            if (data[key]["precoSemImposto"] != null) {
              parametro.closest('tr').find('.preco').val(parseFloat(data[key]["precoSemImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
              parametro.closest('tr').find('.total').val(((parseFloat(data[key]["precoSemImposto"])) * parametro.closest('tr').find('.qtd').val()) - (((parseFloat(data[key]["precoSemImposto"])) * parametro.closest('tr').find('.qtd').val()) * parametro.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
            } else {
              parametro.closest('tr').find('.preco').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
              parametro.closest('tr').find('.total').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
            }
            parametro.closest('tr').find('.total').val(parseFloat(parametro.closest('tr').find('.total').val()).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
          }
        } else {
          parametro.val("");
          parametro.closest('tr').find('.descricao').val("");
          parametro.closest('tr').find('.preco').val("");
          parametro.closest('tr').find('.total').val("");
        }
      }
    }).done(function() {
      totalDocumento();
      let referencia = document.querySelectorAll(".inputSearchArtigo");
      let resultado = mesmoArtigoVerify(referencia);
      if (resultado != undefined) {
        console.log("Resultados: ", parseFloat(resultado[0].replace(/\ /g, '').replace(/\,/g, '.')), ", ", parseFloat(resultado[1].replace(/\ /g, '').replace(/\,/g, '.')));
        console.log("Vamos lá ver: ", parametro);
        let result = funcaoLinha(resultado);
        if (result != null) {
          return result.querySelector(".qtd").value = parseInt(result.querySelector(".qtd").value) + 1;
        }
        console.log("Resultado: ", result);
      }
    });
  }*/

  function funcaoLinha(resultado) {
    let tabela = document.getElementById("tabelaArtigo");
    for (i = 1; i < tabela.rows.length; i++) {
      let linha = tabela.rows[i].cells[0].querySelector("keyup").value;
      if (linha.includes(resultado[0].replace(/\ /g, '').replace(/\,/g, '.'))) {
        return tabela.rows[i];
      }
    }
    return null;
  }

  function mesmoArtigoVerify(referencia) {
    let valores = [];
    for (let i = 0; i < referencia.length; i++) {
      if (referencia[i].value !== "") {
        valores.push(referencia[i].value);
      }
    }
    let valoresDuplicados = [];
    for (let i = 0; i < valores.length; i++) {
      for (let j = i + 1; j < valores.length; j++) {
        if (valores[i] === valores[j] && !valoresDuplicados.includes(valores[i])) {
          valoresDuplicados.push(valores[i]);
        }
      }
    }
    if (valoresDuplicados.length > 0) {
      console.log("Valores: ", valoresDuplicados);
      var elemento = $(".inputSearchArtigo").filter(function() {
        return $(this).val().indexOf(valoresDuplicados) !== -1;
      });
      let valor = elemento.first().closest('tr').find('.qtd').val();
      if (valor == "") {
        valor = 1;
      } else {
        valor = parseInt(valor) + 1;
      }
      elemento.first().closest('tr').find('.qtd').val(valor);
      totalLinhaArtigo(elemento.closest('tr').find('.qtd')[0]);
      elemento.first().closest('tr').addClass('blink');
      setTimeout(function() {
        elemento.first().closest('tr').removeClass('blink');
      }, 200);
      var table = $('#tabelaArtigo').DataTable();
      var row = elemento.last().closest('tr');
      if ($('#tabelaArtigo tbody tr').length > 1) {
        table.row(row).remove().draw();
      }
    }
  }

  function funcaoEntidade(parametro) {
    let entidade = document.querySelector("#entidade");
    entidade.parentElement.parentElement.querySelectorAll('small')[0].innerText = parametro;
    entidade.placeholder = "Pesquisar " + parametro;
  }

  /*
  OFICIAL
  $(document).ready(function() {
    $.ajax({
      url: "includes/read/queryUser.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idUsuario: <?php echo $_SESSION["usuarioId"]; ?>
      },
      success: function(data) {
        for (var key in data) {
          vendedorFactura.value = data[key]["nome"];
        }
      }
    });
    serie.value = "<?php echo date("Y"); ?>";
  });*/

  $(document).ready(function() {
    funcaoSelect("includes/select.inc.php", "post", "json", "tipoDoc", function success(data) {
      let select = "";
      select += "<option value='0'>Selecione o Tipo de Documento</option>";
      for (var key in data) {
        select += "<option value=" + data[key]['idTipoDoc'] + ">" + data[key]['nome'] + "</option>";
      }
      $("#tipoDocumento").html(select);
    }, function error(data) {

    }, function done(data) {
      tipoDocumento.setAttribute("disabled", "disabled");
      let promessa = new Promise(function(resolve, reject) {
        let tipoDocumento = "<?php echo $_GET['tipoDocumento']; ?>";
        let natureza = "<?php echo $_GET['natureza']; ?>";
        let id = {
          tipoDocumento: tipoDocumento,
          natureza: natureza
        }
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", id, "tipoDoc", function success(data) {
          $('#tipoDocumento').val(data[0]['tipoDoc']);
          $('#tipoDocumento').select2().trigger('change');
          loadEntidade(data[0]['tipoEnt']);
          loadTabelaDocumento(data[0]['tipoDoc']);
          funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idTipoEntidade: data[0]['tipoEnt']
          }, "tipoEntidade", function success(data) {
            funcaoEntidade(data[0]['nome']);
          }, function error(data) {

          }, function done(data) {

          });
        }, function error(data) {

        }, function done(data) {

        });
      });
    });
  });

  $(document).ready(function() {
    let parametro = 1;
    funcaoSelect("includes/select.inc.php", "post", "json", "prazoPagamento", function success(data) {
      let select = "";
      select += "<option value='0'>Selecione um Prazo de Pagamento</option>";
      for (var key in data) {
        if (data[key]['idPrazoPagamento'] == parametro) {
          select += "<option value=" + data[key]['idPrazoPagamento'] + ">" + data[key]['nome'] + "</option>";
        } else {
          select += "<option value=" + data[key]['idPrazoPagamento'] + " disabled='disabled'>" + data[key]['nome'] + "</option>";
        }
      }
      $("#prazoPagamento").html(select);
    }, function error(data) {

    }, function done(data) {
      $('#prazoPagamento').val(parametro);
      $('#prazoPagamento').select2().trigger('change');
    });

    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
      idUsuario: 1
    }, "viewusuariotipo", function success(data) {
      vendedorFactura.value = data[0]['nome'];
    }, function error(data) {}, function done(data) {

    });
  });

  $(document).on('click', '.btn-layout', function(e) {
    e.preventDefault();
    var iframe = document.getElementById('layoutDocumento');

    function loadDocumento() {
      iframe.contentWindow.codigoDocumento(idDoc, tipoDocumento.value);
    }
    iframe.onload = loadDocumento;
    iframe.src = this.id;
    $('#modal-layout').modal('show');
  });

  function readLayout(url, tipoLayout) {
    $.ajax({
      url: url,
      type: "head",
      success: function(data) {
        document.querySelector('iframe').src = url;
        $('#modal-layout').modal('show');
      },
      error: function(data) {
        if (data.status === 404) {
          console.log('O arquivo não existe.');
          createLayout(codigoReport, nomeReport, tipoLayout);
        } else {
          console.error('Erro na verificação do arquivo.');
        }
      }
    });
  }

  $(document).on('click', '#tabelaArtigoListagem tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    $('#tabelaArtigoListagem tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
    }
  });

  $(document).on('click', '#tabelaEntidade tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    $('#tabelaEntidade tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
    }
  });

  $(document).on('click', '#tabelaDocumento tbody tr', function() {
    var isSelected = $(this).hasClass('selected');
    let btn = document.querySelectorAll(".btn-layout");
    $('#tabelaDocumento tbody tr').removeClass('selected');
    if (!isSelected) {
      $(this).addClass('selected');
      for (let i = 0; i < btn.length; i++) {
        btn[i].removeAttribute("disabled");
      }
      idDoc = $(this).closest('tr').find('td')[0].innerText;
    } else {
      for (let i = 0; i < btn.length; i++) {
        btn[i].setAttribute("disabled", "disabled");
      }
    }
  });

  $(document).ready(function() {
    let linhaPreco = 0;
    loadTabelaArtigo(linhaPreco, function callback(data) {
      console.log("Pegar: ", data);
      $("#tabelaArtigoListagem").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "idArtigo"
        }, {
          data: "nome"
        }, {
          data: "familiaNome"
        }, {
          data: "precoSemImposto",
          render: function(data, type, row) {
            if (data == null) {
              return `0,00`;
            } else {
              return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
            }
          }
        }, {
          data: "precoComImposto",
          render: function(data, type, row) {
            if (data == null) {
              return `0,00`;
            } else {
              return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
            }
          }
        }, {
          data: "stock"
        }],
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "language": idiomaPortugues,
        lengthMenu: [
          [7, 25, 50, -1],
          [10, 25, 50, 'All']
        ]
      }).buttons().container().appendTo('#tabelaArtigoListagem_wrapper .col-md-6:eq(0)');
      /*var tabelaArtigoListagem = $("#tabelaArtigoListagem").DataTable();
      tabelaArtigoListagem.clear();
      tabelaArtigoListagem.rows.add(data);
      tabelaArtigoListagem.draw();*/
    });
  });

  var idiomaPortugues = {
    buttons: {
      copy: "Copiar",
      print: "Imprimir",
      colvis: "Visibilidade"
    },
    "sProcessing": "A processar...",
    "sLengthMenu": "Mostrar _MENU_ dos registros",
    "sZeroRecords": "Sem resultados!",
    "sEmptyTable": "Tabela sem dados disponíveis",
    "sInfo": "De _START_ à _END_ de um total de _TOTAL_ registros",
    "sInfoEmpty": "De 0 à 0 de um total de 0 registros",
    "sInfoFiltered": "(filtrado de um total de _MAX_ registros)",
    "sInfoPostFix": "",
    "sSearch": "Pesquisar:",
    "sUrl": "",
    "sInfoThousands": ",",
    "sLoadingRecords": "A carregar...",
    "oPaginate": {
      "sFirst": "Primeira",
      "sLast": "Última",
      "sNext": "Seguinte",
      "sPrevious": "Anterior"
    },
    "oAria": {
      "sSortAscending": ": Activar para ordenar a coluna de forma ascendente",
      "sSortDescending": ": Activar para ordenar a coluna de forma descendente"
    }
  }

  $('#tabelaEntidade tbody').on('click', 'td', function() {
    let tabela = document.getElementById("tabelaEntidade");
    for (i = 1; i < tabela.rows.length; i++) {
      tabela.rows[i].ondblclick = function() {
        searchEntidade(this.cells[0].innerText, tipoEntidade);
        $('#modal-entidade').modal('hide');
      }
    }
  });

  function searchEntidade(idEntidade, tipoEntidade) {
    if (idEntidade === "0") {
      let elemento = entidade.parentElement.parentElement.querySelectorAll("small");
      elemento[1].style.visibility = "visible";
      elemento[1].style.color = "#28a745";
      elemento[1].innerText = elemento[0].innerText + " passante";
      entidade.className = "form-control";
      nomeEntidade.removeAttribute('disabled');
      nomeEntidade.value = "";
      moradaEntidade.value = "";
      nifEntidade.value = "";
      firstNextBtn.removeAttribute('disabled');
    } else {
      funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
        idEntidade: idEntidade,
        idTipoEntidade: tipoEntidade
      }, "viewEntidade", function success(data) {
        entidade.parentElement.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
        nomeEntidade.setAttribute('disabled', 'disabled');
        nomeEntidade.className = "form-control";
        nomeEntidade.parentElement.querySelectorAll("small")[1].style.visibility = "hidden";
        const firstNextBtn = document.querySelector(".nextBtn");
        if (data == null) {
          idEntidade = undefined;
          entidade.value = "";
          nomeEntidade.value = "";
          moradaEntidade.value = "";
          nifEntidade.value = "";
          linhaPrecoEntidade = "";
          firstNextBtn.setAttribute('disabled', 'disabled');
        } else {
          for (let i = 0; i < data.length; i++) {
            idEntidade = data[i]['idEntidade'];
            entidade.value = data[i]['idEntidade'];
            nomeEntidade.value = data[i]['nome'];
            moradaEntidade.value = data[i]['morada'];
            nifEntidade.value = data[i]['nif'];
            linhaPrecoEntidade = data[i]["linhaPreco"];
            firstNextBtn.removeAttribute('disabled');
          }
        }
      }, function error(data) {

      }, function done(data) {
        let linhaPreco;
        if (data != null) {
          if (data[0]['linhaPreco'] == 0) {
            funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
              idDefinicao: 2
            }, "definicao", function success(data) {
              linhaPreco = data[0]['valor'];
            }, function error(data) {

            }, function done(data) {

            });
          } else {
            linhaPreco = data[0]['linhaPreco'];
          }
          loadTabelaArtigo(linhaPreco, function callback(data) {
            var tabelaArtigoListagem = $("#tabelaArtigoListagem").DataTable();
            tabelaArtigoListagem.clear();
            tabelaArtigoListagem.rows.add(data);
            tabelaArtigoListagem.draw();
          });
        }
      });
    }
  }

  function loadTabelaArtigo(linhaPreco, callback) {
    let tabela;
    let iteracao = 0;
    funcaoSelect("includes/select.inc.php", "post", "json", "viewartigousuariofamilia", function success(data) {
      tabela = data;
      for (let i = 0; i < data.length; i++) {
        tabela[i].precoComImposto = 0;
        tabela[i].precoSemImposto = 0;
        tabela[i].stock = 0;
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
          idArtigo: data[i]["idArtigo"],
          indice: linhaPreco
        }, "precoArtigo", function success(data) {
          if (data != null) {
            $("#tabelaArtigoListagem").DataTable().cell(i, 3).data(data[0]['semImposto']).draw();
            $("#tabelaArtigoListagem").DataTable().cell(i, 4).data(data[0]['comImposto']).draw();
          }
          funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idArtigo: tabela[i]["idArtigo"]
          }, "artigoStock", function success(data) {
            if (data != null) {
              $("#tabelaArtigoListagem").DataTable().cell(i, 5).data(data[0]['qtdDisponivel']).draw();
            }
          }, function error(data) {

          }, function done(data) {

          });
        }, function error(data) {

        }, function done(data) {

        });
        iteracao = iteracao + 1;
      }
      if (iteracao == data.length) {
        callback(tabela);
      }
    }, function error(data) {

    }, function done(data) {});
  }

  function loadQueryArtigo(id, linhaPreco, callback) {
    let dados;
    funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
      idArtigo: id
    }, "viewartigousuariofamilia", function success(data) {
      dados = data;
      if (data != null) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
          idArtigo: data[0]["idArtigo"],
          indice: linhaPreco
        }, "precoArtigo", function success(data) {
          console.log("Preço: ", data);
          if (data != null) {
            dados[0].precoComImposto = data[0]['comImposto'];
            dados[0].precoSemImposto = data[0]['semImposto'];
          } else {
            dados[0].precoComImposto = 0;
            dados[0].precoSemImposto = 0;
          }
          funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
            idArtigo: dados[0]["idArtigo"]
          }, "artigoStock", function success(data) {
            if (data != null) {
              dados[0].stock = data[0]['qtdDisponivel'];
            } else {
              dados[0].stock = 0;
            }
          }, function error(data) {

          }, function done(data) {
            callback(dados);
          });
        }, function error(data) {

        }, function done(data) {});
      } else {
        callback(null);
      }
    }, function error(data) {}, function done(data) {

    });
  }
</script>
<script>
  let linha;
  $(document).ready(function() {
    addRow();
    $.ajax({
      url: "includes/read/tipoUsuario.inc.php",
      type: "post",
      dataType: "json",
      success: function(data) {
        let select = "";
        select += "<option value='0'>Selecione um Tipo de Usuario</option>";
        for (var key in data) {
          select += "<option value=" + data[key]['idTipoUsuario'] + ">" + data[key]['nome'] + "</option>";
        }
        $("#idTipoUsuario").html(select);
      }
    });
  });

  /*function loadTabelaDocumento(tipoDocumento) {
    $.ajax({
      url: "includes/read/documentoTipo.inc.php",
      type: "post",
      dataType: "json",
      data: {
        idTipoDoc: tipoDocumento
      },
    }).done(function(data) {
      console.log(data);
      $("#tabelaDocumento").DataTable({
        select: 'single',
        "aaData": data,
        "columns": [{
          data: "codigoDocumento"
        }, {
          data: "entregue",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "troco",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "dataDoc"
        }, {
          data: "nomeU"
        }, {
          data: "total",
          render: function(data, type, row) {
            return parseFloat(data).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          }
        }, {
          data: "nomeE"
        }, {
          data: null,
          render: function(data, type, row) {
            if (data["entregue"] >= data["total"]) {
              return "<small class='badge badge-success'>Pago</small>";
            } else {
              if (data["entregue"] == 0) {
                return "<small class='badge badge-danger'>Por Pagar</small>";
              } else {
                return "<small class='badge badge-warning'>Pago Parcialmente</small>";
              }
            }
          }
        }, {
          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-cancel" style="padding: .8rem; border-radius: 5px;">Anular</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item" style="padding: .8rem; border-radius: 5px;">Duplicar</a></li>
              <li style="padding: 0 .4rem;"><a href="#" class="dropdown-item" style="padding: .8rem; border-radius: 5px;">Anular e Duplicar</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"],
        order: [
          [3, 'asc']
        ]
      }).buttons().container().appendTo('#tabelaDocumento_wrapper .col-md-6:eq(0)');
    });
  }*/

  var idiomaPortugues = {
    buttons: {
      copy: "Copiar",
      print: "Imprimir",
      colvis: "Visibilidade"
    },
    "sProcessing": "A processar...",
    "sLengthMenu": "Mostrar _MENU_ dos registros",
    "sZeroRecords": "Sem resultados!",
    "sEmptyTable": "Tabela sem dados disponíveis",
    "sInfo": "De _START_ à _END_ de um total de _TOTAL_ registros",
    "sInfoEmpty": "De 0 à 0 de um total de 0 registros",
    "sInfoFiltered": "(filtrado de um total de _MAX_ registros)",
    "sInfoPostFix": "",
    "sSearch": "Pesquisar:",
    "sUrl": "",
    "sInfoThousands": ",",
    "sLoadingRecords": "A carregar...",
    "oPaginate": {
      "sFirst": "Primeira",
      "sLast": "Última",
      "sNext": "Seguinte",
      "sPrevious": "Anterior"
    },
    "oAria": {
      "sSortAscending": ": Activar para ordenar a coluna de forma ascendente",
      "sSortDescending": ": Activar para ordenar a coluna de forma descendente"
    }
  }

  $('#tabelaDocumento tbody').on('click', 'td', function() {
    let tabela = document.getElementById("tabelaDocumento");

    for (i = 1; i < tabela.rows.length; i++) {
      tabela.rows[i].ondblclick = function() {
        linha = this.cells[0].parentElement;
        idUsuario = this.cells[0].innerHTML;
        nomeEdit = this.cells[1];
        generoEdit = this.cells[2];
        biEdit = this.cells[3];
        emailEdit = this.cells[4];
        nomeUsuarioEdit = this.cells[5];

        console.log(idUsuario);
        ajax();
        //$('#modal-lg').modal('show');
        //this.classList.remove("selected");
      }
    }

    function ajax() {
      $.ajax({
        url: "includes/read/queryUser.inc.php",
        type: "post",
        dataType: "json",
        data: {
          idUsuario: idUsuario
        },
        success: function(data) {
          console.log("Resultados: ", data);
          imagemInfo = document.getElementById("imagemInfo");
          img = document.querySelector(".image-info");

          imgUpdate = document.querySelector(".image-container");

          for (var key in data) {
            if (data[key]['imagem'] != null) {
              img.querySelector("i").style.display = "none";
              imagemInfo.style.backgroundImage = "url('images/usuario/" + data[key]['imagem'] + "')";
              console.log("Tem imagem!");
            } else {
              console.log("Não tem imagem!");
              img.querySelector("i").style.display = "block";
              imagemInfo.style.backgroundImage = "url('images/usuario/" + data[key]['imagem'] + "')";
            }

            nomeModal.innerText = data[key]['nome'];
            idInfo.innerText = data[key]['idUsuario'];
            nomeInfo.innerText = data[key]['nome'];
            nomeUsuarioInfo.innerText = data[key]['nomeUsuario'];
            generoInfo.innerText = data[key]['genero'];
            biInfo.innerText = data[key]['bi'];
            emailInfo.innerText = data[key]['email'];
            enderecoInfo.innerText = data[key]['endereco'];
            telefoneInfo.innerText = data[key]['telefone'];
            dataNascInfo.innerText = data[key]['dataNasc'];
            dataAdesaoInfo.innerText = data[key]['dataAdesao'];
            estadoInfo.innerText = data[key]['estado'];
            tipoUsuarioInfo.innerText = data[key]['tipoUsuario'];

            imgUpdate.style.backgroundImage = "url('images/usuario/" + data[key]['imagem'] + "')";
            imgUpdate.querySelector("i").style.display = "none";

            nome.value = data[key]['nome'];
            nomeUsuario.value = data[key]['nomeUsuario'];

            $('#genero').val(data[key]['genero']);
            $('#genero').select2().trigger('change');

            email.value = data[key]['email'];
            bi.value = data[key]['bi'];

            $('#idTipoUsuario').val(data[key]['idTipoUsuario']);
            $('#idTipoUsuario').select2().trigger('change');
          }
        }
      }).done(function(data) {
        $('#modal-updateUsuario').modal('show');
      });
    }
  });

  function totalLinhaArtigo(parametro) {
    if (parametro.closest('tr').querySelector('.total').value != "") {
      parametro.closest('tr').querySelector('.total').value = (parseFloat(parametro.closest('tr').querySelector('.preco').value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.closest('tr').querySelector('.qtd').value.replace(/\ /g, '').replace(/\,/g, '.'))) - ((parseFloat(parametro.closest('tr').querySelector('.preco').value.replace(/\ /g, '').replace(/\,/g, '.')) * parseFloat(parametro.closest('tr').querySelector('.qtd').value.replace(/\ /g, '').replace(/\,/g, '.'))) * parseFloat(parametro.closest('tr').querySelector('.desconto').value.replace(/\,/g, '.').replace(/\%/g, '')) / 100);
      parametro.closest('tr').querySelector('.total').value = parseFloat(parametro.closest('tr').querySelector('.total').value).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
    }
    totalDocumento();
    //viewConfirmacao();
  }

  $(document).on("change", ".imposto", function(e) {
    e.preventDefault();
    let total = 0;
    if ($(this).closest('tr').find('.total').val() != "") {
      let tabela = document.getElementById("tabelaArtigo");
      for (i = 1; i < tabela.rows.length; i++) {
        if (tabela.rows[i].querySelector('.total').value != "") {
          total += (((parseFloat(tabela.rows[i].querySelector('.imposto').value.replace(/\ /g, '').replace(/\,/g, '.')) / 100) * parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.'))) + parseFloat(tabela.rows[i].querySelector('.total').value.replace(/\ /g, '').replace(/\,/g, '.')));
          console.log("Linhas: ", total);
        }
      }
      totalSpan.innerText = total;
      //totalDoc = total;
      totalDocumento();
      sumModoPagamento(document.querySelectorAll(".mp"), entregueSpan, totalSpan, totalText, totalEntregue, totalDoc);
      totalSpan.innerText = parseFloat(totalSpan.innerText.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + " Kzs";
      recalcular();
    }
  });

  $(document).on("click", "#btn", function(e) {
    e.preventDefault();
    var table = $("#tabelaArtigo").DataTable();
    table.destroy();
    var tabela = $("#tabelaArtigo").DataTable({
      select: 'single',
      dom: 'Bfrtip',
      buttons: [{
        text: 'Adicionar Artigo',
        action: function(e, dt, node, config) {
          addRow();
        }
      }],
      "searching": false,
      "responsive": true,
      "lengthChange": false,
      "autoWidth": true,
      "language": idiomaPortugues,
      lengthMenu: [
        [7, 25, 50, -1],
        [10, 25, 50, 'All']
      ],
      columnDefs: [{
        targets: -1,
        orderable: false
      }],
      scrollResize: true,
      scrollCollapse: true,
      paging: false,
      scrollY: "32vh"
    });

    $('#modal-documento').modal('show');

    $('#modal-documento').on('shown.bs.modal', function() {
      tabela.columns.adjust().draw();
    });
    /*$('#modal-documento').modal({
      backdrop: 'static'
    }, 'show');*/
  });

  $('#tabelaArtigo').on('click', '.btnSearchArtigo', function() {
    let botao = $(this);
    $('#modal-artigo').modal('show');
    $('#tabelaArtigoListagem tbody').on('click', 'td', function() {
      let tabela = document.getElementById("tabelaArtigoListagem");

      for (i = 1; i < tabela.rows.length; i++) {
        tabela.rows[i].ondblclick = function() {
          $.ajax({
            url: "includes/read/queryArtigoList.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idArtigo: this.cells[0].innerText,
              linhaPreco: linhaPrecoEntidade
            },
            success: function(data) {
              console.log("Esses são os dados: ", data);
              for (var key in data) {
                botao.closest('tr').find('.inputSearchArtigo').val(data[key]["idArtigo"]);
                botao.closest('tr').find('.descricao').val(data[key]["nome"]);
                if (data[key]["precoSemImposto"] != null) {
                  botao.closest('tr').find('.preco').val(parseFloat(data[key]["precoSemImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                  botao.closest('tr').find('.total').val(((data[key]["precoSemImposto"]) * botao.closest('tr').find('.qtd').val()) - (((data[key]["precoSemImposto"]) * botao.closest('tr').find('.qtd').val()) * botao.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
                } else {
                  botao.closest('tr').find('.preco').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                  botao.closest('tr').find('.total').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                }
                botao.closest('tr').find('.total').val(parseFloat(botao.closest('tr').find('.total').val()).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
                $('#modal-artigo').modal('hide');
              }
            }
          }).done(function() {
            totalDocumento();
            let referencia = document.querySelectorAll(".inputSearchArtigo");
            let resultado = mesmoArtigoVerify(referencia);
            if (resultado != undefined) {
              console.log("Resultados: ", parseFloat(resultado[0].replace(/\ /g, '').replace(/\,/g, '.')), ", ", parseFloat(resultado[1].replace(/\ /g, '').replace(/\,/g, '.')));
              console.log("Vamos lá ver: ", parametro);
              let result = funcaoLinha(resultado);
              if (result != null) {
                return result.querySelector(".qtd").value = parseInt(result.querySelector(".qtd").value) + 1;
              }
              console.log("Resultado: ", result);
            }
          });
        }
      }
    });
  });

  function addRow() {
    var table = $('#tabelaArtigo').DataTable();
    var linha = $(`<tr>
        <td style="padding: .2rem; vertical-align: inherit;">
          <div class="input-group input-group">
            <input type="text" class="form-control inputSearchArtigo" placeholder="Procurar" title="Procurar Artigo" data-inputmask="'mask': ['AAA-99-99-AA', 'LD-99-99-AA']" data-mask>
            <div class="input-group-append">
              <button type="button" class="btn btn btn-default btnSearchArtigo"  style="line-height: 0 ;">
                  <i class="fa fa-search"></i>
              </button>
            </div>
          </div>
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control descricao" placeholder="Descrição" title="Descrição">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control qtd" placeholder="Quantidade" title="Quantidade" value="1">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control preco" placeholder="Preço" title="Preço">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control desconto" placeholder="Desconto" title="Desconto" value="0">
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <select class="form-control imposto select2" style="width: 100%;" placeholder="Imposto" title="Imposto">
          </select>
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <input type="text" class="form-control total" placeholder="Total" title="Total" disabled>
        </td>
        <td style="padding: .2rem; vertical-align: inherit;">
          <button class='btn btn-block btn-danger btn-delete remove_row' type='button'><i class="fa fa-xmark"></i></button>
        </td>
    </tr>`);
    const no = table.row.add(linha).draw().node();
    $(function() {
      //Initialize Select2 Elements
      $('.select2').select2()

      //Initialize Select2 Elements
      $('.select2bs4').select2({
        theme: 'bootstrap4'
      })
    });
    funcaoSelect("includes/select.inc.php", "post", "json", "imposto", function success(data) {
      let select = "";
      for (var key in data) {
        select += "<option value=" + data[key]['idImposto'] + " data-taxa=" + data[key]['taxa'] + ">" + data[key]['nome'] + "</option>";
      }
      $(no).find('.imposto').html(select);
    }, function error(data) {

    }, function done(data) {

    });
    let preco = document.querySelectorAll(".preco");
    for (let i = 0; i < preco.length; i++) {
      preco[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
          totalSpan.className = "";
        }
        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        var parts = this.value.replace(/\ /g, '').replace(/\,/g, '.').split('.');
        /*if (parts[1].length > 2) {
          var novoValor = parseFloat(this.value.replace(/\ /g, '').replace(/\,/g, '.')).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ");
          this.value = novoValor;
        }*/
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
        }
        if (this.value != "" && this.closest('tr').querySelector('.qtd').value != "" && this.closest('tr').querySelector('.desconto').value != "") {
          totalLinhaArtigo(preco[i]);
        }
        //totalLinhaArtigo(preco[i]);
      });
    }

    let qtd = document.querySelectorAll(".qtd");
    for (let i = 0; i < qtd.length; i++) {
      qtd[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
          totalSpan.className = "";
        }

        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        if (this.value != "" && this.closest('tr').querySelector('.preco').value != "" && this.closest('tr').querySelector('.desconto').value != "") {
          totalLinhaArtigo(qtd[i]);
        }
        //totalLinhaArtigo(qtd[i]);
      });
    }

    let desconto = document.querySelectorAll(".desconto");

    for (let i = 0; i < desconto.length; i++) {
      desconto[i].addEventListener("keyup", function(e) {
        e.preventDefault();
        var removeChar = this.value.replace(/[^0-9,\.]/g, '');
        var removeDot = removeChar.replace(/\./g, '');
        this.value = removeDot;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
          totalSpan.className = "";
        }
        var formatedNumber = this.value.replace(/\B(?=(\d{3})+(?!\d))/g, " ");
        this.value = formatedNumber;
        if (this.value == "") {
          this.closest('tr').querySelector('.total').value = "0,00";
          totalSpan.innerText = "0,00 Kzs";
        }

        if (this.value != "" && this.closest('tr').querySelector('.qtd').value != "" && this.closest('tr').querySelector('.preco').value != "") {
          totalLinhaArtigo(desconto[i]);
        }
        if (this.value.replace(/\ /g, '') > 100) {
          this.value = 100;
        }
        //totalLinhaArtigo(desconto[i]);
      });

      desconto[i].addEventListener("focusout", function(e) {
        e.preventDefault();
        if (desconto[i].value == "") {
          desconto[i].value = "0";
          totalLinhaArtigo(desconto[i]);
        }
      });
    }
  }

  $('#tabelaDocumento').on('click', '.btn-cancel', function(e) {
    e.preventDefault();
    swal.fire({
      title: "Tem a certeza que pretende anular este documento?",
      text: "Documento: " + $(this).closest('tr').find('td')[0].textContent,
      icon: "warning",
      showCancelButton: true,
      confirmButtonText: 'Confirmar',
      confirmButtonColor: '#560085',
      cancelButtonText: 'Cancelar',
      cancelButtonColor: '#560085',
    }).then((result) => {
      if (result.isConfirmed) {
        $.ajax({
          url: "includes/read/queryCodigoDocumento.inc.php",
          type: "post",
          dataType: "json",
          data: {
            codigo: $(this).closest('tr').find('td')[0].textContent.split("/")[1],
            tipoDocumento: tipoDocumento.value
          },
          success: function(data) {
            let codigo = data[0]['idDocumento'];

            $.ajax({
              url: "includes/update/estadoDocumento.inc.php",
              type: "post",
              dataType: "json",
              data: {
                idDocumento: codigo,
                estado: 0
              },
              success: function(data) {
                swal.fire({
                  title: "Documento Anulado com sucesso!",
                  text: "Documento anulado",
                  confirmButtonText: 'Confirmar',
                  confirmButtonColor: '#560085',
                  icon: "success",
                });
              }
            });
          }
        });
      }
    });
  });

  $('#tabelaDocumento').on('click', '.btn-more', function(e) {
    e.preventDefault();
    detalhes($(this).closest('tr').find('td')[0].textContent.split("/")[1], tipoDocumento.value);
  });

  /*
  OFICIAL
  function detalhes(id, tipoDocumento) {
    detalheCabecalho.innerText = "<?php echo $rows[1]['valor']; ?>";
    $.ajax({
      url: "includes/read/queryCodigoDocumento.inc.php",
      type: "post",
      dataType: "json",
      data: {
        codigo: id,
        tipoDocumento: tipoDocumento
      },
      success: function(data) {
        let codigo = data[0]['idDocumento'];

        $.ajax({
          url: "includes/read/queryDocumentoModoPagamento.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idDocumento: codigo,
          },
          success: function(data) {
            let row = "";
            for (var key in data) {
              row += `<p><span>${data[key]['nomeMp']}</span> - <span>${data[key]['valor'].replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</span></p>`;
            }
            $("#detalheModoPagamento").html(row);
          }
        });
        $.ajax({
          url: "includes/read/queryDocumentoLinha.inc.php",
          type: "post",
          dataType: "json",
          data: {
            idDocumento: codigo,
          },
          success: function(data) {
            let row = "";
            for (var key in data) {
              row += `
            <tr>
              <td>${data[key]['idArtigoAd']}</td>
              <td>${data[key]['descricaoAd']}</td>
              <td>${parseInt(data[key]['qtdAd']).toFixed(0).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
              <td>${parseFloat(data[key]['precoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
              <td>${parseFloat(data[key]['descontoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
              <td>${parseFloat(data[key]['impostoAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ") + "%"}</td>
              <td>${parseFloat(data[key]['totalAd']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
            </tr>
            `;
            }
            $("#corpoTabelaDetalhes").html(row);
          }
        }).done(function() {
          $.ajax({
            url: "includes/read/queryDocumento.inc.php",
            type: "post",
            dataType: "json",
            data: {
              idDocumento: codigo,
            },
            success: function(data) {
              console.log("Aqui: ", data);
              detalheDataActual.innerText = "Data Documento: " + data[0]['dataDoc'];
              detalheCodigo.innerText = data[0]['codigoDocumento'];
              detalheDocumento.innerText = data[0]['nomeTd'];
              detalheSerie.innerText = data[0]['serieDocumento'];
              detalhePrazoPagamento.innerText = data[0]['nomePp'];
              detalheVendedor.innerText = data[0]['nomeU'];
              detalheIdEntidade.innerText = data[0]['idEntidade'];
              detalheNome.innerText = data[0]['nomeE'];
              detalheMorada.innerText = data[0]['moradaE'];
              detalheNif.innerText = data[0]['nifE'];

              let row = `
          <tr>
            <th>Entregue</th>
            <td>${parseFloat(data[0]['entregue']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          </tr>
          <tr>
            <th>Troco</th>
            <td>${parseFloat(data[0]['troco']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          </tr>
          <tr>
            <th>Total</th>
            <td>${parseFloat(data[0]['total']).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " ")}</td>
          </tr>
          `;
              $("#detalheTabelaMontante").html(row);
              if (data[0]["entregue"] >= data[0]["total"]) {
                corpoTabelaDetalhes.innerHTML += `<td colspan="7" style="color: #676767a6; font-size: 4rem; border-bottom: 1px solid #dee2e6;">Pago</td>`;
              } else {
                if (data[0]["entregue"] == 0) {
                  corpoTabelaDetalhes.innerHTML += `<td colspan="7" style="color: #676767a6; font-size: 4rem; border-bottom: 1px solid #dee2e6;">Por Pagar</td>`;
                } else {
                  corpoTabelaDetalhes.innerHTML += `<td colspan="7" style="color: #676767a6; font-size: 4rem; border-bottom: 1px solid #dee2e6;">Pago Parcialmente</td>`;
                }
              }
            }
          }).done(function() {
            $('#modal-detalhes').modal('show');
          });
        });
      }
    });
  }*/

  $('#tabelaArtigo').on('click', '.remove_row', function(e) {
    e.preventDefault();
    var table = $('#tabelaArtigo').DataTable();
    var row = $(this).closest('tr');
    if ($('#tabelaArtigo tbody tr').length > 1) {
      table.row(row).remove().draw();
    } else {
      row.find('.inputSearchArtigo').val("");
      row.find('.descricao').val("");
      row.find('.qtd').val(1);
      row.find('.preco').val("");
      row.find('.desconto').val("0,00%");
      row.find('.imposto').val(0);
      row.find('.imposto').select2().trigger('change');
      row.find('.total').val("");
    }
    totalDocumento();
  });

  $('#tabelaArtigo').on('keypress', '.inputSearchArtigo', function() {
    let parametro = $(this);
    if (event.which === 13) {
      event.preventDefault();
      let linhaPreco;
      if (linhaPrecoEntidade == 0) {
        funcaoQuerySelect("includes/querySelect.inc.php", "post", "json", {
          idDefinicao: 2
        }, "definicao", function success(data) {
          linhaPreco = data[0]['valor'];
        }, function error(data) {

        }, function done(data) {

        });
      } else {
        linhaPreco = linhaPrecoEntidade;
      }
      loadQueryArtigo($(this).val(), linhaPreco, function callback(data) {
        getArtigo(data, parametro);
        totalDocumento();
        let referencia = document.querySelectorAll(".inputSearchArtigo");
        let resultado = mesmoArtigoVerify(referencia);
        if (resultado != undefined) {
          let result = funcaoLinha(resultado);
          if (result != null) {
            return result.querySelector(".qtd").value = parseInt(result.querySelector(".qtd").value) + 1;
          }
        }
      });
    }
  });

  $('#tabelaArtigo').on('focusout', '.inputSearchArtigo', function() {
    event.preventDefault();
    let parametro = $(this);
    if (this.value == "") {
      $(this).closest('tr').find('.inputSearchArtigo').val("");
      $(this).closest('tr').find('.descricao').val("");
      $(this).closest('tr').find('.qtd').val(1);
      $(this).closest('tr').find('.preco').val("");
      $(this).closest('tr').find('.desconto').val("0,00%");
      $(this).closest('tr').find('.imposto').val(0);
      $(this).closest('tr').find('.imposto').select2().trigger('change');
      $(this).closest('tr').find('.total').val("");
    } else {
      funcaoQueryArtigo($(this).val(), linhaPrecoEntidade, function success(data) {
        getArtigo(data, parametro);
      }, function error(data) {

      }, function done(data) {
        totalDocumento();
        let referencia = document.querySelectorAll(".inputSearchArtigo");
        let resultado = mesmoArtigoVerify(referencia);
        if (resultado != undefined) {
          let result = funcaoLinha(resultado);
          if (result != null) {
            return result.querySelector(".qtd").value = parseInt(result.querySelector(".qtd").value) + 1;
          }
        }
      });
    }
    totalDocumento();
  });

  function getArtigo(data, parametro) {
    if (data != null) {
      for (var key in data) {
        parametro.val(data[key]["idArtigo"]);
        parametro.closest('tr').find('.descricao').val(data[key]["nome"]);
        if (data[key]["precoSemImposto"] != null) {
          parametro.closest('tr').find('.preco').val(parseFloat(data[key]["precoSemImposto"]).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
          parametro.closest('tr').find('.total').val(((parseFloat(data[key]["precoSemImposto"])) * parametro.closest('tr').find('.qtd').val()) - (((parseFloat(data[key]["precoSemImposto"])) * parametro.closest('tr').find('.qtd').val()) * parametro.closest('tr').find('.desconto').val().replace(/\,/g, '.').replace(/\%/g, '') / 100));
        } else {
          parametro.closest('tr').find('.preco').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
          parametro.closest('tr').find('.total').val(parseFloat(0).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
        }
        parametro.closest('tr').find('.total').val(parseFloat(parametro.closest('tr').find('.total').val()).toFixed(2).replace(/\./g, ',').replace(/\B(?=(\d{3})+(?!\d))/g, " "));
      }
    } else {
      parametro.val("");
      parametro.closest('tr').find('.descricao').val("");
      parametro.closest('tr').find('.preco').val("");
      parametro.closest('tr').find('.total').val("");
    }
  }

  $(document).on("click", "#outrasOpcoes", function(e) {
    e.preventDefault();
    document.querySelector('.tooltip-content').classList.toggle("tooltip-show");
  });
</script>