let PagosImportarController = {
	importPayments: null,
	payments: null,
	noPayments: [],
	pendingValidation: [],
	processedPayments: [],
	SYSNotifUser: '',
	tablePending: null,
	stampsToPay: [],
	stampsPending: [],
	valuesToSend: [],
	tempFileName: '',

	setEvents() {
		let self = PagosImportarController;

		// Reset valores
		self.importPayments = null;
		self.payments = null;
		self.noPayments = [];
		self.pendingValidation = [];
		self.processedPayments = [];
		self.SYSNotifUser = '';
		self.tablePending = null;
		self.stampsToPay = [];
		self.stampsPending = [];
		self.valuesToSend = [];
		self.tempFileName = '';

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

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

		// Opciones de header
		let jsonsubopt = {
			import: 'importLayout',
			save: 'btn-save'
		};

		let nav = `
			<div class="row mx-0">
				${createSubOptionImport(jsonsubopt.import)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		// Botón principal
		$('#btn-save').addClass('main-button');

		// Botones secundarios
		$('#importLayout').addClass('secondary-button');

		self.loadLanguage();

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.SYSNotifUser = config.SYSNotifUser.trim();

		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();
	},

	applyEvents() {
		let self = PagosImportarController;

		// Exportar excel
		$('#exportLayout').click(function() {
			window.location = stcm.const.downloads + 'payments.xls';
		})

		// Importar excel
		$('#importLayout').click(function() {
			$('#inputFile').trigger('click');
		})

		// Detectar fichero subido
		$('#inputFile').change(function(evt) {
			self.uploadFile(evt);
		});

		// Guardar usuarios
		$('#btn-save').click(function() {
			self.stampsToPay = self.payments.getStampsToPay();
			if(self.tablePending != null) {
				self.stampsPending = self.getStampsPending();
			}

			self.valuesToSend = [];

			// Pagos aceptados
			let sizePay = self.payments.data.length;
			for(let i = 0; i < sizePay; i ++) {
				if(self.stampsToPay.indexOf(self.payments.data[i].stamp.toString()) != -1) {
					self.payments.data[i]['differentValue'] = 0;
					self.valuesToSend.push(self.payments.data[i]);
				}
			}

			// Pagos con diferente valor aceptados
			let sizePen = self.pendingValidation.length;
			for(let i = 0; i < sizePen; i ++) {
				if(self.stampsPending.indexOf(self.pendingValidation[i].stamp.toString()) != -1) {
					self.pendingValidation[i]['differentValue'] = 1;
					self.valuesToSend.push(self.pendingValidation[i]);
				}
			}

			// Comprobación de pagos pendientes aceptados
			if(self.stampsPending.length != self.pendingValidation.length) {
				let objInfo = {
					accept: {
						text: pf.const.language.RSC141
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC16;
				let alertText = pf.const.language.RSC1534;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.savePayments();
				}, function() {});
			} else {
				self.savePayments();
			}
		});

		// Notificar usuarios de Pagos sin realizar
		$('#notify').off().on('click', function() {
			self.sendNoPayments();
		});
	},

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

	uploadFile(evt) {
		let self = PagosImportarController;

		let currentURL = window.location.href;

		addLoader();
		// Convertir excel a JSON
		var selectedFile = evt.target.files[0];

		var reader = new FileReader();
		reader.onload = function(event) {
			var data = event.target.result;
			var workbook = XLSX.read(data, {
				type: 'binary'
			});
			workbook.SheetNames.forEach(function(sheetName) {
				self.importPayments = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
				// Comprobar el formato de los datos importados
				if(
					(self.importPayments[0][pf.const.language.RSC68] === undefined ||
					self.importPayments[0][pf.const.language.RSC123] === undefined ||
					self.importPayments[0][pf.const.language.RSC308] === undefined ||
					self.importPayments[0][pf.const.language.RSC348] === undefined ||
					self.importPayments[0][pf.const.language.RSC178] === undefined ||
					self.importPayments[0][pf.const.language.RSC349] === undefined ||
					self.importPayments[0][pf.const.language.RSC165] === undefined ||
					self.importPayments[0][pf.const.language.RSC609] === undefined ||
					self.importPayments[0][pf.const.language.RSC610] === undefined ||
					self.importPayments[0][pf.const.language.RSC350] == undefined) &&
					currentURL.indexOf('yastas') == -1
				) {
					let alertTitle = pf.const.language.RSC4;
					let alertText = pf.const.language.RSC322;
					pf.utils.showInfoDialog(alertTitle, alertText);
				} else {
					self.uploadImportPaymentsNoProcessed(selectedFile);
					self.printTable();
				}
				removeLoader();
				$('#inputFile').val('');
			});
		};

		/* reader.onerror = function(event) {
			console.error('File could not be read! Code ' + event.target.error.code);
		}; */

		reader.readAsBinaryString(selectedFile);
	},

	printTable() {
		let self = PagosImportarController;

		let currentURL = window.location.href;

		self.noPayments = [];
		// Transformar objeto a formato de pagos
		let payments = [];
		if(currentURL.indexOf('yastas') != -1) {
			for(let i = 0; i < self.importPayments.length; i++) {
				// En caso de que una de los registros no tenga el 'stamp' definido se salta
				if(self.importPayments[i][pf.const.language.RSC1315] == undefined) {
					continue;
				}

				var payment = {
					stamp: self.importPayments[i][pf.const.language.RSC1315],
					user: self.importPayments[i][pf.const.language.RSC68],
					perfil: self.importPayments[i][pf.const.language.RSC134],
					name: self.importPayments[i][pf.const.language.RSC123],
					sid: self.importPayments[i][pf.const.language.RSC348],
					concepto: self.importPayments[i][pf.const.language.RSC178],
					valor: self.importPayments[i][pf.const.language.RSC349],
					fecha: self.importPayments[i][pf.const.language.RSC165],
					cobrado: self.importPayments[i][pf.const.language.RSC350],
					countrydesc: self.importPayments[i][pf.const.language.RSC550],
					yastas_id_cmr: self.importPayments[i]['CMR'],
					yastas_id_cob: self.importPayments[i]['COB'],
					yastas_id_sahuayo: self.importPayments[i]['SAHUAYO'],
					yastas_nombre_comercio: self.importPayments[i]['Comercio'],
					yastas_nombre_comisionista: self.importPayments[i]['Comisionista'],
					comentario: self.importPayments[i][pf.const.language.RSC1240]
				};

				if(payment.cobrado == 1) {
					payments.push(payment);
				} else {
					self.noPayments.push(payment);
				}
			}
		} else {
			for(let i = 0; i < self.importPayments.length; i++) {
				// En caso de que una de los registros no tenga el 'stamp' definido se salta
				if(self.importPayments[i][pf.const.language.RSC1315] == undefined) {
					continue;
				}

				var payment = {
					stamp: self.importPayments[i][pf.const.language.RSC1315],
					user: self.importPayments[i][pf.const.language.RSC68],
					perfil: self.importPayments[i][pf.const.language.RSC134],
					name: self.importPayments[i][pf.const.language.RSC123],
					clabeInterbancaria: self.importPayments[i][pf.const.language.RSC308],
					sid: self.importPayments[i][pf.const.language.RSC348],
					concepto: self.importPayments[i][pf.const.language.RSC178],
					valor: self.importPayments[i][pf.const.language.RSC349],
					fecha: self.importPayments[i][pf.const.language.RSC165],
					cobrado: self.importPayments[i][pf.const.language.RSC350],
					countrydesc: self.importPayments[i][pf.const.language.RSC550],
					tipoIdentificacion: self.importPayments[i][pf.const.language.RSC609],
					userIdentificador: self.importPayments[i][pf.const.language.RSC610],
					comentario: self.importPayments[i][pf.const.language.RSC1240]
				};

				if(payment.cobrado == 1) {
					payments.push(payment);
				} else {
					self.noPayments.push(payment);
				}
			}
		}

		self.validatePagosRealizados(payments);
	},

	savePayments() {
		let self = PagosImportarController;

		// Array con no pagados con comentarios
		let noPaymentsComments = [];
		let size = self.noPayments.length;
		for(let i = 0; i < size; i++) {
			if(self.noPayments[i].comentario !== undefined) {
				let userStamp = self.noPayments[i].user.trim() + '#' + self.noPayments[i].stamp;
				noPaymentsComments.push(userStamp);
			}
		}

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;

		if(self.valuesToSend.length == 0 && noPaymentsComments.length == 0) {
			let errorTitle = pf.const.language.RSC16;
			let errorContent = pf.const.language.RSC2315;
			pf.utils.showInfoDialog(errorTitle, errorContent);

			return false;
		}

		let parameters = {
			payments: JSON.stringify(self.valuesToSend),
			userMail: userMail,
			tempFileName: self.tempFileName,
			noPaymentsComments: noPaymentsComments
		};
		ajaxComunCallWithCallback('setPagosRealizados', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC16;
				let errorContent = pf.const.language.RSC497;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				$('#containerImport').addClass('d-none');
				$('#resultTable').html('');
				$('#cointarnePending').addClass('d-none');
				$('#pendingTable').html('');
			}
		});
	},

	renderNoPayments() {
		let self = this;

		let table = `
			<table id="tableNoPaymenyts" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC134}">${pf.const.language.RSC134}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC348}">${pf.const.language.RSC348}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
						<th scope="col" title="${pf.const.language.RSC1240}">${pf.const.language.RSC1240}</th>
					</tr>
				</thead>

				<thead class="filtersNoPaymenyts">
					<tr>
						<td>user</td>
						<td>perfil</td>
						<td>nombre</td>
						<td>concepto</td>
						<td>conceptoDesc</td>
						<td>valor</td>
						<td>Pais</td>
						<td>fecha</td>
						<td>Comentarios</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.noPayments.length;
		for(let i = 0; i < size; i++) {
			let date = self.noPayments[i].fecha.split(' ');
			let startDate = date[0];

			table += `
				<tr data-id="${i}">
					<td class="text-truncate" title="${self.noPayments[i].user}">${(self.noPayments[i].user != '' ? self.noPayments[i].user : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].perfil}">${(self.noPayments[i].perfil != '' ? self.noPayments[i].perfil : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].name}">${(self.noPayments[i].name != '' ? self.noPayments[i].name : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].sid}">${(self.noPayments[i].sid != '' ? self.noPayments[i].sid : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].concepto}">${(self.noPayments[i].concepto != '' ? self.noPayments[i].concepto : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].valor}">${(self.noPayments[i].valor != '' ? self.noPayments[i].valor : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].countrydesc}">${((self.noPayments[i].countrydesc != '' && self.noPayments[i].countrydesc) ? self.noPayments[i].countrydesc : '-')}</td>
					<td class="text-truncate" title="${startDate}">${(startDate != '' ? startDate : '-')}</td>
					<td class="text-truncate" title="${self.noPayments[i].comentario}">${(self.noPayments[i].comentario != '' && self.noPayments[i].comentario != undefined ? self.noPayments[i].comentario : '-')}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

		$('#noPaymentsTable').html(table);

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

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

		let tableNoPaymenyts = $('#tableNoPaymenyts').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false
		});

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

		// Apply the search
		applyTheSearch(tableNoPaymenyts, 'filtersNoPaymenyts');
	},

	sendNoPayments() {
		let self = this;

		// Comprobar si hay emisor
		if(self.SYSNotifUser == '') {
			let warningTitle = pf.const.language.RSC11;
			let warningContent = pf.const.language.RSC1245;
			pf.utils.showInfoDialog(warningTitle, warningContent);
			return;
		}

		// Comprobación de usuarios sin comentarios
		let comments = true;
		// Objeto de usuarios por comentario
		let usersComments = {};
		let size = self.noPayments.length;
		for(let i = 0; i < size; i++) {
			let objectKeys = Object.keys(usersComments);
			if(self.noPayments[i].comentario == undefined || self.noPayments[i].comentario.trim() == '') {
				comments = false;
				continue;
			}

			if(objectKeys.indexOf(self.noPayments[i].comentario) == -1) {
				usersComments[self.noPayments[i].comentario] = [self.noPayments[i].user + '#' + self.noPayments[i].stamp];
			} else {
				if(usersComments[self.noPayments[i].comentario].indexOf(self.noPayments[i].user + '#' + self.noPayments[i].stamp) == -1) {
					usersComments[self.noPayments[i].comentario].push(self.noPayments[i].user + '#' + self.noPayments[i].stamp);
				}
			}
		}

		if(comments) {
			self.sendNoPaymentNotifications(usersComments);
		} else {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC377
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC11;
			let alertText = pf.const.language.RSC1243;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.sendNoPaymentNotifications(usersComments);
			}, function() {});
		}
	},

	sendNoPaymentNotifications(usersComments) {
		let self = this;

		let parameters = {
			from: self.SYSNotifUser,
			data: JSON.stringify(usersComments),
			message: pf.const.language.RSC1244
		};
		ajaxComunCallWithCallback('sendNoPaymentNotifications', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC11;
				let successContent = pf.const.language.RSC401;
				pf.utils.showInfoDialog(successTitle, successContent);

				// Destruir tabla de no pagados
				self.noPayments = [];
				$('#tableNoPaymenyts').dataTable().fnDestroy();
				$('#noPaymentsTable').html('');
				$('#cointarneSend').addClass('d-none');
			}
		});
	},

	validatePagosRealizados(payments) {
		let self = this;

		let idUseridSurvey = [];
		let size = payments.length;
		for(let i = 0; i < size; i++) {
			//usuario#sid#valor#concepto#stamp
			let string = payments[i].user + '#' + payments[i].sid + '#' + payments[i].valor + '#' + payments[i].concepto + '#' + payments[i].stamp;
			idUseridSurvey.push(string);
		}

		let parameters = {
			idUseridSurvey: JSON.stringify(idUseridSurvey)
		};
		ajaxComunCallWithCallback('validatePagosRealizados', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.processedPayments = [];
				self.pendingValidation = [];
				let validation1 = [];
				let validation2 = [];

				// Pagos ya procesados - processed
				let sizeA = payments.length;
				let sizeVal = ajaxReturn.result_prev_processed.length;
				if(sizeVal > 0) {
					for(let i = 0; i < sizeA; i++) {
						let processed = false;
						for(let j = 0; j < sizeVal; j++) {
							if(ajaxReturn.result_prev_processed[j].stamp == payments[i].stamp) {
								payments[i]['importeOrig'] = ajaxReturn.result_prev_processed[j].importeOrig;
								self.processedPayments.push(payments[i]);
								processed = true;
								break;
							}
						}

						if(!processed) {
							validation1.push(payments[i]);
						}
					}
				} else {
					$('#cointarnePending').addClass('d-none');
					validation1 = payments;
				}

				// Pagos con diferente valor - pending
				let sizeB = validation1.length;
				let sizePro = ajaxReturn.result_diff_import.length;
				if(sizePro > 0) {
					for(let i = 0; i < sizeB; i++) {
						let pending = false;
						for(let j = 0; j < sizePro; j++) {
							if(ajaxReturn.result_diff_import[j].stamp == validation1[i].stamp) {
								self.pendingValidation.push(validation1[i]);
								pending = true;
								break;
							}
						}

						if(!pending) {
							validation2.push(validation1[i]);
						}
					}
				} else {
					$('#containerProcessed').addClass('d-none');
					validation2 = validation1;
				}

				self.payments = new TablePayments(true);
				self.payments.data = validation2;
				self.payments.receivedData = true;
				self.payments.excel = false;
				self.payments.import = true;
				self.payments.setEvents();

				$('#containerImport').removeClass('d-none');
				$('#btn-save').attr('disabled', false);
				$('#inputFile').val('');

				// Pendientes de validación
				if(self.pendingValidation.length > 0) {
					$('#cointarnePending').removeClass('d-none');
					self.renderPending();
				}

				// No pagados
				if(self.noPayments.length > 0) {
					$('#cointarneSend').removeClass('d-none');
					self.renderNoPayments();
				}

				// Ya pagados
				if(self.processedPayments.length > 0) {
					$('#containerProcessed').removeClass('d-none');
					self.renderProcessedPayments();
				}
			}
		});
	},

	renderPending() {
		let self = this;

		let table = `
			<table id="tablePending" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1315}">${pf.const.language.RSC1315}</th>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC134}">${pf.const.language.RSC134}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC348}">${pf.const.language.RSC348}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
						<th scope="col" title="${pf.const.language.RSC1458}">${pf.const.language.RSC1458}</th>
						<th scope="col" title="${pf.const.language.RSC1459}">${pf.const.language.RSC1459}</th>
					</tr>
				</thead>

				<thead class="filtersPending">
					<tr>
						<td class="d-none">stamp</td>
						<td>user</td>
						<td>perfil</td>
						<td>nombre</td>
						<td>concepto</td>
						<td>conceptoDesc</td>
						<td>Pais</td>
						<td>fecha</td>
						<td>importeOriginal</td>
						<td>importeExcel</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.pendingValidation.length;
		for(let i = 0; i < size; i++) {
			let date = self.pendingValidation[i].fecha.split(' ');
			let startDate = date[0];

			table += `
				<tr data-id="${i}" class="c-pointer" data-stamp="${self.pendingValidation[i].stamp}">
					<td class="text-truncate" title="${self.pendingValidation[i].stamp}">${(self.pendingValidation[i].stamp != '' ? self.pendingValidation[i].stamp : '-')}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].user}" data-stamp="${self.pendingValidation[i].stamp}">
						<input type="checkbox" class="selectionValidation mx-1">
						${(self.pendingValidation[i].user != '' ? self.pendingValidation[i].user : '-')}
					</td>
					<td class="text-truncate" title="${self.pendingValidation[i].perfil}">${(self.pendingValidation[i].perfil != '' ? self.pendingValidation[i].perfil : '-')}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].name}">${(self.pendingValidation[i].name != '' ? self.pendingValidation[i].name : '-')}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].sid}">${(self.pendingValidation[i].sid != '' ? self.pendingValidation[i].sid : '-')}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].concepto}">${(self.pendingValidation[i].concepto != '' ? self.pendingValidation[i].concepto : '-')}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].countrydesc}">${((self.pendingValidation[i].countrydesc != '' && self.pendingValidation[i].countrydesc) ? self.pendingValidation[i].countrydesc : '-')}</td>
					<td class="text-truncate" title="${startDate}">${(startDate != '' ? startDate : '-')}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].importeOrig}">${self.pendingValidation[i].importeOrig}</td>
					<td class="text-truncate" title="${self.pendingValidation[i].valor}">${self.pendingValidation[i].valor}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

		$('#pendingTable').html(table);

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

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

		let cVisibility = [
			{visible: false},
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null,
			null
		];

		self.tablePending = $('#tablePending').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			columns: cVisibility
		});

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

		// Apply the search
		applyTheSearch(self.tablePending, 'filtersPending');

		// Marcar todo
		$('#checkFiltersRowsPending').off().on('click', function() {
			self.tablePending.rows({filter: 'applied'}).every(function(rowIdx, tableLoop, rowLoop) {
				let value = self.tablePending.cell(rowIdx, 1).data();
				value = value.replace('<input type="checkbox" class="selectionValidation mx-1">', '<input type="checkbox" class="selectionValidation mx-1" checked>');
				self.tablePending.cell(rowIdx, 1).data(value);
			}).draw();
		});

		// Desmarcar todo
		$('#uncheckRowsPending').off().on('click', function() {
			self.tablePending.rows().every(function(rowIdx, tableLoop, rowLoop) {
				let value = self.tablePending.cell(rowIdx, 1).data();
				value = value.replace(/ checked=""| checked/g, '');
				self.tablePending.cell(rowIdx, 1).data(value);
			}).draw();
			self.stampsPending = [];
		});

		self.tablePendingEvents();

		$('#tablePending').on('draw.dt', function() {
			self.tablePendingEvents();
		});
	},

	tablePendingEvents() {
		let self = this;

		// Marcar de uno en uno por tr
		$('#pendingTable tbody tr').off().on('click', function() {
			let stamp = $(this).data('stamp');
			let checked = $(this).find('.selectionValidation').prop('checked');
			if(checked) {
				$(this).find('.selectionValidation').prop('checked', false);
				let index = self.stampsPending.indexOf(stamp);
				self.stampsPending.splice(index, 1);
			} else {
				$(this).find('.selectionValidation').prop('checked', true);
				self.stampsPending.push(stamp.toString());
			}
		});

		// Marcar de uno en uno por checbox
		$('.selectionValidation').off().on('click', function() {
			let checked = $(this).prop('checked');

			if(checked) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}
		});
	},

	renderProcessedPayments() {
		let self = this;

		let table = `
			<table id="tableProcessedPayments" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1315}">${pf.const.language.RSC1315}</th>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC134}">${pf.const.language.RSC134}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC348}">${pf.const.language.RSC348}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
					</tr>
				</thead>

				<thead class="filtersProcessedPayments">
					<tr>
						<td class="d-none">stamp</td>
						<td>user</td>
						<td>perfil</td>
						<td>nombre</td>
						<td>concepto</td>
						<td>conceptoDesc</td>
						<td>Pais</td>
						<td>fecha</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.processedPayments.length;
		for(let i = 0; i < size; i++) {
			let date = self.processedPayments[i].fecha.split(' ');
			let startDate = date[0];

			table += `
				<tr data-id="${i}">
					<td class="text-truncate" title="${self.processedPayments[i].stamp}">${(self.processedPayments[i].stamp != '' ? self.processedPayments[i].stamp : '-')}</td>
					<td class="text-truncate" title="${self.processedPayments[i].user}" data-stamp="${self.processedPayments[i].stamp}">
						${(self.processedPayments[i].user != '' ? self.processedPayments[i].user : '-')}
					</td>
					<td class="text-truncate" title="${self.processedPayments[i].perfil}">${(self.processedPayments[i].perfil != '' ? self.processedPayments[i].perfil : '-')}</td>
					<td class="text-truncate" title="${self.processedPayments[i].name}">${(self.processedPayments[i].name != '' ? self.processedPayments[i].name : '-')}</td>
					<td class="text-truncate" title="${self.processedPayments[i].sid}">${(self.processedPayments[i].sid != '' ? self.processedPayments[i].sid : '-')}</td>
					<td class="text-truncate" title="${self.processedPayments[i].concepto}">${(self.processedPayments[i].concepto != '' ? self.processedPayments[i].concepto : '-')}</td>
					<td class="text-truncate" title="${self.processedPayments[i].countrydesc}">${((self.processedPayments[i].countrydesc != '' && self.processedPayments[i].countrydesc) ? self.processedPayments[i].countrydesc : '-')}</td>
					<td class="text-truncate" title="${startDate}">${(startDate != '' ? startDate : '-')}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

		$('#processedTable').html(table);

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

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

		let cVisibility = [
			{visible: false},
			null,
			null,
			null,
			null,
			null,
			null,
			null
		];

		let tableProcessedPayments = $('#tableProcessedPayments').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			columns: cVisibility
		});

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

		// Apply the search
		applyTheSearch(tableProcessedPayments, 'filtersProcessedPayments');
	},

	getStampsPending() {
		let self = this;

		let data = self.tablePending.rows().data();
		data.each(function(value, index) {
			if(value[1].indexOf('checked') !== -1) {
				if(self.stampsPending.indexOf(value[0].toString()) === -1) {
					self.stampsPending.push(value[0].toString());
				}
			}
		});

		return self.stampsPending;
	},

	uploadImportPaymentsNoProcessed(selectedFile) {
		let self = this;

		let date = new Date();
		var stampName = date.getTime();
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;

		let parameters = {
			stampName: stampName,
			userMail: userMail,
			file: selectedFile
		};
		ajaxComunCallWithCallback('uploadImportPaymentsNoProcessed', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Archivo guardado correctamente
				console.log('Data excel send.');
				self.tempFileName = ajaxReturn.result;
			}
		});
	}
};