let StepByStepSummaryController = {
	user: null,
	language: '',
	idProject: '',
	project: '',
	idProfiling: [],
	numberRecords: '',
	targetsSurvey: '',
	leader: '',
	missionsCount: '',
	participants: '',
	filter: '',
	tokensArray: [],
	participantsFiltered: [],
	poolFlag: false,
	importParticipants: '',
	projectMisions: '',
	loaded: false,
	misionRotations: [],
	userInitalRotations: [],
	countryFilter: '',
	sidRelations: [],
	idSegmentations: '',
	selectedSegmentations: '',
	xmpp_domain: '',
	loaders: {},
	cpgList: '',
	advisorsInProject: [],

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		// id del proyecto
		self.idProject = sessionStorage.getItem('idProjectSBS');
		self.project = '';
		// Nº de registros
		self.numberRecords = '0';
		// Encuestas
		// id de encuesta de perfilación
		self.idProfiling = sessionStorage.getItem('idProfilingSBS').split(',');
		// Objetivos de la encuesta
		self.targetsSurvey = JSON.parse(sessionStorage.getItem('targetsSurveySBS'));
		// Lider del proyecto
		self.leader = JSON.parse(sessionStorage.getItem('leaderSBS'));
		// Nº de misiones
		self.missionsCount = '1';
		// Misiones
		//self.projectMisions = JSON.parse(sessionStorage.getItem('projectMisionsSBS'));
		self.projectMisions = [];
		self.participants = '';
		self.filter = '';
		self.tokensArray = [];
		self.participantsFiltered = [];
		self.poolFlag = false;
		self.importParticipants = '';
		self.loaded = false;
		self.misionRotations= [];
		self.userInitalRotations= [];
		// País del proyecto
		self.countryFilter = sessionStorage.getItem('countryProjectSBS');
		self.sidRelations = [];
		// Segmentaciones
		// id de segmentaciones
		self.idSegmentations = sessionStorage.getItem('segmentationSBS').split(',');
		// Objetivos de las segmentaciones
		self.selectedSegmentations = JSON.parse(sessionStorage.getItem('selectedSegmentationsSBS'));
		self.xmpp_domain = '';
		self.loaders = {
			getCMBPProjects: false,
			getAllUsers: false,
			getAnswersSurvey: false
		};
		// CPG's
		self.cpgList = sessionStorage.getItem('cpgListSBS');
		self.advisorsInProject = [];
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.xmpp_domain = config.xmpp_domain;

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

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

		self.loadLang();

		// Petición de datos de proyecto
		self.requestProject();

		// Petición de respuestas/participantes de encuesta
		self.LoadSurveyParticipants();

		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();
	},

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

		// Títulos comunes
		StepByStepSharedController.commonTitles();
	},

	applyEvents() {
		let self = this;

		// Volver a criterios
		$('#backSBS').on('click', function() {
			window.location.href = '#!step_by_step_criterion_edit';
		});

		// Importar participantes
		$('#import').on('click', function() {
			$('#inputFile').trigger('click');
		});

		// Detectar fichero de participantes
		$('#inputFile').change(function(evt) {
			self.importUsers(evt);
		});

		// Añadir usuario a odjetivo
		$('#add').on('click', function() {
			if(self.poolFlag) {
				$('#tableObjectives').dataTable().fnDestroy();
			} else {
				self.poolFlag = true;
			}
			self.renderPool();
		});

		// Ejecutar metodologías sobre resultados
		$('#nextSBS').on('click', function() {
			if(self.participantsFiltered.length > 0) {
				if(self.project.ListaDistribucion == 1 && self.participantsFiltered.length < 2) {
					let successTitle = pf.const.language.RSC394;
					let successContent = pf.const.language.RSC526;
					pf.utils.showInfoDialog(successTitle, successContent);
				} else {
					self.executeMethodologiesOnResults();
				}
			} else {
				let successTitle = pf.const.language.RSC394;
				let successContent = pf.const.language.RSC527;
				pf.utils.showInfoDialog(successTitle, successContent);
			}
		});
	},

	// Petición de todos los proyectos
	requestProject() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.project = ajaxReturn.result[0];

				let relations = self.project.sidRelations.split(',');
				for(let i = 0; i < relations.length; i++) {
					let rel = relations[i].split('#');
					if(rel[1] === undefined) {
						self.sidRelations.push('&');
					} else {
						self.sidRelations.push(rel[1].replace('amp;', ''));
					}
				}
			}
		});
	},

	LoadSurveyParticipants() {
		let self = this;

		let parameters = {
			country: self.countryFilter,
			consejero: 1,
			enabled: 1,
			staff: 1
		};
		ajaxComunCallWithCallback('getAllUsers', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.participants = ajaxReturn.result;

				// Petición de participantes del proyecto
				self.requestProjectParticipants();
			}
		});
	},

	LoadSurveyParticipantsFiltered() {
		let self = this;

		let columname = '';
		let ageQuery = '';
		let queryTotal = '';

		let sizeT = self.targetsSurvey.length;
		for(let t = 0; t < sizeT; t++) {
			let query = '';
			let size = self.targetsSurvey[t].length;
			for(let i = 0; i < size; i++) {
				if(self.targetsSurvey[t][i].type == 'M') {
					if(self.targetsSurvey[t][i].code.length > 0 && self.targetsSurvey[t][i].code[0] != '') {
						if(query === '') {
							query += ' survey_' + self.idProfiling[t] + '.' + self.targetsSurvey[t][i].columnName + self.targetsSurvey[t][i].code + ' IN (\'Y\') ';
						} else {
							query += 'AND survey_' + self.idProfiling[t] + '.' + self.targetsSurvey[t][i].columnName + self.targetsSurvey[t][i].code + ' IN (\'Y\') ';
						}
					}
				} else if(self.targetsSurvey[t][i].type != 'K') {
					if(self.targetsSurvey[t][i].code.length > 0 && self.targetsSurvey[t][i].code[0] != '') {
						if(self.targetsSurvey[t][i].type == '2') {
							columname = self.targetsSurvey[t][i].columnName;
							ageQuery = ' edad in (\'' + self.targetsSurvey[t][i].code.toString().replace(/,/g, '\',\'') + '\')';
						} else {
							if(query === '') {
								query += ' survey_' + self.idProfiling[t] + '.' + self.targetsSurvey[t][i].columnName + ' IN (\'' + self.targetsSurvey[t][i].code.toString().replace(/,/g, '\',\'') + '\') ';
							} else {
								query += 'AND survey_' + self.idProfiling[t] + '.' + self.targetsSurvey[t][i].columnName + ' IN (\'' + self.targetsSurvey[t][i].code.toString().replace(/,/g, '\',\'') + '\') ';
							}
						}
					}
				} else {
					let sizeK = self.targetsSurvey[t][i].valuesSQ.length;
					for(let j = 0; j < sizeK; j++) {
						let valuesSQArray = self.targetsSurvey[t][i].valuesSQ[j].split('|');
						let columnNameK = valuesSQArray[0];
						if(self.targetsSurvey[t][i].code[columnNameK].length > 0 && self.targetsSurvey[t][i].code[columnNameK][0] != '') {
							if(query === '') {
								query += ' survey_' + self.idProfiling[t] + '.' + columnNameK + ' IN (\'' + self.targetsSurvey[t][i].code[columnNameK].toString().replace(/,/g, '\',\'') + '\') ';
							} else {
								query += 'AND survey_' + self.idProfiling[t] + '.' + columnNameK + ' IN (\'' + self.targetsSurvey[t][i].code[columnNameK].toString().replace(/,/g, '\',\'') + '\') ';
							}
						}
					}
				}
			}

			query += '#';

			queryTotal += query;
		}
		queryTotal = queryTotal.substring(0, queryTotal.length - 1);

		let inclusive = sessionStorage['proyect_inclusiveSBS'];

		if(queryTotal === '() ') {
			queryTotal = '';
		}

		let parameters = {
			survey: self.idProfiling.toString().replace(/\,/g, '#'),
			whereQuery: queryTotal,
			maxRows: self.numberRecords,
			havingQuery: ageQuery,
			havingQueryColumnID: columname,
			inclusivo: inclusive,
			cpgList: self.cpgList
		};
		ajaxComunCallWithCallback('getAnswersSurveyByQuery', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.filter = ajaxReturn.result;

				let size = self.filter.length;
				for(let i = 0; i < size; i++) {
					if(self.tokensArray.indexOf(self.filter[i].token) == -1) {
						self.tokensArray.push(self.filter[i].token);
						self.participantsFiltered.push(self.filter[i]);
					}
				}

				// Tabla de participantes filtrados
				self.getAllRotacionesProject();
			}
		});
	},

	getAnswersSurveyByQuerySegmentation() {
		let self = this;

		let queryTotal = '';
		let values = '';

		let sizeS = self.selectedSegmentations.length;
		for(let s = 0; s < sizeS; s++) {
			let query = '';
			let inQuery = '';
			let size = self.selectedSegmentations[s].catalogacion.length;
			for(let i = 0; i < size; i++) {
				query = 'RESULT IN ';

				if(self.selectedSegmentations[s].catalogacion[i].include == '1') {
					if(inQuery !== '') {
						inQuery += ',';
					}
					inQuery += '\'' + self.selectedSegmentations[s].catalogacion[i].name + '\'';

					if(values !== '') {
						values += ',';
					}
					values += '\'' + self.selectedSegmentations[s].catalogacion[i].name + '\'';
				}
			}

			if(inQuery !== '') {
				query += '(' + inQuery + ')#';

				queryTotal += query;
			} else {
				query = '#';

				queryTotal += query;
			}
		}
		queryTotal = queryTotal.substring(0, queryTotal.length - 1);

		let inclusive = sessionStorage['proyect_inclusive'];

		let parameters = {
			segmentation: self.idSegmentations.toString().replace(/\,/g, '#'),
			whereQuery: queryTotal,
			maxRows: self.numberRecords,
			inclusivo: inclusive,
			values: values,
			cpgList: self.cpgList
		};
		ajaxComunCallWithCallback('getAnswersSurveyByQuerySegmentation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.filter = ajaxReturn.result;

				let size = self.filter.length;
				for(let i = 0; i < size; i++) {
					if(self.tokensArray.indexOf(self.filter[i].token) == -1) {
						self.tokensArray.push(self.filter[i].token);
						self.participantsFiltered.push(self.filter[i]);
					}
				}

				// Tabla de participantes filtrados
				self.getAllRotacionesProject();
			}
		});
	},

	// Petición de participantes del proyecto
	requestProjectParticipants() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjectsParticipantes', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Array de asesores que ya están en el proyecto
				self.advisorsInProject = [];
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					self.advisorsInProject.push(ajaxReturn.result[i].email);
				}

				let searchAlgorithm = sessionStorage.getItem('searchAlgorithmSBS');
				if(searchAlgorithm === 'survey') {
					// Petición de respuestas/participantes de encuesta filtrados
					self.LoadSurveyParticipantsFiltered();
				} else if(searchAlgorithm === 'segmentation') {
					// Petición de respuestas/participantes de segmentación filtrados
					self.getAnswersSurveyByQuerySegmentation();
				} else if(searchAlgorithm === 'total') {
					// Todos los usuarios menos staff
					let size = self.participants.length;
					for(let i = 0; i < size; i++) {
						if(self.participants[i].staff == '0' && self.participants[i].enabled == '1') {
							self.tokensArray.push(self.participants[i].email);

							let obj = {
								consejero: self.participants[i].consejero,
								profile: self.participants[i].profile,
								token: self.participants[i].email,
								userName: self.participants[i].id,
								userNameByMail: self.participants[i].id.replace('@', '.')
							};
							self.participantsFiltered.push(obj);
						}
					}

					// Tabla de participantes filtrados
					self.getAllRotacionesProject();
				}
			}
		});
	},

	renderParticipants() {
		let self = this;

		self.assignRotationsToUsers();

		let excelTitle = pf.const.language.RSC523;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC134}">${pf.const.language.RSC134}</th>
					<th scope="col" title="${pf.const.language.RSC1748}">${pf.const.language.RSC1748}</th>
					<th scope="col" title="${pf.const.language.RSC1404}">${pf.const.language.RSC1404}</th>
					<th scope="col" title="${pf.const.language.RSC124}">${pf.const.language.RSC124}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>mail</td>
					<td>profile</td>
					<td>segmentos</td>
					<td>Rotations</td>
					<td>counselor</td>
					<td>delete</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.participantsFiltered.length;
		if(size > 0) {
			$('#deleteAll').show();
		} else {
			$('#deleteAll').hide();
		}
		for(let i = 0; i < size; i++) {
			if(self.advisorsInProject.includes(self.participantsFiltered[i].token)) {
				continue;
			}

			let rotaciones = '';
			if(self.participantsFiltered[i].rotations) {
				self.participantsFiltered[i].rotations.forEach(rotation => {
					rotaciones+=rotation.description + ', ';
				});
				rotaciones = rotaciones.substring(0, rotaciones.length - 2);
			}

			let segments = self.participantsFiltered[i].segmentation || '';

			table += `
				<tr id="${self.participantsFiltered[i].token}">
					<td class="text-truncate" title="${self.participantsFiltered[i].token}">${self.participantsFiltered[i].token}</td>
					<td class="text-truncate" title="${(self.participantsFiltered[i].profile == undefined ? '' : self.participantsFiltered[i].profile)}">${(self.participantsFiltered[i].profile == undefined ? '' : self.participantsFiltered[i].profile)}</td>
					<td class="text-truncate" title="${segments}">${segments}</td>
					<td class="text-truncate" title="${rotaciones}">${rotaciones}</td>
					<td class="text-center">
						<span class="d-none">${(self.participantsFiltered[i].consejero == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.participantsFiltered[i].consejero == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer circle-container deleteParticipant">
							${stcmbackend.svg.trash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title === 'delete') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			} else if(title === 'counselor') {
				value = optionsSelectAllYesNo();
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '100px', targets: 1},
				{width: '70px', targets: 4},
				{width: '30px', orderable: false, targets: 5}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				filename: excelTitle,
				title: null,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

		self.tableEvents();

		$('#registers').on('draw.dt', function() {
			self.tableEvents();
		});
	},

	tableEvents() {
		let self = this;

		// Eliminar objetivo
		$('.deleteParticipant').off().on('click', function() {
			let token = $(this).parent().parent().attr('id');

			self.removeObjectives(token);
		});

		// Eliminar todos los objetivos
		$('#deleteAll').off().on('click', function() {
			self.participantsFiltered = [];
			self.tokensArray = [];

			// Recargar tabla de objetivos
			$('#registers').dataTable().fnDestroy();
			self.renderParticipants();
		});
	},

	removeObjectives(token) {
		let self = this;

		// Búsqueda y eliminación del token en el array de usuarios filtrados
		let size = self.participantsFiltered.length;
		for(let i = 0; i < size; i++) {
			if(self.participantsFiltered[i].token == token) {
				self.participantsFiltered.splice(i, 1);
				break;
			}
		}

		// Búsqueda y eliminación del token en el array de tokens
		let index = self.tokensArray.indexOf(token);
		self.tokensArray.splice(index, 1);

		// Recargar tabla de objetivos
		$('#registers').dataTable().fnDestroy();
		self.renderParticipants();
	},

	renderPool() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title="">
						<div class="div-global-selection">
							<input type="checkbox" class="globalSelection">
						</div>
					</th>
					<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC124}">${pf.const.language.RSC124}</th>
				</tr>
			</thead>

			<thead class="filtersPoll">
				<tr>
					<td>selector</td>
					<td>name</td>
					<td>mail</td>
					<td>id</td>
					<td>counselor</td>
				</tr>
			</thead>

			<tbody>
		`;

		let empty = true;
		let size = self.participants.length;
		for(let i = 0; i < size; i++) {
			if(self.advisorsInProject.includes(self.participants[i].email)) {
				continue;
			}

			if(self.tokensArray.indexOf(self.participants[i].email) == -1 && self.participants[i].enabled == 1) {
				empty = false;
				let userName = self.participants[i].id.replace('@', '.');
				table += `
					<tr id="${self.participants[i].email}" class="c-pointer check-select">
						<td class="text-center">
							<div class="div-single-selection">
								<input type="checkbox" class="selection">
							</div>
						</td>
						<td class="text-truncate" title="${userName}">${userName}</td>
						<td class="text-truncate" title="${self.participants[i].email}">${self.participants[i].email}</td>
						<td class="text-truncate" title="${self.participants[i].id}">${self.participants[i].id}</td>
						<td class="text-center">
							<span class="d-none">${(self.participants[i].consejero == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input type="checkbox" disabled ${(self.participants[i].consejero == '1' ? 'checked' : '')}>
						</td>
					</tr>
				`;
			}
		}

		if(empty) {
			$('#tableObjectives').removeClass('tRegs');
		} else {
			$('#tableObjectives').addClass('tRegs')
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'counselor') {
				value = optionsSelectAllYesNo();
			} else if(title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let tableObjectives = $('#tableObjectives').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '80px', targets: 4}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			tableObjectives.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableObjectives, 'filtersPoll');

		self.multiSelectTableEvents();

		$('#tableObjectives').on('draw.dt', function() {
			self.multiSelectTableEvents();
		});

		$('#addObjectives').off().on('click', function() {
			let addArrayToken = [];
			tableObjectives.destroy();
			$('#tableObjectives tr').each(function() {
				let cheked = $(this).find('.selection');
				if(cheked.prop('checked')) {
					let token = $(this).attr('id');
					addArrayToken.push(token);
				}
			});

			$('#closePool').trigger('click');

			let size = self.participants.length;
			for(let i = 0; i < size; i++) {
				if(addArrayToken.indexOf(self.participants[i].email) != -1) {
					self.tokensArray.push(self.participants[i].email);

					let obj = {
						consejero: self.participants[i].consejero,
						profile: self.participants[i].profile,
						token: self.participants[i].email,
						userName: self.participants[i].id,
						userNameByMail: self.participants[i].id.replace('@', '.')
					};
					self.participantsFiltered.push(obj);
				}
			}

			// Recargar tabla de objetivos
			$('#registers').dataTable().fnDestroy();
			self.renderParticipants();
		});
	},

	multiSelectTableEvents() {
		inputControl();

		// Selección por tr
		$('#tableObjectives tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			inputControl();
		});

		// Selección por input check
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelection').off().on('change', function() {
			if($('.globalSelection').prop('checked')) {
				$('.selection').prop('checked', true);
			} else {
				$('.selection').prop('checked', false);
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	},

	executeMethodologiesOnResults() {
		let self = this;

		let sParams = '[';
		let sizeP = self.participantsFiltered.length;
		for(let i = 0; i < sizeP; i++) {
			// En caso de importados sin sid
			if(self.participantsFiltered[i].userName == '') {
				let sid = self.participantsFiltered[i].token.replace('@', '.') + '@' + self.xmpp_domain;
				sParams += '["' + sid + '",';
			} else {
				sParams += '["' + self.participantsFiltered[i].userName.replace('\t', '') + '",';
			}
			sParams += '"' + self.participantsFiltered[i].token.replace('\t', '') + '"],';
		}
		sParams = sParams.substring(0, (sParams.length - 1));
		sParams += ']';

		let rotationArray = self.createUserRotationArray();

		let parameters = {
			id: self.idProject,
			participants: sParams,
			diffusionList: self.project.ListaDistribucion,
			ListaDistribucionID: self.project.ListaDistribucionID,
			admin: self.leader.id,
			adminEmail: self.leader.email,
			description: self.project.NombreProyecto,
			individualChat: self.project.ChatIndividual,
			groupChat: self.project.ChatGrupal,
			ChatGrupalID: self.project.ChatGrupalID,
			missionsCount: self.missionsCount,
			greeting: pf.const.language.RSC1258,
			greetingGroupChat: pf.const.language.RSC1259,
			greetingNewsGroupChat: pf.const.language.RSC1277,
			notificarInclusion: self.project.notificarInclusion,
			country: self.project.country,
			values: JSON.stringify(rotationArray)
		};
		ajaxComunCallWithCallback('executeMethodologiesOnResults', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC394;
				let successContent = pf.const.language.RSC528;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!proyectos';
			}
		});
	},

	// Importar participantes
	importUsers(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'
			});
			let index = 0;
			workbook.SheetNames.forEach(function(sheetName) {
				self.importParticipants = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

				// Comprobación de e-mails
				let checkEmails = true;
				for(let i = 0; i < self.importParticipants.length; i++) {
					if(!pf.utils.validateEmail(self.importParticipants[i][pf.const.language.RSC136])) {
						checkEmails = false;
					}
				}

				if(!checkEmails) {
					let alertTitle = pf.const.language.RSC316;
					let alertText = pf.const.language.RSC322;
					pf.utils.showInfoDialog(alertTitle, alertText);
				} else {
					self.participantsFiltered = [];
					self.tokensArray = [];

					let size = self.importParticipants.length;
					for(let i = 0; i < size; i++) {
						let object = {
							userNameByMail: self.importParticipants[i][pf.const.language.RSC68] || '',
							token: self.importParticipants[i][pf.const.language.RSC136],
							userName: self.importParticipants[i][pf.const.language.RSC366] || '',
							consejero: self.importParticipants[i][pf.const.language.RSC124] || '',
							profile: self.importParticipants[i][pf.const.language.RSC134] || '',
						}
						self.participantsFiltered.push(object);
						self.tokensArray.push(self.importParticipants[i][pf.const.language.RSC136]);
					}
					$('#registers').dataTable().fnDestroy();
					self.renderParticipants();
				}
				removeLoader();
				$('#inputFile').val(null);
			})
		};

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

		reader.readAsBinaryString(selectedFile);
	},

	getSelectedUsersRotacionesProject() {
		let self = this;

		let misionsParams = [];
		self.projectMisions.forEach(mision => {
			misionsParams.push({
				survey: mision.surveyId,
				idProject: self.idProject,
				mision: mision.stampMision
			})
		});

		let parameters = {
			misions: JSON.stringify(misionsParams)
		};
		ajaxComunCallWithCallback('getAllAsignedProjectRotaciones', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result.length != 0) {
					self.userInitalRotations = ajaxReturn.result[0].rotations;
				}
				if(ajaxReturn.result.length === 0 || ajaxReturn.result[0].rotations.length == 0) {
					self.loaded = true;
				}
				self.renderParticipants();
			}
		});
	},

	getAllRotacionesProject() {
		let self = this;

		let misionsParams = [];
		self.projectMisions.forEach(mision => {
			misionsParams.push({
				survey: mision.surveyId,
				idProject: self.idProject,
				mision: mision.stampMision
			})
		});

		let parameters = {
			misions: JSON.stringify(misionsParams)
		};
		ajaxComunCallWithCallback('getAllRotacionesProject', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.misionRotations = ajaxReturn.result;
				self.getSelectedUsersRotacionesProject();
			}
		});
	},

	assignRotation(rotIdx, usrIdx, rotArray) {
		let self = this;

		moduledRotIndex = rotIdx%rotArray.length;

		rotation = rotArray[moduledRotIndex];
		if(rotation.toAssign <= 0) {
			//condición de parada para evitar loop infinito (no debería darse el caso but anyway)
			if(usrIdx%rotArray.length -1 === moduledRotIndex) {
				return false;
			}

			return(self.assignRotation(rotIdx+1, usrIdx, rotArray));
		} else {
			if(!self.participantsFiltered[usrIdx].rotations) {
				self.participantsFiltered[usrIdx].rotations =[];
			}

			--rotation.toAssign;
			self.participantsFiltered[usrIdx].rotations.push(rotArray[moduledRotIndex]);

			return true;
		}
	},

	assignRotationsToUsers() {
		let self = this;

		if(!self.loaded) {
			self.participantsFiltered.forEach(participant => {
				let rotation = self.userInitalRotations.find(rot => rot.token == participant.token);
				if(!rotation) {
					self.loaded = true;
					self.assignRotationsToUsers();
					return;
				} else {
					if(!participant.rotations)
						participant.rotations =[]
					participant.rotations.push(rotation);
				}
			});

			self.loaded = true;
		} else {
			self.misionRotations.forEach(mision => {
				this.calculatePercentage(mision.rotations);
			});
			for(let i = 0; i < self.participantsFiltered.length; i++) {
				self.participantsFiltered[i].rotations = [];
				for(let j = 0; j < self.misionRotations.length; j++) {
					let valid = self.assignRotation(i,i,self.misionRotations[j].rotations);
					if(!valid) {
						return false;
					}
				}
			}
		}

		return true;
	},

	calculatePercentage(rotations) {
		let self = this;

		function u(c, total) {
			var real, natural;
			real = c * total + amortized;
			natural = Math.floor(real); // just to be on the safe side
			amortized = real - natural;
			return natural;
		}
		let total = self.participantsFiltered.length;
		let sum = 0;
		let amortized = 0;
		let i = 0;
		for(i = 0; i < rotations.length - 1; i++) {
			let percentatge = parseFloat(((rotations[i].porcentaje)/100).toFixed(2));
			numberToAssign = u(percentatge,total);
			rotations[i].assign = numberToAssign;
			rotations[i].toAssign = numberToAssign;
			sum += numberToAssign;
		}

		rotations[i].assign = total - sum;
		rotations[i].toAssign = total - sum;
	},

	createUserRotationArray() {
		let self = this;

		let resultArray = [];
		self.participantsFiltered.forEach(participant => {
			if(participant.rotations) {
				participant.rotations.forEach(rotation => {
					let rotString = `${self.idProject}#${rotation.stampMision}#${rotation.idrotation}#${rotation.sid}#${participant.token}`;
					resultArray.push(rotString)
				});
			}
		});
		return resultArray;
	}
};