let UsuariosEditarController = {
	user: null,
	botConfig: null,
	voiceAssistant: null,
	voiceAssistantNew: {},
	rols: null,
	extendedInfo: null,
	groups: null,
	groupsOld: null,
	forget: '',
	idCPG: '',
	crewObject: {},
	segmentationResult: '',
	devicesResult: '',
	dataBankResult: '',
	userAdmin: '',
	loaders: {},
	extendedData: '',

	resetData() {
		let self = this;

		self.user = null;
		self.botConfig = {
			idUserOrGroup: null,
			directLineSecret: null,
			botId: null,
			isGroup: null,
			enabled: null,
			botUser: null,
			numVecesNoMatch: null,
			textoNoMatch: null,
			userNotificarNoMatch: null,
			messageNotifNoMatch: null,
			SaludoInicial: null
		};
		self.voiceAssistant = {
			enabled: '0',
			dictionary: '',
			voiceAssisUser: '',
			country: '',
			gender: 'MALE',
			applyGreeting: '0',
			textGreeting: '',
			numVecesNoMatch: '',
			textoNoMatch: '',
			texttouser: '',
			notificationType: 'user',
			userNotificarNoMatch: '',
			textoNotificarNoMatch: ''
		};
		self.voiceAssistantNew = {
			dictionary: '',
		};
		self.rols = null;
		self.extendedInfo = null;
		self.groups = [];
		self.groupsOld = [];
		self.forget = '';
		self.idCPG = '';
		self.crewObject = {};
		self.segmentationResult = '';
		self.devicesResult = '';
		self.dataBankResult = '';
		self.userAdmin = '';
		self.loaders = {
			getAllRoles: false,
			getUserGroups: false,
			getUserExtendedInfo: false,
			getBotConfig: false,
			getVoiceAssistantConfig: false,
			isUserForgotten: false,
			getDetallePagosByUser: false
		};
		self.extendedData = '';
	},

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

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

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

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

		// Control de CPG
		self.idCPG = getidCPG();

		// Opciones de header
		let jsonsubopt = {
			back: 'backLists',
			save: 'btn-send',
			pass: 'btn-pass',
			disabledCPG: 'btn-disabledCPG'
		};

		let nav = `<div class="row mx-0">`;

		if(self.idCPG == 0 || self.idCPG == undefined) {
			nav += createSubOptionChangePass(jsonsubopt.pass);
			nav += `<button id="forget" type="button" class="btn ma-le-5"></button>`;
			nav += createSubOptionSave(jsonsubopt.save);
			nav += `</div>`;
		} else {
			nav += createSubOptionDisableCPG(jsonsubopt.disabledCPG);
			nav += `</div>`;
		}

		nav += createSubOptionBack(jsonsubopt.back);

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

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

		// Botones secundarios
		$('#backLists').addClass('secondary-button');
		$('#btn-pass').addClass('secondary-button');
		$('#btn-disabledCPG').addClass('secondary-button');
		$('#forget').addClass('secondary-button');

		if(self.idCPG != 0 && self.idCPG != undefined) {
			$('.cpg').prop('disabled', true);
		}

		// Obtener gestión de GDPR y ocultar en caso necesario el botón de derecho al olvido
		let gdpr = sessionStorage['STCMBackEnd:GDPR'];
		if(gdpr == '0') {
			$('#forget').hide();
		}

		// Obtener usuario a editar
		let user = sessionStorage['STCMBackEnd:editUser'];
		self.user = JSON.parse(atob(user));

		// Extended Data
		if (self.user.extendedData !== undefined && self.user.extendedData !== null && Object.keys(self.user.extendedData).length > 0) {
            $('#extendedDataTab').removeClass('d-none');
            $('#extendedDataCode').text(JSON.stringify(self.user.extendedData, undefined, 4));
        }

		// Quitar opcion de activar usuario cuando es un administrador de cpg
		if(self.idCPG != 0 && self.idCPG != undefined) {
			$('#userActive').hide();
		}

		addLoader();
		ajaxComunCallWithCallback('getIdiomas', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let idiomas = ajaxReturn.result;

				// Búsqueda de idiomas activos y creación de select
				let options = '';
				let sizeA = idiomas.length;
				for(let i = 0; i < sizeA; i++) {
					if(idiomas[i].enabled == 1) {
						options += `<option value="${idiomas[i].isocode}">${idiomas[i].descripcion}</option>`;
					}
				}

				$('#idioma').html(options);

				self.getData();
			}
		}, false);

		self.setUserInputs();
		self.getDetallePagosByUser();

		stcmbackend.usuarios.sharedEvents(self);

		// Texto de saludo de asistente de voz oculto en inicio
		$('#textGreetingContainer').hide();

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

		// Pintar texto de label
		changeLabelsColor();

		// Pestañas de inicio ocultas
		$('.remunerationsTab').hide();
		$('.additionalInfoTab').hide();
		$('.botVoiceAssistantTab').hide();
		$('.extendedDataTab').hide();
	},

	loadLanguage() {
		pf.rsc.translateByTag('text');
		pf.rsc.translateByTag('placeholder');

		let arrObj = ['RSC300'];
		pf.rsc.translateByTagHTMLFormat('simple', arrObj);

		// TITLES
		$('#infoTab').attr('title', pf.const.language.RSC1314);
		$('#remunerationsTab').attr('title', pf.const.language.RSC1324);
		$('#additionalInfoTab').attr('title', pf.const.language.RSC2524);
		$('#botVoiceAssistantTab').attr('title', pf.const.language.RSC2525);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		// Cambio de pestañas
		$('.tab-button').on('click', function() {
			$('.tab-button').removeClass('activeTB');
			$(this).addClass('activeTB');

			// Ocultar todas las secciones
			$('.infoTab').hide();
			$('.remunerationsTab').hide();
			$('.additionalInfoTab').hide();
			$('.botVoiceAssistantTab').hide();
			$('.extendedDataTab').hide();

			// Mostrar la sección activa
			let id = $(this).data('id');
			$('.' + id).show();
		});

		// Comprobar si es cpg para deshabilitar todas las funciones
		if(self.idCPG == 0 || self.idCPG == undefined) {
			// Cargar usuarios admin
			let admin = new TableUsers(0, 'editUser');

			// Cargar usuarios para añadir al grupo
			self.crewObject = new TableGroups(1, 'editUser');
			$('#btn-addGroup').click(function() {
				self.userType = 'addGroups';
				self.crewObject.setEvents();
			});

			// Cargar usuarios bot user
			$('#btn-botUser').click(function() {
				self.userType = 'userBot';
				admin.setEvents();
			});

			// Cargar usuarios notificacion
			let userNotif = new TableUsers(0, 'editUser');
			$('#btn-userNotificarNoMatch').click(function() {
				self.userType = 'userNotif';
				userNotif.setEvents();
			});

			$('#btn-role').click(function() {
				self.userType = 'rol';
				tableRol.setEvents('editUser');
			})

			$('#btn-bots').click(function() {
				self.userType = 'bots';
				tableBots.setEvents('editUser');
			});

			// Cambio select rol
			$('#role').change(function() {
				self.roleChange();
			});

			// Perfil
			$('#btn_searchPerfil').off().on('click', function() {
				self.userType = 'perfil';
				tablePerfiles.setEvents('usersEdit');
			});

			// País
			let countryModal = new TableCountries(0, 'editUserCountry');
			$('#searchCountry').off().on('click', function() {
				self.userType = 'country';
				countryModal.setEvents();
			});

			// Cambiar contraseña
			$('#btn-pass').click(function() {
				setTimeout(function() {
					self.revelPass();
				}, 500);

				let content = `
					<div class="form-group">
						<label class="fw-500">${pf.const.language.RSC288}</label>

						<div class="input-group new-input-pass-style">
							<input id="pass1" type="password" class="form-control" name="pass1" aria-describedby="btn-users">
							<div class="input-group-append">
								<button id="btn-pass1" type="button" class="btn btn-outline-secondary">
									${stcmbackend.svg.eyeWithoutColor}
								</button>
							</div>
						</div>
					</div>

					<div class="form-group">
						<label class="fw-500">${pf.const.language.RSC289}</label>

						<div class="input-group new-input-pass-style">
							<input id="pass2" type="password" class="form-control" name="pass2" aria-describedby="btn-users">
							<div class="input-group-append">
								<button id="btn-pass2" type="button" class="btn btn-outline-secondary">
									${stcmbackend.svg.eyeWithoutColor}
								</button>
							</div>
						</div>
					</div>
				`;

				let objInfo = {
					accept: {
						text: pf.const.language.RSC78
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC287;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, content, objInfo, function() {
					self.changePassword();
				}, function() {});
			});

			// Derecho al olvido
			$('#forget').off().on('click', function() {
				let warningText = '';
				if(self.forget == 0) {
					warningText = pf.const.language.RSC990 + '<br>' + pf.const.language.RSC991;
				} else {
					return;
				}

				let objInfo = {
					accept: {
						text: pf.const.language.RSC141
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = (self.idCPG == 0) ? pf.const.language.RSC986 : pf.const.language.RSC1726;
				let alertText = (self.idCPG == 0) ? warningText : pf.const.language.RSC1727;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.forget = 1;
					self.forgetUser();
				}, function() {});
			});

			// País
			let countryModalVoiceAssis = new TableCountries(0, 'editUserCountry');
			$('#searchCountryVoiceAssis').off().on('click', function() {
				self.userType = 'countryVoiceAssis';
				countryModalVoiceAssis.setEvents();
			});

			// Asistente de voz
			// Si se selecciona 'bot' se deselecciona el asistente de voz y viceversa
			$('#enabled').off().on('change', function() {
				if($('#enabled').prop('checked')) {
					// Asignar usuario a bot
					$('#botUser').val(self.user.id);
					$('#botUserName').text(self.user.nameUser);
					// Limpieza de asistente de voz
					$('#voiceAssisEnabled').prop('checked', false);
					$('#dictionary').val('');
					self.voiceAssistantNew.dictionary = '';
					$('#voiceAssistantUser').val('');
					$('#paisVoiceAssis').val('');
					$('#voiceAssistantName').text('');
					$('#voiceAssisSaludoInicial').prop('checked', false);
					$('#textGreeting').val('');
					$('#voiceAssisNumVecesNoMatch').val('');
					$('#voiceAssisTextoNoMatch').val('');
					$('#voiceAssisTextoContactNotice').val('');
					$('#notificationTypeUser').prop('checked', true);
					$('#voiceAssisUserNotificarNoMatch').val('');
					$('#voiceAssisUserNotificarNoMatchName').text('');
					$('#voiceAssisTextoNotificarNoMatch').val('');

					// Se oculta la obligatoriedad de inputs de asistente de voz
					$('.voiceAssisSpan').hide();
				}
			});

			$('#voiceAssisEnabled').off().on('change', function() {
				if($('#voiceAssisEnabled').prop('checked')) {
					// Asignar usuario a asistente de voz
					$('#voiceAssistantUser').val(self.user.id);
					$('#voiceAssistantName').text(self.user.nameUser);
					// Limpieza de bot
					$('#enabled').prop('checked', false);
					$('#directLineSecret').val('');
					$('#botId').val('');
					$('#botUser').val('');
					$('#botUserName').text('');
					$('#saludoInicial').prop('checked', false);
					$('#numVecesNoMatch').val('');
					$('#textoNoMatch').val('');
					$('#userNotificarNoMatch').val('');
					$('#userNotificarNoMatchName').text('');
					$('#textoNotificarNoMatch').val('');

					// Se hace visible la obligatoriedad de inputs del asistente de voz
					$('.voiceAssisSpan').show();
				} else {
					// Se oculta la obligatoriedad de inputs de asistente de voz
					$('.voiceAssisSpan').hide();
				}
			});

			// Control de saludo de asistente de voz
			$('#voiceAssisSaludoInicial').off().on('change', function() {
				if($('#voiceAssisSaludoInicial').prop('checked')) {
					// Mostrar texto de saludo
					$('#textGreetingContainer').show();
				} else {
					// Ocultar texto de saludo
					$('#textGreeting').val('');
					$('#textGreetingContainer').hide();
				}
			});

			// Cargar diccionarios
			let dictionaries = new TableDictionary('UsuariosEditarController');
			$('#btn-dictionary').click(function() {
				self.userType = 'dictionaries';
				dictionaries.setEvents();
			});

			// Cargar usuarios asistente de voz
			let voiceAssistantUser = new TableUsers(0, 'editUser');
			$('#btn-voiceAssistantUser').click(function() {
				self.userType = 'userVoiceAssistant';
				voiceAssistantUser.setEvents();
			});

			// Tipo de usuario
			$('#staff').on('change', function() {
				if($('#staff').prop('checked')) {
					$('.option-box-check').removeClass('option-box-check-selected');
					$(this).parent().addClass('option-box-check-selected');
				}
			});
			$('#consejero').on('change', function() {
				if($('#consejero').prop('checked')) {
					$('.option-box-check').removeClass('option-box-check-selected');
					$(this).parent().addClass('option-box-check-selected');
				}
			});

			// Tipo de notificación
			$('#notificationTypeUser').on('change', function() {
				if($('#notificationTypeUser').prop('checked')) {
					$('#voiceAssisTextoNotificarNoMatchContainer').show();

					$('.option-box-check-2').removeClass('option-box-check-selected');
					$(this).parent().addClass('option-box-check-selected');
				}
			});
			$('#notificationTypeMail').on('change', function() {
				if($('#notificationTypeMail').prop('checked')) {
					$('#voiceAssisTextoNotificarNoMatchContainer').show();

					$('.option-box-check-2').removeClass('option-box-check-selected');
					$(this).parent().addClass('option-box-check-selected');
				}
			});
			$('#notificationTypeVideo').on('change', function() {
				if($('#notificationTypeVideo').prop('checked')) {
					$('#voiceAssisTextoNotificarNoMatchContainer').hide();
					$('#voiceAssisTextoNotificarNoMatch').val('');

					$('.option-box-check-2').removeClass('option-box-check-selected');
					$(this).parent().addClass('option-box-check-selected');
				}
			});

			// Cargar usuarios notificacion asistente de voz
			$('#btn-voiceAssisUserNotificarNoMatch').click(function() {
				self.userType = 'userNotifVoiceAssistant';
				voiceAssistantUser.setEvents();
			});
		} else {
			$('#email').prop('disabled', true);
			$('#btn-addGroup').prop('disabled', true);
			$('#btn-botUser').prop('disabled', true);
			$('#btn-userNotificarNoMatch').prop('disabled', true);
			$('#btn-role').prop('disabled', true);
			$('#btn-bots').prop('disabled', true);
			$('#searchEstadoPerf').prop('disabled', true);
			$('#searchGeneroPerf').prop('disabled', true);
			$('#role').prop('disabled', true);
			$('#btn_searchPerfil').prop('disabled', true);
			$('#searchCountry').prop('disabled', true);

			// Asistente de voz
			$('#btn-dictionary').prop('disabled', true);
			$('#btn-voiceAssistantUser').prop('disabled', true);
			$('#btn-voiceAssisUserNotificarNoMatch').prop('disabled', true);
			$('#searchCountryVoiceAssis').prop('disabled', true);

			// Desasignar CPG
			$('#btn-disabledCPG').off().on('click', function() {
				let objInfo = {
					accept: {
						text: pf.const.language.RSC141
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC1726;
				let alertText = pf.const.language.RSC1727;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.forget = 1;
					self.disabledCPG();
				}, function() {});
			});
		}

		// change validation email
		$('#btn_communicationEmail').off('click').click(function() {
			let elem = $(this);
			let isBlocked = elem.find('svg').hasClass('bi-lock');
			if(isBlocked) {
				self.showInfoLockedFields(pf.const.language.RSC1926, function(result) {
					if(result == 'ACCEPT') {
						$('#communicationEmail').parent().removeClass('div-disabled');
						self.guiChangeBlockedFields(elem, 'communicationEmail', isBlocked);
					}
				});
			} else {
				$('#communicationEmail').parent().addClass('div-disabled');
				self.guiChangeBlockedFields(elem, 'communicationEmail');
			}
		});

		// change validation phone
		$('#btn_communicationTelf').off('click').click(function() {
			let elem = $(this);
			let isBlocked = elem.find('svg').hasClass('bi-lock');
			if(isBlocked) {
				self.showInfoLockedFields(pf.const.language.RSC1926, function(result) {
					if(result == 'ACCEPT') {
						$('#communicationTelf').parent().removeClass('div-disabled');
						self.guiChangeBlockedFields(elem, 'communicationTelf', isBlocked);
					}
				});
			} else {
				$('#communicationTelf').parent().addClass('div-disabled');
				self.guiChangeBlockedFields(elem, 'communicationTelf');
			}
		});

		// change validation email
		$('#communicationEmail').off('focusout').focusout(function() {
			let elem = $(this);
			let isBlocked = elem.find('i').hasClass('fa-lock');
			if(!isBlocked) {
				$('#btn_communicationEmail').click();
			}
		});

		// change validation phone
		$('#communicationTelf').off('focusout').focusout(function() {
			let elem = $(this);
			let isBlocked = elem.find('i').hasClass('fa-lock');
			if(!isBlocked) {
				$('#btn_communicationTelf').click();
			}
		});

		$('#btn-send').click(function() {
			// Comprobar que los campos esta rellenos
			let clabeOK = {ok: false};
			if($('#pais').val() == 'mex') {
				clabeOK = clabe.validate($('#userAccount').val());
			} else {
				clabeOK.ok = true;
			}

			if($('#nameUser').val().length == 0 || (!clabeOK.ok && $('#userAccount').val().length > 0)) {
				if($('#nameUser').val().length == 0) {
					$('#nameUser').addClass('is-invalid');
					$('[for="nameUser"]').addClass('is-invalid');
				}

				let alertText = pf.const.language.RSC101;

				if(!clabeOK.ok && $('#userAccount').val().length > 0) {
					$('#userAccount').addClass('is-invalid');
					$('[for="userAccount"]').addClass('is-invalid');
					alertText = pf.const.language.RSC315;
				}

				let alertTitle = pf.const.language.RSC78;
				pf.utils.showInfoDialog(alertTitle, alertText);
			} else {
				$('#nameUser').removeClass('is-invalid');
				$('[for="nameUser"]').removeClass('is-invalid');
				$('#userAccount').removeClass('is-invalid');
				$('[for="userAccount"]').removeClass('is-invalid');

				let objInfo = {
					accept: {
						text: pf.const.language.RSC78
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC78;
				let alertText = pf.const.language.RSC105;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.sendData();
				}, function() {});
			}
		});
	},

	guiChangeBlockedFields(elem, taginput, isBlocked) {
		let padlock = '';
		if(isBlocked) {
			padlock = `
				<svg class="bi bi-unlock" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
					<path d="M11 1a2 2 0 0 0-2 2v4a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h5V3a3 3 0 0 1 6 0v4a.5.5 0 0 1-1 0V3a2 2 0 0 0-2-2zM3 8a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V9a1 1 0 0 0-1-1H3z"/>
				</svg>
			`;
			$('#' + taginput).attr('disabled', false);
		} else {
			padlock = `
				<svg class="bi bi-lock" width="16" height="16" fill="currentColor" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
					<path d="M8 1a2 2 0 0 1 2 2v4H6V3a2 2 0 0 1 2-2zm3 6V3a3 3 0 0 0-6 0v4a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2zM5 8h6a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/>
				</svg>
			`;
			$('#' + taginput).attr('disabled', true);
		}

		elem.html(padlock);
	},

	showInfoLockedFields(text, callback) {
		let objInfo = {
			accept: {
				text: pf.const.language.RSC141
			},
			cancel: {
				text: pf.const.language.RSC57
			}
		};

		let alertTitle = pf.const.language.RSC2 + ' - ' + pf.const.language.RSC225;
		pf.utils.showInfoDialogAcceptCancel(alertTitle, text, objInfo, function() {
			callback('ACCEPT');
		}, function() {
			callback('CANCEL');
		});
	},

	// Mostrar Contraseña
	revelPass() {
		$('#btn-pass1').mouseup(function() {
			$('#pass1').attr('type', 'password');
		});
		$('#btn-pass1').mousedown(function() {
			$('#pass1').attr('type', 'text');
		});
		$('#btn-pass2').mouseup(function() {
			$('#pass2').attr('type', 'password');
		});
		$('#btn-pass2').mousedown(function() {
			$('#pass2').attr('type', 'text');
		});
	},

	changePassword() {
		let self = this;

		let pass1 = $('#pass1').val();
		let pass2 = $('#pass2').val();

		if(pass1 == pass2 && pass1 != '') {
			let email = self.user.email;

			let parameters = {
				email: email,
				password: pass1
			};
			ajaxComunCallWithCallback('changePass', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					removeLoader();
					let errorTitle = pf.const.language.RSC71;
					let errorContent = pf.const.language.RSC359;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}
			});
		} else {
			let alertTitle = pf.const.language.RSC287;
			let alertText = pf.const.language.RSC290;
			let alertBtn = pf.const.language.RSC78;
			pf.utils.showInfoDialog(alertTitle, alertText, alertBtn);
		}
	},

	getData() {
		let self = this;

		self.getAllRoles();
		self.getGroups();
		self.getUserExtendedInfo();
		self.getBotConfig();
		self.getVoiceAssistantConfig();
		self.isUserForgotten();
	},

	getUserExtendedInfo() {
		let self = this;

		let parameters = {
			email: self.user.email
		};
		ajaxComunCallWithCallback('getUserExtendedInfo', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.extendedInfo = ajaxReturn.result[0];
				self.segmentationResult = ajaxReturn.segmentationsResult;
				self.dataBankResult = ajaxReturn.clabeInfo;
				self.devicesResult = ajaxReturn.devicePushInfo;
				self.tableSegResult();
				self.tableDataBankResult();
				self.setExtenderInfoInputs();
				self.tableDevsResult();
				self.tableExtDataResult();

				// Control de spinner
				self.loaders.getUserExtendedInfo = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	getAllRoles() {
		let self = this;

		ajaxComunCallWithCallback('getAllRoles', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				// Comprobación de array
				if(!Array.isArray(ajaxReturn.result)) {
					self.rols = [];
				} else {
					self.rols = ajaxReturn.result;
				}

				// Cargar roles select
				let rolePerm = {};
				for(let i = 0; i < self.rols.length; i++) {
					rolePerm[self.rols[i].role] = self.rols[i];
				};

				self.rols = rolePerm;
				$('#role').val(self.user.role);
				self.roleChange();

				// Control de spinner
				self.loaders.getAllRoles = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	roleChange() {
		let self = this;

		let role = $('#role').val();
		if(role.length > 0) {
			TableRoles.setEvents(self.rols[role], 'permission', 'editUser');
		} else {
			$('#permission').html('');
		}
	},

	getGroups() {
		let self = this;

		let parameters = {
			jid: self.user.id
		};
		ajaxComunCallWithCallback('getUserGroups', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.groups = ajaxReturn.result;

				let groupsOld = [];
				for(let i = 0; i < ajaxReturn.result.length; i++) {
					groupsOld.push(ajaxReturn.result[i].id);
				}
				self.groupsOld = groupsOld;
				self.crewObject.groups = ajaxReturn.result;
				TableGroupsUser.setEvents(self.groups, 'divGroupsTable', 'editUsers');
				TableGroupsUser.setEvents(self.groups, 'divGroupsTableAdmin', 'editUsers', 1);

				// Control de spinner
				self.loaders.getUserGroups = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	getBotConfig() {
		let self = UsuariosEditarController;

		let parameters = {
			idUserOrGroup: self.user.id,
			isGroup: 0
		};
		ajaxComunCallWithCallback('getBotConfig', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.length > 0) {
					self.botConfig = {
						idUserOrGroup: ajaxReturn.result[0].idUserOrGroup,
						directLineSecret: ajaxReturn.result[0].directLineSecret,
						botId: ajaxReturn.result[0].botId,
						isGroup: ajaxReturn.result[0].isGroup,
						enabled: ajaxReturn.result[0].enabled,
						botUser: ajaxReturn.result[0].botUser,
						numVecesNoMatch: ajaxReturn.result[0].numVecesNoMatch,
						textoNoMatch: ajaxReturn.result[0].textoNoMatch,
						userNotificarNoMatch: ajaxReturn.result[0].userNotificarNoMatch,
						messageNotifNoMatch: ajaxReturn.result[0].textoNotificarNoMatch,
						SaludoInicial: ajaxReturn.result[0].saludoInicial
					};
				} else {
					self.botConfig = {
						idUserOrGroup: self.user.id,
						directLineSecret: '',
						botId: '',
						isGroup: '0',
						enabled: '0',
						botUser: '',
						numVecesNoMatch: '0',
						textoNoMatch: '',
						userNotificarNoMatch: '',
						messageNotifNoMatch: '',
						SaludoInicial: '0'
					};
				}

				self.setBotsConfigInputs();

				// Control de spinner
				self.loaders.getBotConfig = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	getVoiceAssistantConfig() {
		let self = UsuariosEditarController;

		let parameters = {
			idUserOrGroup: self.user.id,
			isGroup: 0
		};
		ajaxComunCallWithCallback('getVoiceAssistantConfig', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.length > 0) {
					let notificationType = 'user';
					if(ajaxReturn.result[0].emailNoMatch == '1') {
						notificationType = 'mail';
					} else if(ajaxReturn.result[0].videocallNoMatch == '1') {
						notificationType = 'videocall';
					}

					// Nombre del diccionario para el input
					$('#dictionary').val(ajaxReturn.result[0].description);

					self.voiceAssistant = {
						enabled: ajaxReturn.result[0].enabled,
						dictionary: ajaxReturn.result[0].idDictionary,
						voiceAssisUser: ajaxReturn.result[0].idUserOrGroup,
						country: ajaxReturn.result[0].country,
						gender: ajaxReturn.result[0].gender,
						applyGreeting: ajaxReturn.result[0].saludoInicial,
						textGreeting: ajaxReturn.result[0].textoSaludo,
						numVecesNoMatch: ajaxReturn.result[0].numVecesNoMatch,
						textoNoMatch: ajaxReturn.result[0].textoNoMatch,
						texttouser: ajaxReturn.result[0].texttouser,
						notificationType: notificationType,
						userNotificarNoMatch: ajaxReturn.result[0].userNotificarNoMatch,
						textoNotificarNoMatch: ajaxReturn.result[0].textoNotificarNoMatch
					};

					self.voiceAssistantNew.dictionary = ajaxReturn.result[0].idDictionary;

					self.setVoiceAssistantConfigInputs();
				}

				// Control de spinner
				self.loaders.getVoiceAssistantConfig = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	setUserInputs() {
		let self = this;

		// User
		$('#email').val(self.user.email);
		$('#userNombre').val(self.user.nameUser);
		$('#userApellidos').val((self.user.userApellidos == 'null' ? '' : self.user.userApellidos));
		$('#userApellidos2').val((self.user.userApellidos2 == 'null' ? '' : self.user.userApellidos2));
		$('#role').val(self.user.role);
		if(self.user.enabled == 1) {
			$('#enabledUser').prop('checked', true);
		}
	},

	setExtenderInfoInputs() {
		let self = this;

        let welcome = self.extendedInfo !== undefined ? self.extendedInfo.welcome : "";
        let consejero = self.extendedInfo !== undefined ? self.extendedInfo.consejero : "";
		if(welcome == "0" && consejero == '1' && self.user.enabled == '1') {
			let JSONuser = sessionStorage['STCMBackEnd:user'];
			let user = JSON.parse(JSONuser);
			let userMail = user.email;

			self.deactivateUnwelcomeCounselor();
		}

		// Extended Info
		if(self.extendedInfo) {
			$('#nameUser').val(self.extendedInfo.name);
			$('#cataloging').val(self.extendedInfo.catalogacion);
			$('#numMisionesIncumplidas').val(self.extendedInfo.numMisionesIncumplidas);
			$('#userAccount').val(self.extendedInfo.userAccount);
			$('#useridentificador').val(self.extendedInfo.useridentificador);

			if(self.extendedInfo.welcome == '1') {
				if(self.extendedInfo.staff == 1) {
					$('#staff').prop('checked', true);
					$('#staff').parent().addClass('option-box-check-selected');
				}
				if(self.extendedInfo.consejero == 1) {
					$('#consejero').prop('checked', true);
					$('#consejero').parent().addClass('option-box-check-selected');
				}
			} else {
				$('#consejero').prop('disabled', true);
				if(self.extendedInfo.staff == 1) {
					$('#staff').prop('checked', true);
					$('#staff').parent().addClass('option-box-check-selected');
				}
			}

			$('#communicationEmail').val(self.extendedInfo.validationEmail); // =mailToNotify
			$('#communicationTelf').val(self.extendedInfo.validationPhoneNumber);
			$('#pais').val(self.extendedInfo.country.toLowerCase());
			$('#idioma').val(self.extendedInfo.lenguage);
			$('#perfil').val(self.extendedInfo.profile);
			$('#perfil').attr('title', self.extendedInfo.profile);
			$('#estadoPerf').val(self.extendedInfo.questionEstado);
			$('#edadPerf').val(self.extendedInfo.questionEdadFecha);
			$('#generoPerf').val(self.extendedInfo.questionGenero);
			$('#nsePerf').val(self.extendedInfo.questionABI);
			$('#numLogins').val(self.extendedInfo.tryLogin);
			if(self.extendedInfo.tryLogin > 0) {
				$('#btn_numLogins').prop('disabled', false);
			}

			$('#btn_numLogins').off().on('click', function() {
				$('#numLogins').val('0');
				$('#btn_numLogins').prop('disabled', true);
			});
		}

		removeLoader();
	},

	setBotsConfigInputs() {
		let self = this;

		if(self.botConfig && self.botConfig.enabled == 1) {
			$('#directLineSecret').val(self.botConfig.directLineSecret);
			$('#botId').val(self.botConfig.botId);
			$('#botUser').val(self.botConfig.botUser);
			$('#numVecesNoMatch').val(self.botConfig.numVecesNoMatch);
			$('#textoNoMatch').val(self.botConfig.textoNoMatch);
			$('#userNotificarNoMatch').val(self.botConfig.userNotificarNoMatch);
			$('#textoNotificarNoMatch').val(self.botConfig.messageNotifNoMatch);

			if(self.botConfig.enabled == 1) {
				$('#enabled').prop('checked', true);
			}

			if(self.botConfig.SaludoInicial == 1) {
				$('#saludoInicial').prop('checked', true);
			}
		}
	},

	setVoiceAssistantConfigInputs() {
		let self = this;

		if(self.voiceAssistant.enabled == '1') {
			// Se hace visible la obligatoriedad de inputs del asistente de voz
			$('.voiceAssisSpan').show();

			$('#voiceAssisEnabled').prop('checked', true);
			$('#voiceAssistantUser').val(self.voiceAssistant.voiceAssisUser);
			$('#paisVoiceAssis').val(self.voiceAssistant.country);
			$('#genderVoiceAssis').val(self.voiceAssistant.gender);

			if(self.voiceAssistant.applyGreeting == '1') {
				$('#voiceAssisSaludoInicial').prop('checked', true);
				$('#textGreetingContainer').show();
			} else {
				$('#textGreetingContainer').hide();
			}

			$('#textGreeting').val(self.voiceAssistant.textGreeting);
			$('#voiceAssisNumVecesNoMatch').val(self.voiceAssistant.numVecesNoMatch);
			$('#voiceAssisTextoNoMatch').val(self.voiceAssistant.textoNoMatch);
			$('#voiceAssisTextoContactNotice').val(self.voiceAssistant.texttouser);

			if(self.voiceAssistant.notificationType == 'user') {
				$('#notificationTypeUser').prop('checked', true);
				$('#notificationTypeUser').parent().addClass('option-box-check-selected');
			} else if(self.voiceAssistant.notificationType == 'mail') {
				$('#notificationTypeMail').prop('checked', true);
				$('#notificationTypeMail').parent().addClass('option-box-check-selected');
			} else if(self.voiceAssistant.notificationType == 'videocall') {
				$('#voiceAssisTextoNotificarNoMatchContainer').hide();
				$('#notificationTypeVideo').prop('checked', true);
				$('#notificationTypeVideo').parent().addClass('option-box-check-selected');
			}

			$('#voiceAssisUserNotificarNoMatch').val(self.voiceAssistant.userNotificarNoMatch);
			$('#voiceAssisTextoNotificarNoMatch').val(self.voiceAssistant.textoNotificarNoMatch);
		} else {
			// Se oculta la obligatoriedad de inputs de asistente de voz
			$('.voiceAssisSpan').hide();
		}
	},

	sendData() {
		let self = this;

		// Verificación de e-mail de notificación
		let mailToNotify = $('#communicationEmail').val().trim();
		let phoneToNotify = $('#communicationTelf').val().trim();
		let valiEmailNoti = false;

		if((mailToNotify != '' && pf.utils.validateEmail(mailToNotify)) || mailToNotify == '') {
			$('#communicationEmail').removeClass('is-invalid');
			$('[for="communicationEmail"]').removeClass('is-invalid');
			valiEmailNoti = true;
		} else {
			$('#communicationEmail').addClass('is-invalid');
			$('[for="communicationEmail"]').addClass('is-invalid');
			valiEmailNoti = false;
		}

		if(!valiEmailNoti) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let groups = [];
		for(let i = 0; i < self.groups.length; i++) {
			groups.push(self.groups[i].id);
		}

		// Comprobar checkboxs
		if($('#saludoInicial').prop('checked')) {
			$('#saludoInicial').val(1);
		} else {
			$('#saludoInicial').val(0);
		}

		if($('#enabledUser').prop('checked')) {
			$('#enabledUser').val(1);
		} else {
			$('#enabledUser').val(0);
		}

		if($('#enabled').prop('checked')) {
			$('#enabled').val(1);
		} else {
			$('#enabled').val(0);
		}

		if($('#staff').prop('checked')) {
			$('#staff').val(1);
		} else {
			$('#staff').val(0);
		}

		if($('#consejero').prop('checked')) {
			$('#consejero').val(1);
		} else {
			$('#consejero').val(0);
		}

		let userNew = {
			email: $('#email').val(),
			nameUser: $('#nameUser').val(),
			userApellidos: $('#userApellidos').val(),
			userApellidos2: $('#userApellidos2').val(),
			role: $('#role').val(),
			enabled: $('#enabledUser').val(),
			participants: groups,
			participantsOld: self.groupsOld
		};

		let extendedInfoNew = null;
		if(self.extendedInfo) {
			extendedInfoNew = {
				consejero: $('#consejero').val(),
				expirationDate: self.extendedInfo.expirationDate,
				name: $('#nameUser').val(),
				numMisionesIncumplidas: $('#numMisionesIncumplidas').val(),
				registered: self.extendedInfo.registered,
				staff: $('#staff').val(),
				stamp: self.extendedInfo.stamp,
				token: self.extendedInfo.token,
				userAccount: $('#userAccount').val(),
				userApellidos: $('#userApellidos').val(),
				userApellidos2: $('#userApellidos2').val(),
				userEmail: self.extendedInfo.userEmail,
				userIdentificador: $('#useridentificador').val(),
				userNombre: $('#userNombre').val(),
				userPass: self.extendedInfo.userPass,
				welcome: self.extendedInfo.welcome,
				country: $('#pais').val(),
				language: $('#idioma').val(),
				mailToNotify: mailToNotify,
				phoneToNotify: phoneToNotify,
				profile: $('#perfil').val(),
				questionEstado: $('#estadoPerf').val(),
				questionEdadFecha: $('#edadPerf').val(),
				questionGenero: $('#generoPerf').val(),
				questionABI: $('#nsePerf').val(),
				tryLogin: $('#numLogins').val()
			};
		} else {
			extendedInfoNew = {};
		}

		let botConfigNew = {
			idUserOrGroup: self.user.id,
			directLineSecret: $('#directLineSecret').val(),
			botId: $('#botId').val(),
			isGroup: '0',
			enabled: $('#enabled').val(),
			botUser: $('#botUser').val(),
			numVecesNoMatch: ($('#numVecesNoMatch').val() == '' ? '0' : $('#numVecesNoMatch').val()),
			textoNoMatch: $('#textoNoMatch').val().trim(),
			userNotificarNoMatch: $('#userNotificarNoMatch').val(),
			messageNotifNoMatch: $('#textoNotificarNoMatch').val(),
			SaludoInicial: $('#saludoInicial').val()
		};

		let notificationType = 'user';
		if($('#notificationTypeMail').prop('checked')) {
			notificationType = 'mail';
		} else if($('#notificationTypeVideo').prop('checked')) {
			notificationType = 'videocall';
		}

		// Configuración de asistente de voz
		let voiceAssistantNew = {
			enabled: ($('#voiceAssisEnabled').prop('checked') ? '1' : '0'),
			dictionary: self.voiceAssistantNew.dictionary,
			voiceAssisUser: $('#voiceAssistantUser').val(),
			country: $('#paisVoiceAssis').val(),
			gender: $('#genderVoiceAssis').val(),
			applyGreeting: ($('#voiceAssisSaludoInicial').prop('checked') ? '1' : '0'),
			textGreeting: $('#textGreeting').val().trim(),
			numVecesNoMatch: $('#voiceAssisNumVecesNoMatch').val(),
			textoNoMatch: $('#voiceAssisTextoNoMatch').val().trim(),
			texttouser: $('#voiceAssisTextoContactNotice').val().trim(),
			notificationType: notificationType,
			userNotificarNoMatch: $('#voiceAssisUserNotificarNoMatch').val(),
			textoNotificarNoMatch: $('#voiceAssisTextoNotificarNoMatch').val().trim()
		};

		// Control de inputs obligatorios del asistente de voz
		let voiceAssistantEmpty = false;

		// Saludo si es aplicable
		if(voiceAssistantNew.enabled == '1' && voiceAssistantNew.applyGreeting == '1' && voiceAssistantNew.textGreeting == '') {
			$('#textGreeting').addClass('is-invalid');
			$('[for="textGreeting"]').addClass('is-invalid');
			voiceAssistantEmpty = true;
		} else {
			$('#textGreeting').removeClass('is-invalid');
			$('[for="textGreeting"]').removeClass('is-invalid');
		}

		// Número de veces no match
		if(voiceAssistantNew.enabled == '1' && voiceAssistantNew.numVecesNoMatch == '') {
			$('#voiceAssisNumVecesNoMatch').addClass('is-invalid');
			$('[for="voiceAssisNumVecesNoMatch"]').addClass('is-invalid');
			voiceAssistantEmpty = true;
		} else {
			$('#voiceAssisNumVecesNoMatch').removeClass('is-invalid');
			$('[for="voiceAssisNumVecesNoMatch"]').removeClass('is-invalid');
		}

		// Texto "no match" para el usuario
		if(voiceAssistantNew.enabled == '1' && voiceAssistantNew.textoNoMatch == '') {
			$('#voiceAssisTextoNoMatch').addClass('is-invalid');
			$('[for="voiceAssisTextoNoMatch"]').addClass('is-invalid');
			voiceAssistantEmpty = true;
		} else {
			$('#voiceAssisTextoNoMatch').removeClass('is-invalid');
			$('[for="voiceAssisTextoNoMatch"]').removeClass('is-invalid');
		}

		// Texto aviso de contacto
		if(voiceAssistantNew.enabled == '1' && voiceAssistantNew.texttouser == '') {
			$('#voiceAssisTextoContactNotice').addClass('is-invalid');
			$('[for="voiceAssisTextoContactNotice"]').addClass('is-invalid');
			voiceAssistantEmpty = true;
		} else {
			$('#voiceAssisTextoContactNotice').removeClass('is-invalid');
			$('[for="voiceAssisTextoContactNotice"]').removeClass('is-invalid');
		}

		if(voiceAssistantEmpty) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

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

		let parameters = {
			userAdminMail: userMail,
			user: JSON.stringify(self.user),
			userNew: JSON.stringify(userNew),
			extendedInfo: JSON.stringify(self.extendedInfo),
			extendedInfoNew: JSON.stringify(extendedInfoNew),
			botConfig: JSON.stringify(self.botConfig),
			botConfigNew: JSON.stringify(botConfigNew),
			voiceAssistant: JSON.stringify(self.voiceAssistant),
			voiceAssistantNew: JSON.stringify(voiceAssistantNew),
			country: $('#pais').val(),
			language: $('#idioma').val(),
			userAdmin: self.userAdmin
		};
		ajaxComunCallWithCallback('editUser', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.errorUsers == 'overflow') {
					let errorTitle = pf.const.language.RSC2;
					let errorContent = pf.const.language.RSC1254;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				} else {
					let alertTitle = pf.const.language.RSC78;
					let alertText = pf.const.language.RSC106;
					let alertBtn = pf.const.language.RSC132;
					pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
						window.location.href = '#!usuarios';
					});
				}
			}
		});
	},

	clickEvents(data, type = null) {
		let self = this;

		if(type) {
			self.userType = type;
		}

		self.userClick = data;

		switch(self.userType) {
			case 'userBot':
				$('#botUser').val(self.userClick.id);
				$('#botUserName').text(self.userClick.nameUser);
				break;

			case 'userNotif':
				$('#userNotificarNoMatch').val(self.userClick.id);
				$('#userNotificarNoMatchName').text(self.userClick.nameUser);
				break;

			case 'bots':
				$('#directLineSecret').val(self.userClick.directLine);
				$('#botId').val(self.userClick.botName);
				break;

			case 'rol':
				$('#role').val(self.userClick.role);
				self.roleChange();
				break;

			case 'addGroups':
				let newGroups = [];

				for(let i = 0; i < data.length; i++) {
					// buscar rol en el grupo
					var role = 'participante';
					for(let j = 0; j < self.groups.length; j++) {
						if(self.groups[j].id == data[i].idGroup) {
							role = 'Admin';
						}
					}

					newGroups.push({
						id: data[i].idGroup,
						jid: data[i].jidUser,
						name: data[i].groupName,
						nameVisual: data[i].name,
						role: role
					});
				}

				self.groups = newGroups;
				self.crewObject.groups = self.groups;
				TableGroupsUser.setEvents(self.groups, 'divGroupsTable', 'editUsers');
				break;

			// Eliminar usuario de grupo
			case 'removeGroup':
				self.groups.splice(data, 1);
				self.crewObject.groups = self.groups;
				TableGroupsUser.setEvents(self.groups, 'divGroupsTable', 'editUsers');
				break;

			// Seleccionar país
			case 'country':
				$('#pais').val(data.isocode);
				break;

			// Seleccionar perfil
			case 'perfil':
				$('#perfil').val(data.id);
				$('#perfil').attr('title', data.id);
				break;

			// Diccionario
			case 'dictionaries':
				$('#dictionary').val(data.description);
				self.voiceAssistantNew.dictionary = data.idDictionary;
				break;

			// Usuario de asistente de voz
			case 'userVoiceAssistant':
				$('#voiceAssistantUser').val(data.id);
				$('#voiceAssistantName').text(data.nameUser);
				break;

			// Seleccionar país para asistente de voz
			case 'countryVoiceAssis':
				$('#paisVoiceAssis').val(data.isocode);
				break;

			// Usuario a notificar de asistente de voz
			case 'userNotifVoiceAssistant':
				$('#voiceAssisUserNotificarNoMatch').val(data.id);
				$('#voiceAssisUserNotificarNoMatchName').text(data.nameUser);
				break;
		}
	},

	isUserForgotten() {
		let self = this;

		let parameters = {
			email: self.user.email
		};
		ajaxComunCallWithCallback('isUserForgotten', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let icon = '';
				let title = '';
				if(ajaxReturn.result == 'true') {
					icon = `<span>${pf.const.language.RSC992}</span>`;
					self.forget = 1;
					title = pf.const.language.RSC992;
				} else {
					icon = stcmbackend.svg.personXWithoutColor + `<span class="d-none d-xl-inline">${pf.const.language.RSC986}</span>`;
					self.forget = 0;
					title = pf.const.language.RSC986;
				}
				$('#forget').html(icon);
				$('#forget').attr('title', title);

				// Control de spinner
				self.loaders.isUserForgotten = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	forgetUser() {
		let self = this;

		// Email de usuario administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;

		let parameters = {
			email: self.user.email,
			forget: self.forget,
			userMail: userMail
		};
		ajaxComunCallWithCallback('forgetUser', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				window.location.href = '#!usuarios';
			}
		});
	},

	disabledCPG() {
		let self = this;

		let parameters = {
			email: self.user.email,
			idCPG: self.idCPG
		};
		ajaxComunCallWithCallback('disabledCPG', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				window.location.href = '#!usuarios';
			}
		});
	},

	getDetallePagosByUser() {
		let self = this;

		let parameters = {
			user: self.user.email
		};
		ajaxComunCallWithCallback('getDetallePagosByUser', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result == '') {
					ajaxReturn.result = [];
				}

				self.pagosTable(ajaxReturn.result);

				// Control de spinner
				self.loaders.getDetallePagosByUser = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	pagosTable(pagos) {
		let excelTitle = pf.const.language.RSC16;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC348}">${pf.const.language.RSC348}</th>
					<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
					<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
					<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
					<th scope="col" title="${pf.const.language.RSC1334}">${pf.const.language.RSC1334}</th>
					<th scope="col" title="${pf.const.language.RSC1335}">${pf.const.language.RSC1335}</th>
					<th scope="col" title="${pf.const.language.RSC506}">${pf.const.language.RSC506}</th>
					<th scope="col" title="${pf.const.language.RSC1633}">${pf.const.language.RSC1633}</th>
					<th scope="col" title="${pf.const.language.RSC1336}">${pf.const.language.RSC1336}</th>
				</tr>
			</thead>

			<thead class="filtersPagos">
				<tr>
					<td>concepto</td>
					<td>fecha</td>
					<td>valor</td>
					<td>estado</td>
					<td>exportado</td>
					<td>fechaExportado</td>
					<td>cobrado</td>
					<td>noCobrable</td>
					<td>fechaCobrado</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = pagos.length;
		for(let i = 0; i < size; i++) {
			// El valor de estado cambia segun si es o no cobrable
			let estado = pf.const.language[pagos[i].status];
			if(pagos[i].noCobrable == '1') {
				estado = pagos[i].motivoNoCobrable;
			}

			table += `
				<tr>
					<td class="text-truncate" title="${pagos[i].concepto}">${pagos[i].concepto}</td>
					<td class="text-truncate" title="${pagos[i].fecha}">${pagos[i].fecha}</td>
					<td class="text-center" title="${pagos[i].valor}">${pagos[i].valor}</td>
					<td class="text-truncate" title="${estado}">${estado}</td>
					<td class="text-center">
						<span class="d-none">${(pagos[i].exported == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(pagos[i].exported == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${pagos[i].fechaExported}">${pagos[i].fechaExported}</td>
					<td class="text-center">
						<span class="d-none">${(pagos[i].cobrado == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(pagos[i].cobrado == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						<span class="d-none">${(pagos[i].noCobrable == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(pagos[i].noCobrable == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${pagos[i].fechaCobro}">${pagos[i].fechaCobro}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'exportado' || title == 'cobrado' || title == 'noCobrable') {
				value = optionsSelectAllYesNo();
			}

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

		let dataTable = $('#remunerationTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '50px', targets: 2},
				{width: '85px', targets: 3},
				{width: '85px', targets: 6},
				{width: '100px', targets: 7}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			order: [1, 'desc']
		});

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

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

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

	tableSegResult() {
		let self = this;

		let excelTitle = pf.const.language.RSC1769;

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

				<thead class="filterstableSegResult">
					<tr>
						<td>segmentacion</td>
						<td>email</td>
						<td>resultado</td>
					</tr>
				</thead>

				<tbody>
		`;

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

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

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

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

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

		let tableSegResultTables = $('#tableSegResultTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(tableSegResultTables, 'filterstableSegResult');

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

	tableDevsResult() {
		let self = this;

		let excelTitle = pf.const.language.RSC1993;
		// self.devicesResult

		let table = `
			<table id="tableDevsResultTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC558}">${pf.const.language.RSC558}</th>
						<th scope="col" title="${pf.const.language.RSC1424}">${pf.const.language.RSC1424}</th>
					</tr>
				</thead>

				<thead class="filterstableDevResult">
					<tr>
						<td>token</td>
						<td>platform</td>
					</tr>
				</thead>

				<tbody>
		`;

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

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableDevsResultTables, 'filterstableDevResult');

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

	tableDataBankResult() {
		let self = this;

		let excelTitle = pf.const.language.RSC1869;

		let table = `
			<table id="tableDataBankResultTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1870}">${pf.const.language.RSC1870}</th>
						<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
						<th scope="col" title="${pf.const.language.RSC1871}">${pf.const.language.RSC1871}</th>
					</tr>
				</thead>

				<thead class="filterstableDataBankResult">
					<tr>
						<td>account</td>
						<td>active</td>
						<td>stamp</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.dataBankResult.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="${i}">
					<td class="text-truncate" title="${self.dataBankResult[i].userAccount}">${self.dataBankResult[i].userAccount}</td>
					<td class="text-center">
						<span class="d-none">${(self.dataBankResult[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.dataBankResult[i].active == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center" title="${self.dataBankResult[i].stamp}">${self.dataBankResult[i].stamp}</td>
				</tr>
			`;
		}

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

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

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

			if(title == 'active') {
				value = optionsSelectAllYesNo();
			}

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

		let tableDataBankResultTables = $('#tableDataBankResultTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '50px', targets: 1},
				{width: '150px', targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(tableDataBankResultTables, 'filterstableDataBankResult');

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

	tableExtDataResult() {
		let self = this;

		let table = `
			<table id="tableExtDataResultTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="name">Nombre</th>
						<th scope="col" title="key">Clave</th>
						<th scope="col" title="value">Valor</th>
					</tr>
				</thead>
				<thead class="filterstableDataExtDataResult">
					<tr>
						<td>name</td>
						<td>key</td>
						<td>value</td>
					</tr>
				</thead>
				<tbody>
		`;

		let size = 0;
        if (self.extendedInfo && self.extendedInfo.extendedData && Array.isArray(self.extendedInfo.extendedData)) {
            size = self.extendedInfo.extendedData.length;
        }
		for(let i = 0; i < size; i++) {
			let eData = self.extendedInfo.extendedData[i];
			if (eData && eData.name && eData.key && eData.value) {
				table += `
					<tr data-id="${i}">
						<td class="text-truncate" title="${eData.name}">${eData.name}</td>
						<td class="text-truncate" title="${eData.key}">${eData.key}</td>
						<td class="text-truncate" title="${eData.value}">${eData.value}</td>
					</tr>
				`;
			}
		}

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

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

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

		let tableExtDataResultTables = $('#tableExtDataResultTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '50px', targets: 1},
				{width: '150px', targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2660,
				className: 'd-none',
				title: pf.const.language.RSC2660,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(tableExtDataResultTables, 'filterstableDataExtDataResult');
	},

	deactivateUnwelcomeCounselor() {
		let self = this;

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

		let parameters = {
			adminEmail: adminEmail,
			email: self.extendedInfo.userEmail,
			username: self.extendedInfo.userNombre,
			userapellidos: self.extendedInfo.userApellidos,
			userapellidos2: self.extendedInfo.userApellidos2,
			name: self.extendedInfo.name,
			useridentificador: self.extendedInfo.userIdentificador,
			useraccount: self.extendedInfo.userAccount,
			consejero: '0',
			numMisionesIncumplidas: self.extendedInfo.numMisionesIncumplidas,
			staff: self.extendedInfo.staff,
			country: self.extendedInfo.country,
			language: self.extendedInfo.lenguage,
			mailToNotify: self.extendedInfo.mailToNotify,
			profile: self.extendedInfo.profile,
			questionEstado: self.extendedInfo.questionEstado,
			questionEdadFecha: self.extendedInfo.questionEdadFecha,
			questionGenero: self.extendedInfo.questionGenero,
			questionABI: self.extendedInfo.questionABI,
			tryLogin: self.extendedInfo.tryLogin
		};
		ajaxComunCallWithCallback('deactivateUnwelcomeCounselor', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				//
			}
		});
	}
};