/* global jAlert */

$(function () {
  inicializarComponentes();
  configuracionComponentes();
  listarFichas().then(() => {
    validarCheckBox()
  })
  configuracionCheckBox();
  configuracionComboFiltrado();

});

let fichas = [];
let tipoLote = "";
let flagGenerarLote = false;
function listarFichas() {
  return new Promise((resolve, reject) => {
    defaultConfigDataTable();
    $('#tblFichasPendientes').DataTable().destroy()
    $('#tblFichasPendientes').DataTable({
      ajax: {
        url: '../LoteFichaServlet',
        type: 'POST',
        dataType: 'json',
        data: {
          accion: 'listarFichasDT',
          json: JSON.stringify(obtenerDataFiltro())
        }
      },
      processing: true,
      serverSide: true,
      columnDefs: [],
      iDisplayLength: 20,
      columns: [
        {
          data: null,
          render: function () {
            return '<input type="checkbox" class="control-primary checkbox-body">';
          }
        },
        {
          data: null,
          render: function (data) {
            return `${data.apellidoPaterno} ${data.apellidoMaterno}, ${data.nombre}`;
          }
        },
        {
          data: 'numeroDocumento',
          className: 'text-center'
        },
        {
          data: 'nombreSede'
        },
        {
          data: 'nombreArea'
        },
        {
          data: 'nombreCargo'
        },
        {
          data: null,
          className: 'text-center',
          render: function (data) {
            if (data.tipoFicha === 'A') {
              return `<b> S/. ${data.sueldoMensualAdministrativo} </b>`;
            } else if (data.tipoFicha === 'D') {
              return data.costoMensualDocente !== '0.00' ? `<b> S/. ${data.costoMensualDocente} </b>` : ' - ';
            }
          }
        },
        {
          data: 'costoADocente',
          className: 'text-center',
          render: function (data) {
            return data !== '0.00' ? `<b> S/. ${data} </b>` : ' - ';
          }
        },
        {
          data: 'costoBDocente',
          className: 'text-center',
          render: function (data) {
            return data !== '0.00' ? `<b> S/. ${data} </b>` : ' - ';
          }
        },
        {
          data: 'costoCDocente',
          className: 'text-center',
          render: function (data) {
            return data !== '0.00' ? `<b> S/. ${data} </b>` : ' - ';
          }
        }
      ],
      fnDrawCallback: function (settings) {
        $(".control-primary").uniform({
          radioClass: 'choice',
          wrapperClass: 'border-primary-600 text-primary-800 div-checkbox-body'
        });
        setearChecks();
        if (fichas.length !== $('#tblFichasPendientes').DataTable().page.info().recordsTotal) {
          $(".checkbox-head").prop('checked', false);
          $('.div-checkbox-head span').removeClass('checked');
        }
      },
      createdRow: function (row, data, index) {
        let tipoFicha = data.tipoFicha; // "A" ó "D"
        if (tipoFicha === "A") {
          $(row).addClass('info');
        } else if (tipoFicha === "D") {
          $(row).addClass('warning');
        }
      },
      fnInitComplete: function (settings, data) {
        resolve(data)
      }
    })
  })

}
function obtenerDataFiltro() {
  let json = {
    criterio: parseInt($('#cboCriterioFiltroFicha').val())
  };
  return json;
}
function setearChecks() {
  let tabla = $('#tblFichasPendientes').DataTable().rows().data();
  for (let i = 0; i < tabla.length; i++) {
    for (let x = 0; x < fichas.length; x++) {
      if (fichas[x].codigoFicha === obtenerDatosFila(i).codigoFicha) {
        let input = $($($('#tblFichasPendientes').DataTable().row(i).node()).children()[0]).find('input');
        input.parent().addClass('checked');
        input.prop('checked', true);
      }
    }
  }
}
let obtenerDatosFila = (fila) => $('#tblFichasPendientes').DataTable().row(fila).data();
let jsonFichas = () => {
  let json = {}
  let detalleLote = []
  for (let i in fichas) {
    detalleLote.push({codigoFicha: fichas[i].codigoFicha, tipoFicha: fichas[i].tipoFicha});
  }
}
function configuracionCheckBox() {
  $(".checkbox-head").click(function () {
    if ($(this).prop('checked')) { // le doy check
      $('.div-checkbox-body span').addClass('checked');
      $('.checkbox-body').each((i, el) => {
        if (!$(el).prop('checked')) { // no esta marcado
          let x_data = $('#tblFichasPendientes').DataTable().row(i).data();
          fichas.push(x_data);
        }
      });
    } else { // le quito check
      fichas = [];
      $('.div-checkbox-body span').removeClass('checked');
    }
    $(".checkbox-body").prop('checked', $(this).prop('checked'));
  });

  $('#tblFichasPendientes tbody').on('click', '.checkbox-body', function (e) {
    iterateCheckBox();
    let row = $('#tblFichasPendientes').DataTable().row($(this).parents('tr'));
    let data = row.data();
    let id = data.id;
    if ($(this).prop('checked')) {
      fichas.push(data);
    } else {
      removeByKey(fichas, {key: 'id', value: id});
    }
  });
}
function configuracionComboFiltrado() {
  $('#cboCriterioFiltroFicha').on('change', function (e) {
    fichas = [];
    $(".checkbox-head").prop('checked', false);
    $('.div-checkbox-head span').removeClass('checked');

    let codigoCriteroBusqueda = parseInt($('#cboCriterioFiltroFicha').val());
    if (codigoCriteroBusqueda !== 0) {
      flagGenerarLote = true;
      $('#btnGenerarLote').attr('disabled', false);
      if (codigoCriteroBusqueda === 1) {
        tipoLote = 'A';
      } else if (codigoCriteroBusqueda === 2) {
        tipoLote = 'D';
      }
      listarFichas().then(() => {
        $('.div-checkbox-head').removeClass('disabled')
        $(".checkbox-head").prop('disabled', false)
        $('.div-checkbox-body').removeClass('disabled')
        $('.checkbox-body').prop('disabled', false)
      })
    } else {
      $('#btnGenerarLote').attr('disabled', true);
      flagGenerarLote = false;
      tipoLote = '';
      listarFichas()
        .then(() => {
          validarCheckBox()
        })
    }
  });
}
let iterateCheckBox = () => {
  let count = 0;
  $('.checkbox-body:checked').each((el, i) => {
    count++;
  });
  if ($('.checkbox-body').length === count) {
    $('.div-checkbox-head span').addClass('checked');
    $('.checkbox-head').prop('checked', true);
  } else {
    $('.div-checkbox-head span').removeClass('checked');
    $('.checkbox-head').prop('checked', false);
  }
};
function configuracionComponentes() {
  $('#btnGenerarLote').attr('disabled', true);
}
function inicializarComponentes() {
  $('.bootstrap-select').selectpicker();
  // Primary
  $(".control-primary").uniform({
    radioClass: 'choice',
    wrapperClass: 'border-primary-600 text-primary-800 div-checkbox-head'
  });
}
let validarCheckBox = () => {
  $('.div-checkbox-head').addClass('disabled')
  $(".checkbox-head").prop('disabled', true)
  $('.div-checkbox-body').addClass('disabled')
  $('.checkbox-body').prop('disabled', true)
}


