let ClientsManagement = {
	clients: [],

	resetData() {
		let self = this;

		self.clients = [];
	},

	setEvents() {
		let self = this;

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC2242);

		self.resetData();
		self.loadLang();
		self.loadClientsData();

		// Exportar tabla
		$('#exportTablas').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});
	},

	loadLang() {
		pf.rsc.translateByTag('text');
	},

	loadClientsData() {
		let self = this;

		ajaxComunCallWithCallback('getAllCustomers', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.clients = ajaxReturn.result;

				// Tablas de resultados
				self.renderData();
			}
		});
	},

	renderData() {
		let self = this;

		$('#resultTable').show();

		let table = stcmbackend.gestionclientes.generateHeadersTableGestionClientes();

		for(let i = 0; i < self.clients.length; i++) {
			table += stcmbackend.gestionclientes.renderClient(self.clients[i]);
		}

		table += `
			</tbody>
		`;

		$('#registers').html(table);
		// Setup - add a text input to each footer cell
		$('#registers .filtersResult td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

			if(title == 'enabled' || title == 'registro') {
				value = optionsSelectAllYesNo();
			} else if(title == 'edit' || title == 'delete' || title == 'icono') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

			$(this).html(value);
		});

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '30px', orderable: false, targets: 0},
				{width: '30px', targets: 1},
				{width: '100px', targets: 4}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2242,
				className: 'd-none',
				title: pf.const.language.RSC2242,
				exportOptions: {
					columns: [1, 2, 3, 4]
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

		// Ocultar botones de tabla
		hideTableButtons('registers');

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		// Exportar tabla
		$('#export').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});

		self.tableEvents();

		$('#resultTable').on('draw.dt', function() {
			self.tableEvents();
		});
	},

	tableEvents() {
		// Editar Lista Clientes
		$('.edit').off().on('click', function() {
			let idClient = $(this).parent().data('id').toString();
			let client = ClientsManagement.clients.find(o => o.id === idClient);

			sessionStorage.setItem('idClient', JSON.stringify(client));
			window.location.href = '#!clientes_edit';
		});
	}
};