var table = $('#table-notas-pagamento').DataTable({
  "responsive": true,
  "serverSide": false,
  "pageLength" : 25,
  "ajax": {
      url: "/app/data/datatables.php", // json datasource
      data: {action: 'getNotaspagamento'},
      type: 'post',
  },
  error: function () {

  },
  columnDefs: [
    { targets: 'no-sort', orderable: false },
    { "targets": [5], "visible": false, "searchable": false },
  ],
  "language": {
      "lengthMenu": "_MENU_",
      "info": "A mostrar _START_-_END_ de _TOTAL_",
      "search": "Pesquisar:",
      "paginate": {
        "next": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" viewBox=\"0 0 451.846 451.847\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 451.846 451.847;\" xml:space=\"preserve\"><path d=\"M345.441,248.292L151.154,442.573c-12.359,12.365-32.397,12.365-44.75,0c-12.354-12.354-12.354-32.391,0-44.744 L278.318,225.92L106.409,54.017c-12.354-12.359-12.354-32.394,0-44.748c12.354-12.359,32.391-12.359,44.75,0l194.287,194.284 c6.177,6.18,9.262,14.271,9.262,22.366C354.708,234.018,351.617,242.115,345.441,248.292z\"/></svg>",
        "last": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\" viewBox=\"0 0 245 245\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 245 245;\" xml:space=\"preserve\"><path class=\"st0\" d=\"M205.4,122.5l-84.2,95.2c-6.2,6.2-6.2,16.4,0,22.6s16.4,6.2,22.6,0l94-106.3c3.2-3.2,4.7-7.3,4.6-11.5 c0-4.2-1.5-8.4-4.6-11.5l-94-106.3c-6.2-6.2-16.4-6.2-22.6,0s-6.2,16.4,0,22.6L205.4,122.5z\"/><path class=\"st0\" d=\"M91.5,122.5L7.3,217.7C1,224,1,234.1,7.2,240.3c6.2,6.2,16.4,6.2,22.6,0l94-106.3c3.2-3.2,4.7-7.3,4.6-11.5c0-4.2-1.5-8.4-4.6-11.5L29.9,4.6c-6.3-6.2-16.4-6.2-22.6,0C1,10.8,1,21,7.3,27.2L91.5,122.5z\"/></svg>",
        "previous": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\"  x=\"0px\" y=\"0px\" viewBox=\"0 0 451.847 451.847\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 451.847 451.847;\" xml:space=\"preserve\"><path d=\"M97.141,225.92c0-8.095,3.091-16.192,9.259-22.366L300.689,9.27c12.359-12.359,32.397-12.359,44.751,0 c12.354,12.354,12.354,32.388,0,44.748L173.525,225.92l171.903,171.909c12.354,12.354,12.354,32.391,0,44.744 c-12.354,12.365-32.386,12.365-44.745,0l-194.29-194.281C100.226,242.115,97.141,234.018,97.141,225.92z\"/></svg>",
        "first": "<svg version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" x=\"0px\" y=\"0px\"  viewBox=\"0 0 245.019 245.019\" width=\"9\" height=\"19\" style=\"enable-background:new 0 0 245.019 245.019;\" xml:space=\"preserve\"><path d=\"M39.597,122.521l84.224-95.22c6.229-6.229,6.229-16.368,0-22.597 c-6.229-6.229-16.368-6.229-22.597,0L7.179,110.984c-3.178,3.178-4.672,7.342-4.64,11.505c-0.032,4.163,1.462,8.359,4.64,11.537 	l94.044,106.344c6.229,6.198,16.368,6.198,22.597,0c6.229-6.198,6.229-16.4,0-22.597L39.597,122.521z\"/> <path d=\"M153.569,122.521l84.16-95.22c6.325-6.261,6.325-16.4,0.064-22.629 	c-6.198-6.229-16.4-6.229-22.597,0l-94.044,106.312c-3.178,3.178-4.704,7.342-4.64,11.505c-0.032,4.163,1.462,8.359,4.64,11.537 l94.013,106.344c6.261,6.198,16.432,6.198,22.597,0c6.261-6.198,6.261-16.4,0-22.597L153.569,122.521z\"/></svg>",
      }
    },
    "dom": "<'row'<'col-sm-12 text-right'B>>" + "<'row'<'col-sm-12'tr>>" + "<'row'<'col-sm-5'i><'col-sm-7'p>>",
    buttons: [{
      extend: 'csv',
      className: 'btn btn-secondary',
      exportOptions: {
        columns: [0,1,2,3,5,6,7]
      }
    },
    {
      extend: 'excel',
      className: 'btn btn-secondary',
      exportOptions: {
        columns: [0,1,2,3,5,6,7]
      }
    }],
    "order": [[ 2, "desc" ]]
  });

  $('.estado-filter').on('change', function(){
     table.columns(7).search(this.value).draw();
  });

  $('.id-filter').on('keyup', function(){
     table.columns(0).search(this.value).draw();
  });

  $('.entidade-filter').on('change', function(){
     table.columns(1).search(this.value).draw();
  });

  $.fn.dataTable.ext.search.push(
      function( settings, data, dataIndex ) {
          var min  = $('#min').val();
          var max  = $('#max').val();
          var createdAt = data[2] || 0; // Our date column in the table

          if  (
                  ( min == "" || max == "" )
                  ||
                  ( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) )
              )
          {
              return true;
          }
          return false;
      }
  );
  $(document).on('dp.change', 'input.datetimepicker.filter', function() {
     table.draw();
  });

  $.fn.dataTable.ext.search.push(
      function( settings, data, dataIndex ) {
          var min  = $('#minval').val();
          var max  = $('#maxval').val();
          var column = data[4] || 0;
          var arr = column.split('€');
          var price = parseFloat(arr[0]);
          var priceiva = parseFloat(arr[0]) * 1.23;
          if  (
                ( min == "" && max == "" )
                ||
                ( price >= min && price <= max )
                ||
                ( min == "" && price <= max )
                ||
                ( price >= min && max == "" )
              )
          {
              return true;
          }
          return false;
      }
  );
  $(document).on('keyup', 'input.valor.filter', function() {
     table.draw();
  });


