"use strict";

var _utilidades = require("../../utilidades.js");
// 
var tabla = {
  contenedor: null,
  elemento: null,
  impresion: {
    cabecera: "\n      <div class=\"row\">\n        <div\n          class=\"\n            col-12\n            col-sm-12\n            col-md-12\n            col-lg-12\n            col-xl-12\n            col-xxl-12\n          \"\n          style=\"\n            border: 1px solid var(--colorPrimario);\n            border-top: 15px solid var(--colorPrimario);\n            border-radius: 5px;\n            padding: 5px\n          \"\n        >\n          <div class=\"row\">\n\n            <div\n              class=\"\n                col-8\n                col-sm-8\n                col-md-8\n                col-lg-8\n                col-xl-8\n                col-xxl-8\n              \"\n              style=\"\n                border-right: 1px solid var(--colorPrimario);\n                align-self: center;\n                padding: 5px\n              \"\n            >\n\n              <img\n                src=\"\n                  http://daite.com.do/logos/{carpeta}/logotipo.png\n                \"\n                alt=\"{empresa}\"\n                style=\"\n                  width: auto;\n                  height: 34px;\n                  margin: 5px 0\n                \"\n              />\n\n              <p>\n                {empresa}\n\n                <br />\n\n                {ubicacion}\n\n                <br />\n\n                Tel\xE9fono: {telefono}\n\n                <br />\n\n                RNC: {rnc}\n              </p>\n\n            </div>\n\n            <div\n              class=\"\n                col-4\n                col-sm-4\n                col-md-4\n                col-lg-4\n                col-xl-4\n                col-xxl-4\n              \"\n              style=\"\n                align-self: center;\n                padding: 5px\n              \"\n            >\n              <div class=\"row\">\n\n                <div\n                  class=\"\n                    col-6\n                    col-sm-6\n                    col-md-6\n                    col-lg-6\n                    col-xl-6\n                    col-xxl-6\n                  \"\n                >\n\n                  <p>\n                    Fecha:\n\n                    <br />\n\n                    Hora:\n\n                    <br />\n\n                    P\xE1gina:\n\n                    <br />\n\n                    Usuario:\n                  </p>\n\n                </div>\n\n                <div\n                  class=\"\n                    col-6\n                    col-sm-6\n                    col-md-6\n                    col-lg-6\n                    col-xl-6\n                    col-xxl-6\n                  \"\n                >\n\n                  <p class=\"text-end\">\n                    <span class=\"fecha\"></span>\n\n                    <br />\n\n                    <span class=\"hora\"></span>\n\n                    <br />\n\n                    <span class=\"pagina\"></span>/<span class=\"paginas\"></span>\n\n                    <br />\n\n                    {usuario}\n                  </p>\n\n                </div>\n\n              </div>\n            </div>\n\n          </div>\n        </div>\n      </div>\n    "
  }
};
$.extend(true, $.fn.dataTable.defaults, {
  // !
  order: [],
  ordering: true,
  // orderMulti: true,
  pageLength: 500,
  scrollY: '45vh',
  scrollCollapse: true,
  deferRender: true,
  // ! 
  language: {
    sProcessing: "Procesando...",
    sLengthMenu: "Mostrar _MENU_ registros",
    sZeroRecords: "",
    sEmptyTable: "",
    sInfo: "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
    sInfoEmpty: "Mostrando registros del 0 al 0 de un total de 0 registros",
    sInfoFiltered: "(filtrado de un total de _MAX_ registros)",
    sSearch: "",
    sInfoThousands: ",",
    sLoadingRecords: "Cargando...",
    oPaginate: {
      sFirst: "Primero",
      sLast: "Último",
      sPrevious: '<i class="fa-solid fa-arrow-left"></i>',
      sNext: '<i class="fa-solid fa-arrow-right"></i>'
    },
    oAria: {
      sSortAscending: ": Activar para ordenar la columna de manera ascendente",
      sSortDescending: ": Activar para ordenar la columna de manera descendente"
    },
    buttons: {
      "copy": "Copiar",
      "colvis": "Visibilidad"
    }
  },
  // !
  columnDefs: [{
    targets: '_all',
    render: function render(datoCelda, tipoRenderizado, datosFila) {
      if (tipoRenderizado === 'display') {
        /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}.\d{3}$/.test(datoCelda) && (datoCelda = new Date(datoCelda).toLocaleDateString('uk').replaceAll('.', '/'));
      }
      return datoCelda;
    }
  }],
  dom: "\n      <'row justify-content-between align-items-center'<'col-auto'B><'col-auto'f>>\n      <'row'<'col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12't>>\n      <'row'<'col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12'p>>\n    ",
  buttons: [
  // {
  //     extend: 'colvis',
  //     className: 'btn btn-primary buttons-colvis',
  //     text: 'Columnas <i class="fa-solid fa-eye"></i>'
  // },
  {
    extend: 'print',
    className: 'btn buttons-print',
    text: 'Imprimir <i class="fa-solid fa-print px-1"></i>',
    title: '',
    footer: true,
    messageTop: tabla.impresion.cabecera.replace('{carpeta}', 'daite').replaceAll('{empresa}', 'DAITE S.R.L').replace('{ubicacion}', 'AV. HISPANOAMERICANA, MÓDULO 302, SANTIAGO, REPÚBLICA DOMINICANA').replace('{telefono}', '+1 (829) 971-3264').replace('{rnc}', '130-08660-5').replace('{usuario}', 'NULL'),
    exportOptions: {
      page: 'current',
      columns: ':visible'
    },
    customize: function customize(ventanaEmergente) {
      // 
      var documento = ventanaEmergente.document,
        calendario = new Date().toLocaleString("es-419", {
          hour12: true,
          day: '2-digit',
          month: '2-digit',
          year: 'numeric',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        }).split(', '),
        fecha = calendario[0],
        hora = calendario[1];
      $(documento).find('h1').remove();
      $(documento.body).find('.fecha').text(fecha);
      $(documento.body).find('.hora').text(hora);
      $(documento.body).find('.pagina').text('00');
      $(documento.body).find('.paginas').text('00');
      $(documento).find('thead').prepend("\n\n                <tr>\n                  <th colspan=\"100%\">\n                    <p class=\"title text-center\">\n                      ".concat(document.title, "\n                    </p>\n                  </th>\n                </tr>\n\n              "));
    }
  },
  // {
  //   extend: 'pdfHtml5',
  //   className: 'btn buttons-pdf',
  //   text: 'PDF <i class="fa-regular fa-file-pdf px-1"></i>',
  //   orientation: 'portrait',
  //   pageSize: 'A4',
  //   footer: true,
  //   exportOptions: {
  //     page: 'current',
  //     columns: ':visible'
  //   },
  //   customize: function(documento) {

  //     // 
  //     var
  //       tablaDatos = {
  //         columnas: tabla.elemento.DataTable().settings().init().columns
  //       },
  //       PDF = {
  //         columnas: documento.content[1].table.body
  //       };

  //     PDF.columnas.forEach(function(columna, indice1) {

  //       columna.forEach(function(celda, indice2) {

  //         celda.alignment = tablaDatos.columnas[indice2].className.match(/\b(left|center|right)\b/g)[0]

  //       })

  //     });

  //     documento.pageMargins = [15, 15, 15, 15];

  //     documento.header = {
  //       margin: [15, 0, 0, 15],
  //       columns: [{
  //         text: 'Daite', style: 'logo'
  //       }, {
  //         text: 'Daite', style: 'title'
  //       }, {
  //         text: 'Fecha: ', style: 'date'
  //       }, {
  //         text: 'Usuario: ', style: 'username'
  //       }]
  //     }

  //     documento.content[0].margin = [0, 0, 0, 0];

  //     documento.content[1].table.widths = Array(documento.content[1].table.body[0].length + 1).join('*').split('');

  //     documento.defaultStyle.fontSize = 6;

  //     documento.styles.tableHeader.fontSize = 8;
  //     documento.styles.tableHeader.fillColor = '#005cac';
  //     documento.styles.tableFooter.fontSize = 8;
  //     documento.styles.tableFooter.fillColor = '#005cac';

  //     documento.styles.tableBodyOdd.fillColor = '#e5eef7';

  //   }
  // },
  {
    extend: 'excelHtml5',
    className: 'btn buttons-excel',
    text: 'EXCEL <i class="fa-regular fa-file-excel px-1"></i>',
    footer: true,
    exportOptions: {
      page: 'current',
      columns: ':visible'
    }
  }],
  initComplete: function initComplete() {
    $('.dataTables_wrapper').has(this).find('.contenedorCampoConsulta').append("\n          <form id=\"formularioVentanaDialogoConsulta\">\n            <div class=\"input-group \">\n\n              <div class=\"form-floating \">\n\n                <input\n                  type=\"text\"\n                  class=\"form-control\"\n                  id=\"campoConsulta\"\n                  name=\"campoConsulta\"\n                  value=\"\"\n                >\n\n                <label for=\"campoConsulta\">\n                  Buscar\n                </label>\n\n              </div>\n\n              <button\n                type=\"submit\"\n                class=\"btn btn-primary\"\n                id=\"botonBuscarConsulta\"\n                tabindex=\"-1\"\n              >\n                <i class=\"fa-solid fa-magnifying-glass\"></i>\n              </button>\n\n            </div>\n          </form>\n        ");
    $('.dataTables_wrapper').has(this).find('.dataTables_filter').parent().append("\n          <div class=\"form-floating\">\n\n            <label>\n              Buscar Actual\n            </label>\n\n          </div>\n        ");
    $('.dataTables_wrapper').has(this).find('.dataTables_filter ~ .form-floating').prepend($('.dataTables_filter input'));
    $('.dataTables_filter').remove();
    tabla.elemento = this;
    tabla.elemento.parent().parent().find('.dataTables_scrollHead th:not(.d-none)').first().css('border-top-left-radius', '5px');
    tabla.elemento.parent().parent().find('.dataTables_scrollHead th:not(.d-none)').last().css('border-top-right-radius', '5px');
    tabla.elemento.parent().parent().find('.dataTables_scrollFoot th:not(.d-none)').first().css('border-bottom-left-radius', '5px');
    tabla.elemento.parent().parent().find('.dataTables_scrollFoot th:not(.d-none)').last().css('border-bottom-right-radius', '5px');

    // 
    $('.dt-buttons').removeClass('flex-wrap');
    $('#campoConsulta').focus();
  },
  drawCallback: function drawCallback() {
    // 
    var api = this.api(),
      columnas = this.DataTable().settings().init().columns;

    // $(api.column(0, { page: 'current' }).footer())
    //   .html(api.rows({ page: 'current' }).count());

    !!columnas && columnas.forEach(function (columna, indice) {
      var _columna$className, _columna$className2;
      if ((_columna$className = columna.className) !== null && _columna$className !== void 0 && _columna$className.match(/\b(sumar)\b/g)) {
        var columnaActual = api.column(indice, {
          page: 'current'
        });
        var sumaCeldasColumnaActual = columnaActual.data().sumar();
        $(columnaActual.footer()).html((0, _utilidades.formatoNumerico)(sumaCeldasColumnaActual, 2));
      } else if ((_columna$className2 = columna.className) !== null && _columna$className2 !== void 0 && _columna$className2.match(/\b(agrupar)\b/g)) {
        $(tablaRegistros).DataTable().order([[indice, 'asc']]);
        $(tablaRegistros).DataTable().rowGroup().enable().dataSrc(columna.data);
      }
    });
  }
});
$.fn.dataTable.Api.register('sumar()', function () {
  return this.flatten().reduce(function () {
    var valorSumado = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
    var valor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
    typeof valorSumado === 'string' && (valorSumado = valorSumado.replace(',', '') * 1);
    typeof valor === 'string' && (valor = valor.replace(',', '') * 1);
    return valorSumado + valor;
  }, 0);
});