/**
 * DataTables Advanced
 */

'use strict';

var rangePickr = $('#dtsolic');
if (rangePickr.length) {
  rangePickr.flatpickr({
    mode: 'range',
    dateFormat: 'd/m/Y',
    onClose: function (selectedDates, dateStr, instance) {
      var startDate = new Date();
      var endDate = new Date();
      if (selectedDates[0] != undefined) {
        startDate = ('0'+(selectedDates[0].getDate())).slice(-2)+'/'+(('0'+(selectedDates[0].getMonth()+1)).slice(-2))+'/'+selectedDates[0].getFullYear();
        $('#dninicial').val(startDate);
      }
      if (selectedDates[1] != undefined) {
        endDate = ('0'+(selectedDates[1].getDate())).slice(-2)+'/'+(('0'+(selectedDates[1].getMonth()+1)).slice(-2))+'/'+selectedDates[1].getFullYear();
        $('#dnfinal').val(endDate);
      }
      $(rangePickr).trigger('change').trigger('keyup');
    }
  });
}

var normalizeDate = function (dateString) {
  var normalized = null;
  if (dateString.length == 10){
    if (dateString.includes("/")) {
      const dtArr = dateString.split("/");
      normalized = parseInt(dtArr[2]+dtArr[1]+dtArr[0]);
    }
  } else {
    if (dateString.length > 10){
        if (dateString.includes("-")){
            var nDateString = dateString.replace(/ /gi, "-");
            const dtArr = nDateString.split("-");
            normalized = parseInt(dtArr[0]+dtArr[1]+dtArr[2]);
        }
        if (dateString.includes("/")){
            var nDateString = dateString.replace(/ /gi, "/");
            const dtArr = nDateString.split("/");
            normalized = parseInt(dtArr[2]+dtArr[1]+dtArr[0]);
        }
    }
  }
  return normalized;
};

$.fn.dataTable.ext.search.push(
  function(settings, data, dataIndex) {
      var min = normalizeDate($('#dninicial').val() + '');
      var max = normalizeDate($('#dnfinal').val() + '');
      var date = normalizeDate(data[2] + '');
      if (
          ( min === null && max === null) ||
          ( min === null && date <= max ) ||
          ( min <= date  && max === null) ||
          ( min <= date  && date <= max )
      ) {
          return true;
      }
      return false;
  }
);