$(document).on("click", '#adicionar-linha-nota-pagamento', function() {
  var id = $(this).data('id'),
      nextid = id + 1;
      $(this).data('id',nextid);
      $.ajax({
          url: '/app/elements/functions/ajax.php',
          type: 'POST',
          data: {"ajax": "obter_descritivo_nota_pagamento", "nextid": nextid},
          cache: false,
          success: function(response){
              $('#descritivo_nota_pagamento').append(response);
              $('#div_remover-linha-nota-pagamento').removeClass('d-none');
          }
      });
      return false;
});
$(document).on("click", '#remover-linha-nota-pagamento', function() {
  var id = $('#adicionar-linha-nota-pagamento').data('id'),
      nextid = id - 1;
      $('#adicionar-linha-nota-pagamento').data('id',nextid);
      $('#descritivo_nota_pagamento .descritivo_nota_pagamento:last').remove()
      if(nextid <= 1){
        $('#div_remover-linha-nota-pagamento').addClass('d-none');
      }
      $('#descritivo_nota_pagamento').append(response);
      return false;
});

$(document).on("change", '.selecionar_produto', function() {
  var element = $(this),
  id = element.data('id'),
  produtoid = element.val();

  $('.lista_produtos_' + id).remove();

  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "nota_pagamento_mostrar_select", "id": id, "produtoid": produtoid},
      cache: false,
      success: function(response){
          element.closest('.row').append(response);
      }
  });
});

$(document).on("change", '.selecionar_produto_final', function() {
  var element = $(this),
  id = element.data('id'),
  produtoid = element.val(),
  periodicidade = $('input[name="periodicidade"]:checked').val();
  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "nota_pagamento_preencher", "produtoid": produtoid, "periodicidade": periodicidade, "tipo": "descricao"},
      cache: false,
      success: function(response){
          $('input[name="item[' + id + '][descricao]"]').val(response);
      }
  });
  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "nota_pagamento_preencher", "produtoid": produtoid, "periodicidade": periodicidade, "tipo": "preco"},
      cache: false,
      success: function(response){
          $('input[name="item[' + id + '][preco]"]').val(response);
      }
  });
});

$(document).on("click", '.eliminar_nota_pagamento', function() {
  var notapagamentoid = $(this).data('id');
  $('#delete_nota_pagamento').find('input[name="id"]').val(notapagamentoid);
  $('#delete_nota_pagamento').modal('show');
});

$(document).on("click", '#enviaremailsim', function() {
  $('#enviaremailnao').val('sim');
  $('#enviaremailnao').closest('form').submit();
});

$(document).on("click", '.fechar_nota_pagamento', function() {
  var notapagamentoid = $(this).data('id');
  $('#fechar_nota_pagamento').find('input[name="id"]').val(notapagamentoid);
  $('#fechar_nota_pagamento').modal('show');
});

