let UsuariosImportarController = {
	token: null,
	importUsers: null,
	rols: '',
	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();

		// 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();
		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 => {
					element.email = element.email.trim();
					if(element.email && !pf.utils.validateEmail(element.email)) {
						validate = false;
					}

					// 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;
							}
						}
					}

					// País
					if(element.pais) {
						element.pais = element.pais.toLowerCase();
					} else {
						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.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;

		// Revisión de usuarios para registrar
		// Añadir país como necesario
		let controlDatos = false;
		let size = self.importUsers.length;
		for(let i = 0; i < size; i++) {
			if(self.importUsers[i].nombre == '' || self.importUsers[i].nombre == undefined || self.importUsers[i].password == '' || self.importUsers[i].password == undefined || self.importUsers[i].pais == '' || self.importUsers[i].pais == undefined) {
				controlDatos = true;
				break;
			}
		}

		if(controlDatos) {
			let alertTitle = pf.const.language.RSC4;
			let alertText = pf.const.language.RSC322;
			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(resp.errorUsers == 'overflow') {
					let numberOverflow = resp.num;
					let alertText = pf.const.language.RSC1238.replace('__N__', numberOverflow);
					let alertTitle = pf.const.language.RSC4;
					pf.utils.showInfoDialog(alertTitle, alertText);
				} else if(resp.errorUsers.length == 0) {
					let alertTitle = pf.const.language.RSC4;
					let alertText = pf.const.language.RSC106;
					let alertBtn = pf.const.language.RSC132;
					pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
						window.location.href = '#!usuarios';
					});
				} else {
					let errors = '';
					errors += pf.const.language.RSC323;
					errors += ': <br>';
					for(let i = 0; i < resp.errorUsers.length; i++) {
						errors += resp.errorUsers[i];
						errors += '<br>';
					}
					let alertTitle = pf.const.language.RSC4;
					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;
				}
			}
		});
	},

	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';
				});
			}
		});
	}
};