let UsuariosImportarController = {
	token: null,
	importUsers: null,
	rols: '',
	profiles: '',
	idCPG: '',
	registrationPermit: '0',
	userAdmin: '',

	setEvents() {
		let self = UsuariosImportarController;

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

		// Reset valores
		self.token = sessionStorage['STCMBackEnd:token'];
		self.importUsers = null;

		// Control de CPG
		self.idCPG = getidCPG();
		self.registrationPermit = sessionStorage['STCMBackEnd:addUsers'];

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

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

		// Opciones de header
		let jsonsubopt = {
			generateLayout: 'exportLayout',
			importLayout: 'importLayout',
			saveMassive: 'btn-save',
			activeMassive: 'btn-activation',
			deactiveMassive: 'btn-deactivation',
			deactiveMassiveCPG: 'btn-desassign'
		};

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

		if(self.idCPG == 0 || self.idCPG == undefined) {
			nav += createSubOptionActiveMassive(jsonsubopt.activeMassive);
			nav += createSubOptionDeactiveMassive(jsonsubopt.deactiveMassive);
		} else {
			nav += createSubOptionDeactiveMassive(jsonsubopt.deactiveMassiveCPG);
		}

		nav += `
				${createSubOptionSaveMassive(jsonsubopt.saveMassive)}
			</div>
		`;

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

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

		// Botones secundarios
		$('#exportLayout').addClass('secondary-button');
		$('#importLayout').addClass('secondary-button');
		$('#btn-activation').addClass('secondary-button');
		$('#btn-deactivation').addClass('secondary-button');
		$('#btn-desassign').addClass('secondary-button');

		self.loadLanguage();
		self.applyEvents();

		self.getAllRoles();
		self.getProfile();
		// Collapse
		addEventArrowTableHeader();
	},

	applyEvents() {
		let self = UsuariosImportarController;

		// Exportar excel
		$('#exportLayout').click(function() {
			window.location = stcm.const.downloads + 'layout.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.registerUsers();
		});

		// Activar usuarios
		$('#btn-activation').click(function() {
			self.activationUsers();
		});

		// Desactivar usuarios
		$('#btn-deactivation').click(function() {
			self.deactivationUsers();
		});

		// Desasignar cpg usuarios
		$('#btn-desassign').click(function() {
			self.dessasignCPG();
		});
	},

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

	uploadFile(evt) {
		let self = UsuariosImportarController;

		addLoader();
		// Convertir excel a JSON
		var selectedFile = evt.target.files[0];
		var reader = new FileReader();
		let rolesNotFound = new Set();
		let profilesNotFound = new Set();
		let emailSet = new Set(); // Set para almacenar correos electrónicos únicos
		let duplicateEmailsSet = new Set(); // Set para almacenar correos electrónicos duplicados
		let invalidEmails = []; 
		let notFoundMessage = [];

		reader.onload = function(event) {
			var data = event.target.result;
			var 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 => {
					let roleFound = false;
					let profileFound = false;

					// Email
					if (element.email) {
						element.email = element.email.trim();
						if (!pf.utils.validateEmail(element.email)) {
							validate = false;
							invalidEmails.push(element.email); // Añadir el correo inválido al array
						}
						if (emailSet.has(element.email)) {
							// Si el correo ya está en el Set, es un duplicado
							duplicateEmailsSet.add(element.email);
						} else {
							// Añadir el correo al Set
							emailSet.add(element.email);
						}
					} 
				
					// Roles
					if(element.role) {
						let roleSize = self.rols.length;
						for(let i = 0; i < roleSize; i++) {
							if(element.role.toString().toLowerCase() == self.rols[i].role.toLowerCase()) {
								element.role = self.rols[i].role;
								roleFound = true;
								break; 
							}
						}
						if (!roleFound) {
							rolesNotFound.add(element.role);
						}
					}
				
					// Perfil
					if(element.perfil) {
						let perfilSize = self.profiles.length;
						for(let i = 0; i < perfilSize; i++) {
							if(element.perfil.toString().toLowerCase() == self.profiles[i].id.toLowerCase()) {
								element.perfil = self.profiles[i].id;
								profileFound = true;
								break; 
							}
						}
						if (!profileFound) {
							profilesNotFound.add(element.perfil);
						}
					}
					 // Consejero
					if (element.consejero !== 0 && element.consejero !== 1) {
						validate = false;
						notFoundMessage.push('Consejero debe ser 1 o 0.');
					}
				});

				// Mostrar una alerta si hay correos electrónicos duplicados
				if (duplicateEmailsSet.size > 0) {
					notFoundMessage.push('Email duplicados: ' + Array.from(duplicateEmailsSet).join(', '));
				}
				// Mostrar una alerta si no se encontró el rol o perfil
				
				if (rolesNotFound.size > 0) {
					notFoundMessage.push(pf.const.language.RSC2760 + ': ' + Array.from(rolesNotFound).join(', '));
				}
				if (profilesNotFound.size > 0) {
					notFoundMessage.push(pf.const.language.RSC2761 + ': ' + Array.from(profilesNotFound).join(', '));
				}
				if (!validate) {
					notFoundMessage.push(pf.const.language.RSC322 + ' ' + invalidEmails.join(', '));
				}
				if (notFoundMessage.length > 0) {
					let alertTitle = pf.const.language.RSC4;
					let notFound = notFoundMessage.join('<br>');
					pf.utils.showInfoDialog(alertTitle, notFound);
				} else {
					self.printTable();
				}

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

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

		reader.readAsBinaryString(selectedFile);
	},

	printTable() {
		let self = this;

		tableImport.setEvents(self.importUsers, 'resultTable');

		$('#containerImport').removeClass('d-none');

		// Control de alta de usuarios
		if(self.registrationPermit == '1') {
			$('#btn-save').prop('disabled', false);
		}

		$('#btn-activation').attr('disabled', false);
		$('#btn-deactivation').attr('disabled', false);
		$('#btn-desassign').attr('disabled', false);
		$('#inputFile').val('');
	},

	registerUsers() {
		let self = UsuariosImportarController;
		let alertTitle = pf.const.language.RSC4;
		// Comprobar si falta algún dato necesario: nombre, contraseña, email o país
		let controlDatos = self.importUsers.some(user => 
			!user.nombre || !user.password || !user.pais || !user.perfil || !user.email || !user.role || (user.consejero !== 0 && user.consejero !== 1)
		);

		// Mostrar alert si faltan datos
		if (controlDatos) {
			let alertText = pf.const.language.RSC939;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return;
		}
	
		let parameters = {
			users: JSON.stringify(self.importUsers),
			idCPG: self.idCPG,
			userAdmin: self.userAdmin
		};
	
		ajaxComunCallWithCallbackOne('importUsers', parameters, function(ajaxReturn) {
			if (ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				if (Object.keys(resp.errors).length === 0) {
					handleNoError();
				} else {
					handleErrors(resp);
				}
			}
		});
	
		function handleNoError() {
			let alertText = pf.const.language.RSC106;
			let alertBtn = pf.const.language.RSC132;
			pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
				window.location.href = '#!usuarios';
			});
		}
	  	// Función para manejar los errores
		function handleErrors(resp) {
			let errors = '';
			if (resp.errors && Object.keys(resp.errors).length) {
				
				for (let error in resp.errors) {
					if (resp.errors.hasOwnProperty(error)) {
						errors += error + '<br>';
						errors += pf.const.language.RSC323 + ': <br>';
						// Añadir cada usuario que tuvo este error
						for (let i = 0; i < resp.errors[error].length; i++) {
							errors += resp.errors[error][i] + '<br>';
						}
						errors += '<br>';
					}
				}
			}
			// Mostrar un diálogo con todos los errores y usuarios afectados
			pf.utils.showInfoDialog(alertTitle, errors);
		}
	},
	
	activationUsers() {
		let self = this;

		let validacion = false;
		let size = self.importUsers.length;
		for(let i = 0; i < size; i++) {
			if(self.importUsers[i].consejero == undefined) {
				validacion = true;
			}
		}

		// Falta el valor de 'consejero' en alguno de los registros
		if(validacion) {
			let alertTitle = pf.const.language.RSC1308;
			let alertText = pf.const.language.RSC322;
			pf.utils.showInfoDialog(alertTitle, alertText);

			return;
		}

		let parameters = {
			users: JSON.stringify(self.importUsers),
			userAdmin: self.userAdmin
		};
		ajaxComunCallWithCallback('activationUsers', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.errorUsers == 'overflow') {
					let numberOverflow = ajaxReturn.num;
					let alertText = pf.const.language.RSC1238.replace('__N__', numberOverflow);
					let alertTitle = pf.const.language.RSC4;
					pf.utils.showInfoDialog(alertTitle, alertText);
				} else {
					let alertTitle = pf.const.language.RSC1308;
					let alertText = pf.const.language.RSC1310;
					let alertBtn = pf.const.language.RSC132;
					pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
						window.location.href = '#!usuarios';
					});
				}
			}
		});
	},

	deactivationUsers() {
		let self = this;

		let parameters = {
			users: JSON.stringify(self.importUsers)
		};
		ajaxComunCallWithCallback('deactivationUsers', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let alertTitle = pf.const.language.RSC1309;
				let alertText = pf.const.language.RSC1305;
				let alertBtn = pf.const.language.RSC132;
				pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
					window.location.href = '#!usuarios';
				});
			}
		});
	},

	// Recibir todos los roles
	getAllRoles() {
		let self = this;

		ajaxComunCallWithCallback('getAllRoles', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				if(!Array.isArray(ajaxReturn.result)) {
					self.rols = [];
				} else {
					self.rols = ajaxReturn.result;
				}
			}
		});
	},

	getProfile(){
		let self = this;

		ajaxComunCallWithCallback('getProfiles', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				if(!Array.isArray(ajaxReturn.result)) {
					self.profiles = [];
				}else {
					self.profiles = ajaxReturn.result;
				}
			}
		});
	},

	dessasignCPG() {
		let self = this;

		let parameters = {
			users: JSON.stringify(self.importUsers),
			idCPG: self.token
		};
		ajaxComunCallWithCallback('dessasignCPG', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let alertTitle = pf.const.language.RSC1309;
				let alertText = pf.const.language.RSC1305;
				let alertBtn = pf.const.language.RSC132;
				pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
					window.location.href = '#!usuarios';
				});
			}
		});
	}
};