$(document).on("click", '.reenviar_nota_pagamento', function() {
  var notapagamentoid = $(this).data('id');
  $("body").addClass("loading");
  $.ajax({
      url: '/app/elements/functions/actions.php',
      type: 'POST',
      data: {"acao": "reenviar_nota_pagamento", "id": notapagamentoid},
      cache: false,
      success: function(response){
        $("body").removeClass("loading");
        $('#resposta').append(response);
        setTimeout(function() {  $('#resposta').html('');}, 10000);
      }
  });
});

$(document).on("click", '.ver_nota_pagamento', function() {
  var notapagamentoid = $(this).data('id');
  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "nota_pagamento_ver", "notapagamentoid": notapagamentoid},
      cache: false,
      success: function(response){
        $('#ver_nota_pagamento .modal-content').html(response);
      }
  });
});

$(document).on("change", '.preco', function() {
  $(this).val($(this).val().replace(',', '.'));
});


$(document).on("click", '#adicionar-acoes-nota-pagamento', function() {
  var id = $(this).data('id'),
      nextidacao = id + 1;
      $(this).data('id',nextidacao);
      $.ajax({
          url: '/app/elements/functions/ajax.php',
          type: 'POST',
          data: {"ajax": "obter_acoes_nota_pagamento", "nextid": nextidacao},
          cache: false,
          success: function(response){
              $('#acoes_nota_pagamento').append(response);
              $('#div_remover-acao-nota-pagamento').removeClass('d-none');
          }
      });
      return false;
});
$(document).on("click", '#remover-acao-nota-pagamento', function() {
  var id = $('#adicionar-acoes-nota-pagamento').data('id'),
      nextidacao = id - 1;
      $('#adicionar-acoes-nota-pagamento').data('id',nextidacao);
      $('#acoes_nota_pagamento .acao_nota_pagamento:last').remove()
      if(nextidacao <= 1){
        $('#div_remover-acao-nota-pagamento').addClass('d-none');
      }
      return false;
});


$(document).on("click", '.add_nota_pagamento-btn', function() {
  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "obter_add_nota_pagamento"},
      cache: false,
      async:false,
      success: function(response){
          $('#add_nota_pagamento').html(response);
          $('#add_nota_pagamento').modal('show');
      }
  });
  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "obter_descritivo_nota_pagamento", "nextid": "1"},
      cache: false,
      success: function(response){
          $('#descritivo_nota_pagamento').append(response);
      }
  });
  return false;
});

$(document).on('change', '#add_nota_pagamento select[name="orcamento"]', function() {
  var orcid = $('#add_nota_pagamento select[name="orcamento"]  option:selected').val();
  $("body").addClass("loading");
  $.ajax({
    type: 'GET',
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "obter_descritivo_nota_pagamento_orcamento", "orcid": orcid},
    cache: true,
    success: function(response) {
      $('#add_nota_pagamento .descritivo_nota_pagamento').html(response);
      $("body").removeClass("loading");
    },error: function() {
      console.log('ERRO');
    }
  });
});


$(document).on('change', '#add_nota_pagamento select[name="entidade"]', function() {
  var select = $(this);
  var entidadeid = select.find("option:selected").val();
  $("body").addClass("loading");
  $.ajax({
    type: 'GET',
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "obter_orcamentos_nota_pagamento", "entidadeid": entidadeid},
    cache: true,
    success: function(response) {
      $("#add_nota_pagamento select[name='orcamento']").select2('destroy');
      $("#add_nota_pagamento select[name='orcamento']").find('option').remove().end().append(response).select2({
        width: '100%'
      });
      $("body").removeClass("loading");
    },error: function() {
      console.log('ERRO');
    }
  });
  $('.extrainfo').html('');
  $.ajax({
    type: 'GET',
    url: '/app/elements/functions/ajax.php',
    type: 'POST',
    data: {"ajax": "obter_taxa_entidade", "entidadeid": entidadeid},
    cache: true,
    success: function(response) {
      $('.extrainfo').html(response);
    },error: function() {
      console.log('ERRO AO OBTER TAXA');
    }
  });
});


$(document).on("click", '.info-extra-preco', function() {
  var este = $(this);
  var pai = este.closest('div.row');
  var id = pai.closest('div.descritivo_nota_pagamento').data('id');
  var entidadeid = $('select[name="entidade"]').find("option:selected").val();
  $.ajax({
      url: '/app/elements/functions/ajax.php',
      type: 'POST',
      data: {"ajax": "obter_info-extra-preco","id": id, "entidadeid": entidadeid},
      cache: false,
      success: function(response){
        pai.after(response);
        este.remove();
      }
  });
  return false;
});
