let NotificacionesPreConsejerosController = {
	importUsers: null,
	ajax: false,

	reset() {
		let self = this;

		self.importUsers = null;
		self.ajax = false;
	},

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

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

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

		// Opciones de header
		let jsonsubopt = {
			generateLayout: 'exportLayout',
			importLayout: 'importLayout',
			sendEmail: 'send_email',
			sendEmailData: 'send_email_data'
		};

		let nav = `
			<div class="row mx-0">
				${createSubOptionGenerateLayout(jsonsubopt.generateLayout)}
				${createSubOptionImportLayout(jsonsubopt.importLayout)}
				${createSubOptionSendEmailData(jsonsubopt.sendEmailData)}
				${createSubOptionSendEmail(jsonsubopt.sendEmail)}
			</div>
		`;

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

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

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

		self.loadLanguage();
		self.applyEvents();
	},

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

	applyEvents() {
		let self = this;

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

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

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

		// Enviar e-mails
		$('#send_email').click(function() {
			let values = {
				ajax: self.ajax,
				reqLabel: 'sendReActivationEmail',
				sendMail: '1'
			};

			let generator = new NotificationGeneratorController(values);
			generator.start();
		});

		// Enviar e-mails
		$('#send_email_data').click(function() {
			let values = {
				ajax: self.ajax,
				reqLabel: 'sendReActivationEmail',
				sendMail: '0'
			};

			let generator = new NotificationGeneratorController(values);
			generator.start();
		});
	},

	uploadFile(evt) {
		let self = this;

		addLoader();
		// Convertir excel a JSON
		let selectedFile = evt.target.files[0];
		let reader = new FileReader();
		reader.onload = function(event) {
			let data = event.target.result;
			let workbook = XLSX.read(data, {
				type: 'binary'
			});

			workbook.SheetNames.forEach(function(sheetName) {
				self.importUsers = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

				let validate = true;
				self.importUsers.forEach(element => {
					element.email = element.email.trim();
					if(element.email && !pf.utils.validateEmail(element.email)) {
						validate = false;
					}
				});

				if(!validate) {
					let alertTitle = pf.const.language.RSC4;
					let alertText = pf.const.language.RSC322;
					pf.utils.showInfoDialog(alertTitle, alertText);
				} else {
					self.printTable();
				}

				removeLoader();
				$('#inputFile').val(null);
			})
		};

		reader.readAsBinaryString(selectedFile);
	},

	printTable() {
		let self = this;

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

		self.renderUsers();
	},

	renderUsers() {
		let self = this;

		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>name</td>
			<td>surname1</td>
			<td>surname2</td>
		`;

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

		let table = `
			<table id="registers" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						${nameSurnameHead}
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>email</td>
						${nameSurnameFilter}
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.importUsers.length;

		if(size === 0) {
			$('#send_email').attr('disabled', true);
			$('#send_email_data').attr('disabled', true);
		}

		for(let i = 0; i < size; i++) {
			let nameSurnameBody = `
				<td class="text-truncate" title="${(self.importUsers[i].nombre || '-')}">${(self.importUsers[i].nombre || '-')}</td>
				<td class="text-truncate" title="${(self.importUsers[i].apellido1 || '-')}">${(self.importUsers[i].apellido1 || '-')}</td>
				<td class="text-truncate" title="${(self.importUsers[i].apellido2 || '-')}">${(self.importUsers[i].apellido2 || '-')}</td>
			`;

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

			table += `
				<tr data-id="${i}">
					<td class="text-truncate" title="${self.importUsers[i].email}">${self.importUsers[i].email}</td>
					${nameSurnameBody}
				</tr>
			`;
		}

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

		$('#resultTable').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
		});

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

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

	sendReActivationEmail(idReport, sendMail) {
		let self = this;

		let emailArray = [];
		let size = self.importUsers.length;
		for(let i = 0; i < size; i++) {
			emailArray.push(self.importUsers[i].email);
		}

		let parameters = {
			emailArray: emailArray,
			sendMail: sendMail
		};
		ajaxComunCallWithCallback('sendReActivationEmail', parameters, function(ajaxReturn) {
			let title = '';
			let content = '';

			if(ajaxReturn) {
				title = pf.const.language.RSC1876;
				if(sendMail == 0) {
					content = pf.const.language.RSC2019;
				} else {
					content = pf.const.language.RSC1880;
				}

				CardGeneratorController.showOnScreenNotification(idReport, content, 'check-circle');
				// En caso de dar click en 'Generar Data para envío email por fuera de plataforma'
				if(sendMail == 0) {
					ajaxComunCallWithCallback('getPreConsejeros', {}, function(ajaxReturn) {
						if(ajaxReturn) {
							self.renderPreConsejeros(ajaxReturn);
						}
					});
				}
			}

			$(`#downloadCardTitle_${idReport}`).html(title);
			$(`#downloadCardTitle_${idReport}`).addClass('main-color-text');
			$(`#downloadCardText_${idReport}`).html(content);
			$(`#${idReport}`).removeClass('runningReport');
			CardGeneratorController.updateIcon();
		});
	},

	renderPreConsejeros(data) {
		$('#resultPreConsejeros').removeClass('d-none');

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC785}">${pf.const.language.RSC785}</th>
					<th scope="col" title="${pf.const.language.RSC355}">${pf.const.language.RSC355}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>email</td>
					<td>url</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = data.result.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="${data.result[i].token}">
					<td class="text-truncate" title="${data.result[i].token}">${data.result[i].token}</td>
					<td class="text-truncate" title="${data.result[i].url}">${data.result[i].url}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let dataTable = $('#tablePreConsejeros').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '300px', targets: 0}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1876,
				className: 'd-none',
				title: pf.const.language.RSC1876,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

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

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