let PerSinFinalizarController = {
	data: '',
	countriesToSee: [],
	countriesToSeeDesc: '',
	tableFlag: false,

	reset() {
		let self = this;

		self.data = '';
		self.countriesToSee = [];
		self.countriesToSeeDesc = '';
		self.tableFlag = false;
	},

	setEvents() {
		let self = this;
		self.reset();

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

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

		// Opciones de header
		let jsonsubopt = {
			country: 'country',
		};

		let nav = `
			<div class="d-flex flex-row-reverse">
				${createSubOptionCountrySimple(jsonsubopt.country)}
			</div>
		`;

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

		self.loadLang();
		self.applyEvents();

		$('#resultTableContainer').hide();

		// Control de países permitidos por el administrador si solo hay uno
		let countries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let countriesDesc = atob(sessionStorage['STCMBackEnd:userCountriesDesc']);
		if(countries.length === 1) {
			self.countriesToSee = countries;
			self.countriesToSeeDesc = countriesDesc;
			$('#country').val(self.countriesToSeeDesc);
			$('#country').attr('title', self.countriesToSeeDesc);

			// Cargar tabla
			self.getAnalyticsConsejerosNoFinPerf();
		}

		// Collapse
		addEventArrowTableHeader();
	},

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

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		// País
		let countryModal = new TableCountries(1, 'perSinFinalizar');
		$('#searchCountry').on('click', function() {
			countryModal.setEvents();
		});
	},

	getAnalyticsConsejerosNoFinPerf() {
		let self = this;

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

		let parameters = {
			country: self.countriesToSee.toString()
		};
		ajaxComunCallWithCallback('getAnalyticsConsejerosNoFinPerf', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				self.renderData();
			}
		});
	},

	renderData() {
		let self = this;

		$('#registers').html('');
		if(self.tableFlag) {
			$('#registers').dataTable().fnDestroy();
		} else {
			self.tableFlag = true;
		}

		$('#export').prop('disabled', false);
		$('#resultTable').show();

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
			<th scope="col" title="${pf.const.language.RSC1626}">${pf.const.language.RSC1626}</th>
			<th scope="col" title="${pf.const.language.RSC1627}">${pf.const.language.RSC1627}</th>
		`;
		let nameSurnameFilter = `
			<td>Nombre</td>
			<td>Apellido 1</td>
			<td>Apellido 2</td>
		`;

		// Control GDPR
		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC597}">${pf.const.language.RSC597}</th>
					<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
					<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
					<th scope="col" title="${pf.const.language.RSC115}">${pf.const.language.RSC115}</th>
					<th scope="col" title="${pf.const.language.RSC613}">${pf.const.language.RSC613}</th>
					<th scope="col" title="${pf.const.language.RSC614}">${pf.const.language.RSC614}</th>
					<th scope="col" title="${pf.const.language.RSC615}">${pf.const.language.RSC615}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					${nameSurnameFilter}
					<td>E-mail</td>
					<td>pais</td>
					<td>region</td>
					<td>edad</td>
					<td>genero</td>
					<td>estadoPerfilacion</td>
					<td>ultimaPagina</td>
					<td>ultimaPregunta</td>
					<td>numIntentos</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.data[i].country) == -1) {
				continue;
			}

			let lastQuestion = '-';
			if(self.data[i].LastQuestion != null) {
				let textWithTags = self.data[i].LastQuestion;
				lastQuestion = textWithTags.replace(/<[^>]*>?/g, '');
			}

			let nameSurnameBody = `
				<td class="text-truncate" title="${self.data[i].userNombre}">${self.data[i].userNombre}</td>
				<td class="text-truncate" title="${(self.data[i].userApellidos == null ? '-' : self.data[i].userApellidos)}">${(self.data[i].userApellidos == null ? '-' : self.data[i].userApellidos)}</td>
				<td class="text-truncate" title="${(self.data[i].userApellidos2 == null ? '-' : self.data[i].userApellidos2)}">${(self.data[i].userApellidos2 == null ? '-' : self.data[i].userApellidos2)}</td>
			`;

			// Control GDPR
			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${self.data[i].token}">${self.data[i].token}</td>
					<td class="text-truncate" title="${self.data[i].country}">${self.data[i].country}</td>
					<td class="text-truncate" title="${(self.data[i].region == null ? '-' : self.data[i].region)}">${(self.data[i].region == null ? '-' : self.data[i].region)}</td>
					<td class="text-truncate" title="${(self.data[i].edad == null ? '-' : self.data[i].edad)}">${(self.data[i].edad == null ? '-' : self.data[i].edad)}</td>
					<td class="text-truncate" title="${(self.data[i].genero == null ? '-' : self.data[i].genero)}">${(self.data[i].genero == null ? '-' : self.data[i].genero)}</td>
					<td class="text-truncate" title="${self.data[i].EstadoPerfilacion}">${self.data[i].EstadoPerfilacion}</td>
					<td class="text-truncate" title="${(self.data[i].lastpage || '-')}">${(self.data[i].lastpage || '-')}</td>
					<td class="text-truncate" title="${lastQuestion}">${lastQuestion}</td>
					<td class="text-truncate" title="${self.data[i].numIntentos}">${self.data[i].numIntentos}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC611,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			rowGroup: {
				endRender(rows, group) {
					return group + ': ' + pf.const.language.RSC146 + ' (' + rows.count() + ')';
				},
				dataSrc: 0
			},
			aaSorting: []
		});

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

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

		dataTable.rowGroup().disable().draw();
		$('#nestBy').hide();

		// Creación de select principal de agrupamiento
		// Arrays de datos
		let name = [];

		$.each($('#registers thead th'), function() {
			name.push($(this).text());
		});

		let options1 = `<option value="-1">${pf.const.language.RSC130}</option>`;
		for(let i = 0; i < name.length; i++) {
			options1 += `<option value="${i}">${name[i]}</option>`;
		}
		$('#groupBy').html(options1);

		// Función de agrupamiento anidado
		function nestBy() {
			$('#nestBy').html('');
			let options2 = `<option value="-1">${pf.const.language.RSC131}</option>`;
			for(let i = 0; i < name.length; i++) {
				if(i == $('#groupBy').val()) {
					continue;
				} else {
					options2 += `<option value="${i}">${name[i]}</option>`;
				}
			}
			$('#nestBy').html(options2);

			// Evento de anidado
			$('#nestBy').off().on('change', function() {
				let valueGroup = $('#groupBy').val();

				if($('#nestBy').val() === '-1') {
					dataTable.rowGroup().dataSrc(valueGroup);
					dataTable.order([[valueGroup, 'asc']]).draw();
				} else {
					let valueNest = $('#nestBy').val();
					dataTable.rowGroup().dataSrc([valueGroup, valueNest]);
					dataTable.order([[valueGroup, 'asc'], [valueNest, 'asc']]).draw();
				}
			});
		}

		// Evento de agrupamiento
		$('#groupBy').on('change', function() {
			if($('#groupBy').val() === '-1') {
				dataTable.rowGroup().disable().draw();
				$('#nestBy').hide();
			} else {
				let value = $('#groupBy').val();

				dataTable.rowGroup().enable().draw();
				$('#nestBy').show();

				dataTable.rowGroup().dataSrc(value);
				dataTable.order([[value, 'asc']]).draw();

				// Recreación de agrupamiento secundario
				nestBy();
			}
		});

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

	clickEvents(data) {
		let self = this;

		self.countriesToSee = [];
		self.countriesToSeeDesc = '';

		let size = data.length;
		for(let i = 0; i < size; i++) {
			self.countriesToSee.push(data[i].isocode);
			self.countriesToSeeDesc += data[i].descripcion + ',';
		}
		self.countriesToSeeDesc = self.countriesToSeeDesc.substring(0, self.countriesToSeeDesc.length - 1);

		$('#country').val(self.countriesToSeeDesc);
		$('#country').attr('title', self.countriesToSeeDesc);

		// Cargar tabla
		self.getAnalyticsConsejerosNoFinPerf();
	}
};