let KPISurveysController = {
	event: '',
	surveyID: '',
	surveyName: '',
	questionID: '',
	questionName: '',
	answerCode: '',
	answerName: '',
	margin: '',
	nQuestions: '',
	data: [],
	speedingData: [],
	tableFlag: false,
	missions: null,
	stampMission: '',

	reset() {
		let self = this;

		self.event = '';
		self.surveyID = '';
		self.surveyName = '';
		self.questionID = '';
		self.questionName = '';
		self.answerCode = '';
		self.answerName = '';
		self.margin = '';
		self.nQuestions = '';
		self.data = [];
		self.speedingData = [];
		self.tableFlag = false;
		self.missions = null;
		self.stampMission = '';
	},

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

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

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

		// Añadir opciones
		let nav = `
			<div class="d-flex justify-content-end row m-0">
				<!-- Misión -->
					<div class="input-group new-input-style new-input-style-action-page ma-le-5">
						<input id="mission" type="text" class="form-control" aria-label="mission" placeholder="${pf.const.language.RSC14}" title="${pf.const.language.RSC14}" disabled>
						<div class="input-group-append d-block">
							<button id="searchMission" type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#missionsContainer">
								${stcmbackend.svg.threeDotsWithoutMargin}
							</button>
						</div>
					</div>

				<!-- Pregunta -->
					<div class="input-group new-input-style new-input-style-action-page ma-le-5">
						<input id="question" type="text" class="form-control" aria-label="question" placeholder="${pf.const.language.RSC111}" title="${pf.const.language.RSC111}" disabled>
						<div class="input-group-append d-block">
							<button id="searchQuestionB" type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#modalContainer" disabled>
								${stcmbackend.svg.threeDotsWithoutMargin}
							</button>
						</div>
					</div>

				<!-- Respuestas -->
					<div class="input-group new-input-style new-input-style-action-page ma-le-5">
						<input id="answer" type="text" class="form-control" aria-label="answer" placeholder="${pf.const.language.RSC127}" title="${pf.const.language.RSC127}" disabled>
						<div class="input-group-append d-block">
							<button id="searchAnswer" type="button" class="btn btn-outline-secondary" data-toggle="modal" data-target="#modalContainer" disabled>
								${stcmbackend.svg.threeDotsWithoutMargin}
							</button>
						</div>
					</div>

				<!-- Inputs numéricos -->
				<!-- Margen -->
				<div class="form-group wi-100 mb-0 p-0 ma-le-5">
					<input id="margin" type="number" class="form-control he-32" placeholder="${pf.const.language.RSC1832}" title="${pf.const.language.RSC1832}" min="0" max="100" disabled>
				</div>

				<!-- Nº preguntas -->
				<div class="form-group wi-100 mb-0 p-0 ma-le-5">
					<input id="nQuestions" type="number" class="form-control he-32" placeholder="${pf.const.language.RSC1833}" title="${pf.const.language.RSC1833}" min="2" max="99" disabled>
				</div>

				<!-- Botones -->
				<button id="load" type="button" class="btn btn-nav d-flex align-items-center ma-le-5" title="${pf.const.language.RSC46}" disabled>
					${stcmbackend.svg.arrowRepeat}
					<span class="ml-1">${pf.const.language.RSC46}</span>
				</button>
			</div>
		`;

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

		// Botones secundarios
		$('#load').addClass('secondary-button');

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

		self.loadLang();
		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();
	},

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

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		// Modal tabla de misiones
		$('#searchMission').click(function() {
			if(self.missions) {
				$('#missionsContainer').modal('toggle');
			} else {
				let JSONuser = sessionStorage['STCMBackEnd:user'];
				let user = JSON.parse(JSONuser);
				let idCliente = user.idCliente;

				// Parámetro de cliente
				let parameters = {
					idCliente: idCliente
				}
				ajaxComunCallWithCallback('getAllMisiones', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.missions = ajaxReturn.result;

						// Modal de misiones de encuesta
						self.renderSurveyMissions();
					}
				});
			}
		});

		// Input de margen
		$('#margin').on('blur', function() {
			let val = $('#margin').val();
			if(val < 0) {
				val = 0;
				$('#margin').val(val);
			} else if(val > 100) {
				val = 100;
				$('#margin').val(val);
			}
			self.margin = val;
		});

		// Llamada a servicio
		$('#load').on('click', function() {
			let red_herringControl = self.questionID;
			if(self.answerCode.includes('SQ')) {
				red_herringControl = self.questionID + self.answerCode;
			}

			let parameters = {
				stampMision: self.stampMission,
				survey: self.surveyID,
				red_herringControl: red_herringControl,
				red_herringControlValue: self.answerCode,
				speedingMarginPercent: self.margin,
				numFlatliningControl: self.nQuestions
			};
			ajaxComunCallWithCallback('getAnalyticsKPIS', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					self.speedingData = ajaxReturn.result_speeding;
					let result_speeding_tokens = [];
					if(self.speedingData !== '') {
						let sizeRS = self.speedingData.length;
						for(let i = 0; i < sizeRS; i++) {
							result_speeding_tokens.push(self.speedingData[i].token);
						}
					}

					let result_flatlining_tokens = [];
					if(ajaxReturn.result_flatlining !== '') {
						let sizeRF = ajaxReturn.result_flatlining.length;
						for(let i = 0; i < sizeRF; i++) {
							result_flatlining_tokens.push(ajaxReturn.result_flatlining[i].token);
						}
					}

					let result_red_herring_tokens = [];
					if(ajaxReturn.result_red_herring !== '') {
						let sizeRRH = ajaxReturn.result_red_herring.length;
						for(let i = 0; i < sizeRRH; i++) {
							result_red_herring_tokens.push(ajaxReturn.result_red_herring[i].token);
						}
					}

					self.data = ajaxReturn.result_participantes;
					let sizeRP = self.data.length;
					for(let i = 0; i < sizeRP; i++) {
						if(result_speeding_tokens.indexOf(self.data[i].token) !== -1) {
							self.data[i]['speeding'] = '1';
						} else {
							self.data[i]['speeding'] = '0';
						}

						if(result_flatlining_tokens.indexOf(self.data[i].token) !== -1) {
							self.data[i]['flatlining'] = '1';
						} else {
							self.data[i]['flatlining'] = '0';
						}

						if(result_red_herring_tokens.indexOf(self.data[i].token) !== -1) {
							self.data[i]['herring'] = '1';
						} else {
							self.data[i]['herring'] = '0';
						}
					}

					self.renderTable();
				}
			});
		});
	},

	renderSurveyMissions() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
					<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
					<th scope="col" title="${pf.const.language.RSC171}">${pf.const.language.RSC171}</th>
					<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
					<th scope="col" title="${pf.const.language.RSC172}">${pf.const.language.RSC172}</th>
					<th scope="col" title="${pf.const.language.RSC145}">${pf.const.language.RSC145}</th>
				</tr>
			</thead>

			<thead class="filtersMissions">
				<tr>
					<td>idmision</td>
					<td>encuesta</td>
					<td>fechainicio</td>
					<td>horainicio</td>
					<td>fechafin</td>
					<td>horafin</td>
					<td>importe</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let size = self.missions.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.missions[i].country) == -1 || self.missions[i].isSurvey != '1') {
				continue;
			}

			let startDateTime = self.missions[i].fechahorainicio.split('#');
			let startDateArray = startDateTime[0].split('/');
			let startDate = startDateArray[2] + '-' + startDateArray[1] + '-' + startDateArray[0];
			let startTimeArray = startDateTime[2].split(':');
			let startTime = startDateTime[1] + ':' + startTimeArray[0];

			let endDateTime = self.missions[i].fechahorafin.split('#');
			let endDateArray = endDateTime[0].split('/');
			let endDate = endDateArray[2] + '-' + endDateArray[1] + '-' + endDateArray[0];
			let endTimeArray = endDateTime[2].split(':');
			let endTime = endDateTime[1] + ':' + endTimeArray[0];

			table += `
				<tr class="c-pointer missionSelect" data-mission="${self.missions[i].stampMision}" data-name="${self.missions[i].idmision}" data-survey="${self.missions[i].sid}">
					<td class="text-truncate" title="${self.missions[i].idmision}">${self.missions[i].idmision}</td>
					<td class="text-truncate" title="${self.missions[i].sid}">${self.missions[i].sid}</td>
					<td class="text-truncate" title="${startDate}">${startDate}</td>
					<td class="text-truncate" title="${startTime}">${startTime}</td>
					<td class="text-truncate" title="${endDate}">${endDate}</td>
					<td class="text-truncate" title="${endTime}">${endTime}</td>
					<td class="text-truncate" title="${self.missions[i].importe}">${self.missions[i].importe}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let ObjetiveTable = $('#tableMissions').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '60px', targets: 1},
				{width: '90px', targets: 2},
				{width: '80px', targets: 3},
				{width: '90px', targets: 4},
				{width: '80px', targets: 5},
				{width: '50px', targets: 6}
			],
			autoWidth: false,
			aaSorting: []
		});

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

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

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filtersMissions');

		self.eventsSurveyMissions();

		$('#tableMissions').on('draw.dt', function() {
			self.eventsSurveyMissions();
		});
	},

	eventsSurveyMissions() {
		let self = this;

		$('.missionSelect').off().on('click', function() {
			$('#missionsContainer').modal('toggle');

			let stampMision = $(this).data('mission');
			let nameMission = $(this).data('name');
			let survey = $(this).data('survey');

			self.surveyID = survey;
			self.stampMission = stampMision;

			$('#mission').val(nameMission);
			$('#mission').attr('title', nameMission);
			$('#searchQuestionB').prop('disabled', false);
			$('#margin').prop('disabled', false);
			$('#load').prop('disabled', false);

			// Limpieza de preguntas, respuestas, margen y número de preguntas
			self.questionID = '';
			self.questionName = '';
			$('#question').val('');
			$('#question').attr('title', '');
			self.answerCode = '';
			self.answerName = '';
			$('#answer').val('');
			$('#answer').attr('title', '');
			$('#margin').val('');
			self.margin = '';
			$('#nQuestions').val('');
			self.nQuestions = '';

			// Modal tabla de preguntas de encuesta
			let questions = new TableQuestions(0, 'KPISurvey', self.surveyID);
			// Con parámetro de inicio en true para saber el número de preguntas
			questions.init = true;
			questions.setEvents('tableModal');
			$('#searchQuestionB').off().on('click', function() {
				self.event = 'question';
				// Con parámetro de inicio en false
				questions.init = false;
				questions.setEvents('tableModal');
			});
		});
	},

	renderTable() {
		let self = this;

		if(self.tableFlag) {
			$('#registers').dataTable().fnDestroy();
		} else {
			self.tableFlag = true;
		}

		$('#resultTableContainer').show();
		$('#export').prop('disabled', false);

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
			<th scope="col" title="${pf.const.language.RSC1626}">${pf.const.language.RSC1626}</th>
			<th scope="col" title="${pf.const.language.RSC1627}">${pf.const.language.RSC1627}</th>
		`;
		let nameSurnameFilter = `
			<td>name</td>
			<td>surname1</td>
			<td>surname2</td>
		`;

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

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
					<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
					<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC1902}">${pf.const.language.RSC1902}</th>
					<th scope="col" title="${pf.const.language.RSC1903}">${pf.const.language.RSC1903}</th>
					<th scope="col" title="KPI">KPI</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					${nameSurnameFilter}
					<td>email</td>
					<td>age</td>
					<td>gender</td>
					<td>state</td>
					<td>country</td>
					<td>averagetime</td>
					<td>usertime</td>
					<td>speed</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.data[i].questionPais) === -1) {
				continue;
			}

			let kpiSurvey = '';

			let kpiSurveySpan = '';

			if(self.data[i].speeding === '1') {
				kpiSurveySpan = ' speeding ';
				kpiSurvey += `<div class="d-inline-block" title="speeding">${stcmbackend.svg.speedometer2WithoutColor}</div>`;
			}

			if(self.data[i].flatlining === '1') {
				kpiSurveySpan += ' flatlining ';
				kpiSurvey += `<div class="d-inline-block" title="flatlining">${stcmbackend.svg.alignStartWithoutColor}</div>`;
			}

			if(self.data[i].herring === '1' && self.answerCode != '') {
				kpiSurveySpan += ' red_herring ';
				kpiSurvey += `<div class="d-inline-block" title="red_herring">${stcmbackend.svg.flagFillWithoutColor}</div>`;
			}

			// No todos los usuarios tienen runTime/runTimeAVG (result participantes length != result speeding length)
			// Hay que buscar el token correspondiente al usuario (participantes) y ver si existe en speeding
			let runTime = '';
			let runTimeAVG = '';

			let tokenParticipante = self.data[i].token;

			for(let j = 0; j < self.speedingData.length; j++) {
				if(tokenParticipante == self.speedingData[j].token) {
					runTime = self.speedingData[j].runTime;
					runTimeAVG = self.speedingData[j].runTimeAVG;
				}
			}

			let nameSurnameBody = `
				<td class="text-truncate" title="${(self.data[i].userNombre || '')}">${(self.data[i].userNombre || '')}</td>
				<td class="text-truncate" title="${(self.data[i].userApellidos || '')}">${(self.data[i].userApellidos || '')}</td>
				<td class="text-truncate" title="${(self.data[i].userApellidos2 || '')}">${(self.data[i].userApellidos2 || '')}</td>
			`;

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

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${(self.data[i].token || '')}">${(self.data[i].token || '')}</td>
					<td class="text-truncate" title="${(self.data[i].questionEdad || '')}">${(self.data[i].questionEdad || '')}</td>
					<td class="text-truncate" title="${(self.data[i].questionGenero || '')}">${(self.data[i].questionGenero || '')}</td>
					<td class="text-truncate" title="${(self.data[i].questionEstado || '')}">${(self.data[i].questionEstado || '')}</td>
					<td class="text-truncate" title="${(self.data[i].questionPais || '')}">${(self.data[i].questionPais || '')}</td>
					<td class="text-truncate" title="${(runTimeAVG || '')}">${(runTimeAVG || '')}</td>
					<td class="text-truncate" title="${(runTime || '')}">${(runTime || '')}</td>
					<td class="text-center">
						<span class="d-none">${kpiSurveySpan}</span>
						${kpiSurvey}
					</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 == 'speed') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let columnDefs = [
			{width: '40px', targets: 4},
			{width: '60px', targets: 5},
			{width: '40px', targets: 7},
			{width: '60px', targets: 8},
			{width: '60px', targets: 9},
			{width: '60px', targets: 10}
		];

		// Control GDPR
		if(gdpr == '1') {
			columnDefs = [
				{width: '40px', targets: 1},
				{width: '60px', targets: 2},
				{width: '40px', targets: 4},
				{width: '60px', targets: 5},
				{width: '60px', targets: 6},
				{width: '60px', targets: 7}
			];
		}

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

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

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

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

	clickSurvey(data) {
		let self = this;

		switch(self.event) {
			case 'question':
				self.questionID = data.id;
				self.questionName = data.name;
				$('#question').val(data.name);
				$('#question').attr('title', data.name);

				// Limpieza de respuestas
				self.answerCode = '';
				self.answerName = '';
				$('#answer').val('');
				$('#answer').attr('title', '');

				// Array de preguntas sin respuestas
				let withoutAnswer = ['2', '3', '5', 'O', 'B', 'A', '|', 'R', '7', 'J', 'S', 'T', 'U', 'D'];

				if(withoutAnswer.indexOf(data.type.toString()) === -1) {
					$('#searchAnswer').prop('disabled', false);

					// Modal tabla de respuestas de pregunta
					let answers = new TableAnswers(0, 'KPISurvey', self.surveyID, self.questionID);
					$('#searchAnswer').off().on('click', function() {
						self.event = 'answer';
						answers.setEvents('tableModal');
					});
				} else {
					$('#searchAnswer').prop('disabled', true);
				}

				break;
			case 'answer':
				self.answerCode = data.code;
				self.answerName = data.answer;
				$('#answer').val(data.answer);
				$('#answer').attr('title', data.answer);
				break;
		}
	},

	numOfQuestions(number) {
		let self = this;

		$('#nQuestions').prop('disabled', false);

		// Input de número de preguntas
		$('#nQuestions').off().on('blur', function() {
			let val = $('#nQuestions').val();
			if(val < 2) {
				val = 2;
				$('#nQuestions').val(val);
			} else if(val > number) {
				val = number;
				$('#nQuestions').val(val);
			}
			self.nQuestions = val;
		});
	}
};