$(function () {
  var isRtl = $('html').attr('data-textdirection') === 'rtl';
  var countRowValid = 0;
  var dt_adv_filter_table = $('.dt-advanced-search');
  if (dt_adv_filter_table.length) {
    var dt_adv_filter = dt_adv_filter_table.DataTable({
      ajax: 'mod/bpa/monitor_json.php',
      dom: '<"d-flex justify-content-between align-items-center mx-0 row"<"col-sm-12 col-md-4"l><"col-sm-12 col-md-4"B><"col-sm-12 col-md-4"f>>t<"d-flex justify-content-between mx-0 row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
      buttons: [

        {
          extend: 'collection',
          className: 'btn btn-outline-secondary dropdown-toggle me-2',
          text: feather.icons['share'].toSvg({ class: 'font-small-4 me-50' }) + 'Exportar',
          buttons: [
            {
              extend: 'print',
              text: feather.icons['printer'].toSvg({ class: 'font-small-4 me-50' }) + 'Imprimir',
              className: 'dropdown-item',
              exportOptions: { columns: [0,1,2,3,4] }
            },
            {
              extend: 'csv',
              text: feather.icons['file-text'].toSvg({ class: 'font-small-4 me-50' }) + 'Csv',
              className: 'dropdown-item',
              fieldBoundary: '',
              fieldSeparator: ';',
              exportOptions: { columns: [0,1,2,3,4] }
            },
            {
              extend: 'excel',
              text: feather.icons['file'].toSvg({ class: 'font-small-4 me-50' }) + 'Excel',
              className: 'dropdown-item',
              exportOptions: { columns: [0,1,2,3,4] }
            },
            {
              extend: 'pdf',
              text: feather.icons['clipboard'].toSvg({ class: 'font-small-4 me-50' }) + 'Pdf',
              className: 'dropdown-item',
              exportOptions: { columns: [0,1,2,3,4] },
              pageSize: 'A1',
              orientation: 'landscape',
              customize: function ( doc ) {
                var cols = [];
                cols[0] = {text: 'Indicadores', alignment: 'left', margin:[20] };
                cols[1] = {text: 'v6', alignment: 'right', margin:[0,0,20] };
                var objFooter = {};
                objFooter['columns'] = cols;
                doc['footer']=objFooter;
                doc['header']={text: 'SC+SUS', alignment: 'left', margin:[20,10] };
                doc.pageMargins = [50,50,50,50];
              }
            },
            {
              extend: 'copy',
              text: feather.icons['copy'].toSvg({ class: 'font-small-4 me-50' }) + 'Copiar',
              className: 'dropdown-item',
              exportOptions: { columns: [0,1,2,3,4] }
            }
          ],
          init: function (api, node, config) {
            $(node).removeClass('btn-secondary');
            $(node).parent().removeClass('btn-group');
            setTimeout(function () {
              $(node).closest('.dt-buttons').removeClass('btn-group').addClass('d-inline-flex');
            }, 50);
          }
        }

      ],

      responsive: {
        details: {
          display: $.fn.dataTable.Responsive.display.modal({
            header: function (row) {
              var data = row.data();
              return 'Detalhes de ' + data['solic_protocolo'];
            }
          }),
          type: 'column',
          renderer: function (api, rowIdx, columns) {
            var data = $.map(columns, function (col, i) {
              return col.title !== '' // ? Do not show row in modal popup if title is blank (for check box)
                ? '<tr data-dt-row="' +
                    col.rowIdx +
                    '" data-dt-column="' +
                    col.columnIndex +
                    '">' +
                    '<td>' +
                    col.title +
                    ':' +
                    '</td> ' +
                    '<td>' +
                    col.data +
                    '</td>' +
                    '</tr>'
                : '';
            }).join('');
            return data ? $('<table class="table"/>').append('<tbody>' + data + '</tbody>') : false;
          }
        }
      },
      /*
      responsive: true,
      processing: true,
      serverSide: true,
      */
      order: [[19, 'desc']],
      displayLength: 7,
      lengthMenu: [7, 10, 25, 50, 75, 100],
	    lengthChange: true, 
      orderCellsTop: true,
	    autoWidth: false,
      language: {
        lengthMenu: "Mostrando _MENU_ registros por página",
        zeroRecords: "Nenhum encontrado - Desculpe",
        info: "Mostrando página _PAGE_ de _PAGES_",
        infoEmpty: "Nenhum registro encontrado",
        infoFiltered: "(filtrando por _MAX_ de um total de registros)",
        search: "Busca",
        decimal: ",",
        thousands: ".",
        paginate: {
          previous: '&nbsp;',
          next: '&nbsp;'
        }
      },

      columnDefs: [
        {
          targets: 0,
          render: function (data, type, full, meta) {
            var nData = '';
            if (full[4] == 'N'){
              nData = "<input class=\"form-check-input\" type=\"checkbox\" name=\"solid[" + full[21] + "]\" id=\"solid[" + full[21] + "]\" value=\"" + data + "\" />";
            }
            return nData;
          } 
        },
        {
          targets: 1,
          render: function (data, type, full, meta) {
            var nData = data.substr(6,2)+'/'+data.substr(4,2)+'/'+data.substr(0,4);
            return nData;
          } 
        },   
        {
          targets: 2,
          render: function (data, type, full, meta) {
            var nData = data.substr(8,2)+'/'+data.substr(5,2)+'/'+data.substr(0,4)+' '+data.substr(11,8);
            return nData;
          } 
        },
        {
          targets: 3,
          render: function (data, type, full, meta) {
            var nData = data;
            return nData;
          } 
        },
        {
          targets: 4,
          visible: false
        },
        {
          targets: 5,
          render: function (data, type, full, meta) {
            var nData = data;
            return nData;
          }
        },
        {
          targets: 6,
          visible: true
        },
        {
          targets: 7,
          visible: true
        },
        {
          targets: 8,
          visible: true
        },
        {
          targets: 9,
          visible: false
        },
        {
          targets: 10,
          visible: false
        },
        {
          targets: 11,
          visible: true
        },
        {
          targets: 12,
          visible: true
        },
        {
          targets: 13,
          orderable: false,
          render: function (data, type, full, meta) {
              var op1 = '';
              var op2 = '';
              if (full[4] == 'N'){
                op1 = '&nbsp;<a href="#" class="item-edit" onclick="opModal(\'#myModal\',\'mod/bpa/exc.php?id=' + full[0] + '\');"><i class=\"fa fa-times-circle font-small-4 text-danger\"></i></a>';
              }
              op2 = '&nbsp;<a href="#" class="item-edit" onclick="opModal(\'#myModal\',\'mod/bpa/infop.php?id=' + full[0] + '\');"><i class=\"fa fa-info-circle font-small-4 text-primary\"></i></a>';
              var nData = '<a href="http://sigtap.datasus.gov.br/tabela-unificada/app/sec/procedimento/exibir/' + full[12] + '/' + full[3].substr(4,2) + '/' + full[3].substr(0,4) + '" class="item-edit" target="_blank">' + feather.icons['search'].toSvg({ class: 'font-small-4' }) + '</a> ' + op1 + op2;
              return nData;
          }
        },
        {
          targets: 14,
          visible: true
        },
        {
          targets: 15,
          visible: true
        },
        {
          targets: 16,
          visible: false
        },
        {
          targets: 17,
          visible: false
        },
        {
          targets: 18,
          visible: false
        },
        {
          targets: 19,
          visible: false
        },
        {
          targets: 20,
          visible: false
        },
        {
          targets: 21,
          searchable: false,
          orderable: false,
          render: function (data, type, full, meta) {
            var linha = '';
            if (full[4] == "N") {
              linha = countRowValid;
              countRowValid = countRowValid + 1;
            }
            return linha;
          },
          visible: false
        }
      ],
      createdRow: function(row, data, dataIndex) {
        if (data[4] == "S") {
          $(row).addClass('ind-cinza');
        }
        if (data[4] == "X") {
          $(row).addClass('ind-vermelho');
        }
      }
    });

    $('#nome').on('keyup', function () {
      dt_adv_filter.columns(9).search(this.value).draw();
    });
    $('#cnsc').on('keyup', function () {
      dt_adv_filter.columns(9).search(this.value).draw();
    });
    $('#cnsp').on('keyup', function () {
      dt_adv_filter.columns(5).search(this.value).draw();
    });
    $('#bpac').on('change', function () {
      dt_adv_filter.columns(16).search($(this).find(":selected").val()).draw();
    });
    $('#bpai').on('change', function () {
      dt_adv_filter.columns(17).search($(this).find(":selected").val()).draw();
    });
    $('#dtsolic').on('keyup', function () {
      dt_adv_filter.draw();
    });
  }

/*
  // on key up from input field
  $('input.dt-input').on('keyup', function () {
    filterColumn($(this).attr('data-column'), $(this).val());
  });
*/

  // Filter form control to default size for all tables
  $('.dataTables_filter .form-control').removeClass('form-control-sm');
  $('.dataTables_length .form-select').removeClass('form-select-sm').removeClass('form-control-sm');












});