let lote = {
  init() {
    this.generarLote()
  },
  generarLote() {
    document.querySelector('#btnGenerarLote').addEventListener('click', (e) => {
      let valid = this.validarLote()
      if (valid.status) {
        delete valid["status"]
        let json = this.obtenerData()
        jAlert({
          type: 'confirm',
          content: 'Esta a punto de generar un lote. ¿Continuar?',
          buttons: {left: 'Si', right: 'No'}
        }).then(flag => {
          if (flag) {
            $.ajax({
              url: '../LoteFichaServlet',
              type: 'POST',
              dataType: 'json',
              data: {
                accion: 'registrarLote',
                json: JSON.stringify(json)
              }, beforeSend: function (xhr) {
                load('Generando lote')
              }, success: function (data, textStatus, jqXHR) {
                fichas = []
                if (data.status) {
                  listarFichas()
                  unload()
                  jAlert({
                    type: 'success',
                    content: `Se generó el lote <mark>${data.data.getResultedKey}</mark> correctamente`,
                    buttons: {left: 'Aceptar'}
                  })
                } else {
                  jAlert({type: 'error', content: data.message, buttons: {left: 'Aceptar'}})
                }
              }
            })
          }
        })

      } else {
        jAlert({type: 'warning', content: valid.message, buttons: {left: 'Aceptar'}})
      }
    })
  },
  validarLote() {
    if (!flagGenerarLote) {
      return {
        status: false,
        message: 'Accion maliciosa, refresque la página.'
      }
    }

    if (fichas.length === 0) {
      return {
        status: false,
        message: 'Debe seleccionar al menos una ficha.'
      }
    }

    return {
      status: true
    }
  },
  obtenerData() {
    let detalleLote = []
    for (let ficha in fichas) {
      detalleLote.push({
        codigoFicha: fichas[ficha].codigoFicha,
        tipoFicha: fichas[ficha].tipoFicha
      })
    }
    let json = {
      detallelote: detalleLote,
      tipoLote: tipoLote
    }
    return json
  }
}

lote.init()

function generarLote2() {
  $('#btnGenerarLote').on('click', function () {
    if (flagGenerarLote) {
      jAlert({
        type: 'confirm',
        content: '',
        buttons: {left: 'Si', right: 'No'}
      }).then(flag => {
        if (flag) {
          let json = {};
          let detallelote = [];
          for (let i in fichas) {
            detallelote.push({codigoFicha: fichas[i].codigoFicha, tipoFicha: fichas[i].tipoFicha});
          }
          json.detallelote = detallelote;
          json.tipoLote = tipoLote;
          if (detallelote.length !== 0) {
            $.ajax({
              url: '../LoteFichaServlet',
              type: 'POST',
              dataType: 'json',
              data: {
                accion: 'registrarLote',
                json: JSON.stringify(json)
              },
              beforeSend: function (xhr) {
              }, success: function (data, textStatus, jqXHR) {
                if (data.status) {
                  jAlert({
                    type: 'success',
                    content: `Se generó el lote <mark>${data.data.getResultedKey}</mark> correctamente</b>`,
                    buttons: {left: 'Aceptar'}
                  })
                  $('#cboCriterioFiltroFicha').val(0).change();
                  $('#cboCriterioFiltroFicha').selectpicker('refresh');
                  listarFichas();
                } else {
                  jAlert({type: 'error', content: data.message, buttons: {left: 'Aceptar'}})
                }
              }
            });
          } else {
            jAlert({type: 'warning', content: 'Debe seleccionar al menos una ficha.', buttons: {left: 'Aceptar'}})
          }
        }
      })
    } else {
      jAlert({type: 'error', content: 'Acción maliciosa, refresque la página!', buttons: {left: 'Aceptar'}})
        .then(flag => {
          if (flag) {
            window.location.reload()
          }
        })
    }
  });
}