class DocumentComparativoGeneratorController {
	constructor(values) {
		this.ajax = values.ajax;
		this.generalCharts = values.generalCharts;
		this.paramsWc = values.paramsWc;
		this.typeColors = values.typeColors;
		this.fontSize = values.fontSize;
		this.fontName = values.fontName;
		this.colorsRGB = values.colorsRGB;
		this.colorsHex = values.colorsHex;
		this.poll = values.poll;
		this.idPollArray = values.idPollArray;
		this.idPollNameArray = values.idPollNameArray;
		this.idProjectsArray = values.idProjectsArray;
		this.idMissionsArray = values.idMissionsArray;
		this.NameArrayIndex = values.NameArrayIndex;
		this.question = values.question;
		this.questionOrder = values.questionOrder;
		this.questionFlag = values.questionFlag;
		this.questionTitle = values.questionTitle;
		this.wordCloud = values.wordCloud;
		this.wordCloudURL = values.wordCloudURL;
		this.primaryColor = values.primaryColor;
		this.secundaryColor = values.secundaryColor;
		this.data = values.data;
		this.language = values.language;
		this.iChart = values.iChart;
		this.QuestQuantity = values.QuestQuantity;
		this.arrayPpt = values.arrayPpt;
		this.dataPpt = values.dataPpt;
		this.wcPpt = values.wcPpt;
		this.questionsPpt = values.questionsPpt;
		this.user = values.user;
		this.encuestasPpt = values.encuestasPpt;
		this.timestamp = values.timestamp;
		this.reports = values.reports;
		this.errorsReports = values.errorsReports;
		this.numPregPerf = values.numPregPerf;
		this.namePoll = values.namePoll;
		this.columnName = values.columnName;
		this.excelDataOpt = values.excelDataOpt;
		this.idReport = '';
		this.abort = false;
		this.chart = '';
		this.questionIdOut = values.questionIdOut;
		this.numberWordsWordcloud = values.numberWordsWordcloud;
	}

	start() {
		let self = this;

		self.executeReports();
	}

	executeReports() {
		let self = this;

		self.ajax = false;

		$('#show-generating-reports').css('visibility', 'visible');
		let idReport = Math.floor(Date.now() / 1000);
		self.idReport = idReport;
		let report = {
			name: self.namePoll,
			id: idReport,
			title: pf.const.language.RSC1379,
			subtitle: pf.const.language.RSC49,
			cancelButton: true
		}
		CardGeneratorController.addNotification(report);
		$(`#cancelDowload${self.idReport}`).off().on('click', (e)=>{
			e.preventDefault();
			self.cancelAjax();
		});
		setTimeout(function() {
			self.generateDocument();
		}, 500);
	}

	execSocialTools() {
		let self = this;

		let token = sessionStorage['STCMBackEnd:token'];
		let reqName = 'execSocialTools';
		let reqLabel = 'execSocialTools' + self.idReport;
		this.reqLabel = reqLabel;

		let form = new FormData();
		form.append('action', reqName);
		form.append('token', token);

		let reqData = {
			url: stcm.const.serverAPI,
			method: 'POST',
			timeout: stcm.const.AJAX_TIMEOUT,
			processData: false,
			mimeType: 'application/x-www-form-urlencoded',
			contentType: false,
			data: form
		};

		pf.ajax.request(reqLabel, reqData);
		$(document).off(reqLabel);
		$(document).on(reqLabel, function(event, response) {
			if(response.status === 'OK') {
				let resp = JSON.parse(response.resData.response);
				if(resp.status === 'OK') {
					self.generateDocument();
				} else if(!self.abort) {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = pf.const.language.RSC498;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					if(resp.result == 'Not authorized') {
						pf.ajax.setWindowLocationIndex();
					}
				}
			} else if(!self.abort) {
				let errorTitle = pf.const.language.RSC61;
				let errorContent = response.result;
				pf.utils.showInfoDialog(errorTitle, errorContent);
				if(response.result == 'Not authorized') {
					pf.ajax.setWindowLocationIndex();
				}
			}
		});
	}

	cancelAjax() {
		let self = this;

		self.ajax = true;
		self.abort = true;
		pf.ajax.abortRequest(this.reqLabel);
		CardGeneratorController.deleteNotification(this.idReport);
	}

	generateDocument() {
		let self = this;

		let token = sessionStorage['STCMBackEnd:token'];
		let idTenant = sessionStorage['STCMBackEnd:idTenant'];
		let survey = self.idPollArray;
		let reqName = 'requestComparativeWord';
		let reqLabel = 'requestComparativeWord' + self.idReport;
		this.reqLabel = reqLabel;

		let form = new FormData();
		self.paramsWc = [];
		form.append('action', reqName);
		form.append('token', token);
		form.append('idTenant', idTenant);
		form.append('colorsRGB', self.colorsRGB);
		form.append('colorsHex', self.colorsHex);
		form.append('survey', survey);
		form.append('user', self.user);
		form.append('timestamp', self.timestamp);
		form.append('numPregPerf', self.numPregPerf);
		form.append('questionIdOut', self.questionIdOut);

		if(self.reports.word || (!self.reports.ppt && self.reports.wc)) {
			let steps = pf.const.language.RSC50 + '<br>' + pf.const.language.RSC58;
			$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC547 + ' ' + pf.const.language.RSC536+ ' - '+self.namePoll);
			$(`#downloadCardText_${self.idReport}`).html(steps);

			let reqData = {
				url: stcm.const.serverAPI,
				method: 'POST',
				timeout: stcm.const.AJAX_TIMEOUT_REPORTS,
				processData: false,
				mimeType: 'application/x-www-form-urlencoded',
				contentType: false,
				data: form
			};

			pf.ajax.request(reqLabel, reqData);
			$(document).off(reqLabel);

			$(document).on(reqLabel, function(event, response) {
				try {
					if(response.status === 'OK') {
						let resp = JSON.parse(response.resData.response);
						self.generalCharts = resp.resume;

						if(resp.status === 'OK') {
							let steps = pf.const.language.RSC51 + '<br>'+ pf.const.language.RSC52;
							$(`#downloadCardText_${self.idReport}`).html(steps);

							let imagesWC = [];
							let i = 0;
							function searchWC(i) {
								if(!self.ajax) {
									if(resp.wordCloud[i] == 'yes') {
										let position = resp.result[i].length - 1;
										let rest = 1;
										while(resp.result[i][position] == null) {
											position = resp.result[i].length - rest;
											rest++;
										}
										let params = [self.idPollArray[self.idPollArray.length - 1], resp.result[i][position].question];
										self.paramsWc.push(params);

										// Palabras (1) o frases (2)
										let wordsOrPhrases = 2;

										if(resp.result[i][position].data[0].tipoPregunta == 'S' || resp.result[i][position].data[0].tipoPregunta == 'Q') {
											wordsOrPhrases = 1;
										}

										let src = self.wordCloudURL + '/?a=' + self.idPollArray[self.idPollArray.length - 1] + '&b=' + resp.result[i][position].question + '&c=&d=&e=&f=&g=' + self.primaryColor + '&h=' + self.secundaryColor + '&i=' + wordsOrPhrases + '&j=' + self.numberWordsWordcloud;

										window.addEventListener('message', loadWordCloud);
										function loadWordCloud(event) {
											let url_base64jp = event.data;
											imagesWC.push(url_base64jp);
											window.removeEventListener('message', loadWordCloud);
											i++;
											if(i < resp.wordCloud.length) {
												searchWC(i);
											} else {
												self.endWordCloud(resp, imagesWC);
											}
										}
										$('#result_word_cloud').attr('src', src);
									} else {
										imagesWC.push('no');
										i++;
										if(i < resp.wordCloud.length) {
											searchWC(i);
										} else {
											self.endWordCloud(resp, imagesWC);
										}
									}
									return true;
								}
							}
							searchWC(i);
						} else if(!self.abort) {
							self.errorsReports.word = true;
							self.generatePpt();
						}
					} else if(!self.ajax && !self.abort) {
						self.errorsReports.word = true;
						self.generatePpt();
					}
				} catch(e) {
					if(!self.abort) {
						self.errorsReports.word = true;
						self.generatePpt();
					}
				}
			});
		} else {
			self.generatePpt();
		}
	}

	endWordCloud(data, wc) {
		let self = this;

		let wcString = '[';
		for(let i = 0; i < wc.length; i++) {
			wcString += '"' + wc[i] + '",';
		}
		wcString = wcString.substring(0, wcString.length - 1);
		wcString += ']';

		data.result.forEach(function(currentValue, index, arr) {
			currentValue.forEach(function(currentValue, index, arr) {
				if(currentValue != null) {
					if(currentValue.answers.labels[0] === 'Others') {
						//
					} else {
						delete currentValue.data;
					}
				}
			});
		});

		let reqName = 'printComparativeWord';
		let reqLabel = 'printComparativeWord' + self.idReport;
		this.reqLabel = reqLabel;
		let dataResult = JSON.stringify(data.result);
		let encuestas = JSON.stringify(data.encuestas);
		let questions = JSON.stringify(data.questions);
		let paramsWc = JSON.stringify(self.paramsWc);
		let token = sessionStorage['STCMBackEnd:token'];
		let idTenant = sessionStorage['STCMBackEnd:idTenant'];

		let form = new FormData();
		form.append('action', reqName);
		form.append('token', token);
		form.append('idTenant', idTenant);
		form.append('wordCloud', wcString);
		form.append('data', dataResult);
		form.append('encuestas', encuestas);
		form.append('questions', questions);
		form.append('colorsRGB', self.colorsRGB);
		form.append('colorsHex', self.colorsHex);
		form.append('user', self.user);
		form.append('generalCharts', JSON.stringify(self.generalCharts));
		form.append('paramsWc', paramsWc);
		form.append('timestamp', JSON.stringify(self.timestamp));
		form.append('isWc', self.reports.wc);
		form.append('isWord', self.reports.word);

		let steps = pf.const.language.RSC53 + '<br>' + pf.const.language.RSC54;
		$(`#downloadCardText_${self.idReport}`).html(steps);

		let reqData = {
			url: stcm.const.serverAPI,
			method: 'POST',
			timeout: stcm.const.AJAX_TIMEOUT_REPORTS,
			processData: false,
			mimeType: 'application/x-www-form-urlencoded',
			contentType: false,
			data: form
		};

		pf.ajax.request(reqLabel, reqData);
		$(document).off(reqLabel);
		$(document).on(reqLabel, function(event, response) {
			try {
				let resp = JSON.parse(response.resData.response);
				if(resp.status === 'OK') {
					self.generatePpt();
				} else if(!self.abort) {
					self.errorsReports.word = true;
					self.generatePpt();
				}
			} catch(e) {
				if(!self.abort) {
					self.errorsReports.word = true;
					self.generatePpt();
				}
			}
		});
	}

	deleteWord(filename) {
		let token = sessionStorage['STCMBackEnd:token'];
		let reqName = 'deleteWord';
		let reqLabel = 'deleteWord' + self.idReport;
		this.reqLabel = reqLabel;

		let form = new FormData();
		form.append('action', reqName);
		form.append('token', token);
		form.append('filename', filename);

		let reqData = {
			url: stcm.const.serverAPI,
			method: 'POST',
			timeout: stcm.const.AJAX_TIMEOUT,
			processData: false,
			mimeType: 'application/x-www-form-urlencoded',
			contentType: false,
			data: form
		};
		pf.ajax.request(reqLabel, reqData);
		$(document).off(reqLabel);

		$(document).on(reqLabel, function(event, response) {
			//
		});
	}

	generatePpt() {
		let self = this;

		if(self.reports.ppt) {
			let token = sessionStorage['STCMBackEnd:token'];
			let idTenant = sessionStorage['STCMBackEnd:idTenant'];
			let survey = self.idPollArray;
			let reqName = 'requestComparativeAllGraphs';
			let reqLabel = 'requestComparativeAllGraphs' + self.idReport;
			this.reqLabel = reqLabel;

			self.paramsWc = [];

			let steps = pf.const.language.RSC50 + '<br>' + pf.const.language.RSC58;
			$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC547 + ' ' + pf.const.language.RSC538+ ' - '+self.namePoll);
			$(`#downloadCardText_${self.idReport}`).html(steps);

			let form = new FormData();
			form.append('action', reqName);
			form.append('token', token);
			form.append('idTenant', idTenant);
			form.append('colorsRGB', self.colorsRGB);
			form.append('colorsHex', self.colorsHex);
			form.append('survey', survey);
			form.append('numPregPerf', self.numPregPerf);
			form.append('questionIdOut', self.questionIdOut);

			let reqData = {
				url: stcm.const.serverAPI,
				method: 'POST',
				timeout: stcm.const.AJAX_TIMEOUT_REPORTS,
				processData: false,
				mimeType: 'application/x-www-form-urlencoded',
				contentType: false,
				data: form
			};

			pf.ajax.request(reqLabel, reqData);
			$(document).off(reqLabel);

			$(document).on(reqLabel, function(event, response) {
				try {
					if(response.status === 'OK') {
						let resp = JSON.parse(response.resData.response);
						if(resp.status === 'OK') {
							self.dataPpt = resp.result;
							self.wcPpt = resp.wordCloud;
							self.questionsPpt = resp.questions;
							self.encuestasPpt = resp.encuestas;
							let resume = resp.resume;
							resp = resp.result;

							self.dataPpt = resp;

							// Cantidad de preguntas
							self.QuestQuantity = resp.length;
							self.iChart = 0;
							self.arrayPpt = [];

							// Crear graficos generales
							function totalChart(labels, data, title, i) {
								//Seleccion colores
								let quantity = labels.length;
								let gradient = [];
								if(quantity == 2) {
									gradient = self.colorsHex;
								} else {
									if(self.typeColors == 1) {
										gradient = generateColors(self.colorsHex[0], self.colorsHex[1], quantity);
									} else {
										gradient = arrayColors(self.colorsHex, quantity);
									}
								}

								//Definir options
								let options = {
									responsive: true,
									maintainAspectRatio: true,
									legend: {
										display: true,
										position: 'right',
										onClick: false
									},
									scales: {
										xAxes: [{
											stacked: true,
											ticks: {
												display: true,
												autoSkip: false
											}
										}],
										yAxes: [{
											display: false,
											stacked: true,
											ticks: {
												fontSize: 16,
												max: 100
											}
										}]
									},
									title: {
										display: true,
										text: title,
										fontSize: 16
									},
									plugins: {
										datalabels: {
											color: 'white',
											font: {
												weight: 'bold'
											},
											clamp: true,
											formatter(value, context) {
												return value;
											}
										}
									}
								};

								// Crear grafica
								Chart.defaults.global.defaultFontSize = parseInt(self.fontSize);
								Chart.defaults.global.defaultFontFamily = self.fontName;
								let ctx = $('#result_graph_ppt');
								let datasets = [];
								for(let i = 0; i < labels.length; i++) {
									let dataset = {
										borderWidth: 2,
										data: data[i],
										label: labels[i],
										backgroundColor: gradient[i]
									}
									datasets.push(dataset);
								}

								self.chart = new Chart(ctx, {
									// The type of chart we want to create
									type: 'bar',
									// The data for our dataset
									data: {
										labels: self.encuestasPpt,
										datasets: datasets
									},
									// Configuration options go here
									options: options
								});

								setTimeout(function() {
									let url_base64jp = document.getElementById('result_graph_ppt').toDataURL('image/jpg');
									self.generalCharts.push(url_base64jp);
									self.chart.destroy();
									let n = i + 1;

									if(n == 2) {
										totalChart(resume.age.labels, resume.age.values, 'Edad (%)', n);
									} else if(n == 3) {
										totalChart(resume.states.labels, resume.states.values, 'Estados (%)', n);
									} else {
										// LLamada a la generacion de graficos, enviamos la data y la cantidad de preguntas
										self.graphsPpt(resp, self.QuestQuantity);
									}
								}, 1000);
							}
							self.generalCharts = [];

							totalChart(resume.gender.labels, resume.gender.values, 'Género (%)', 1);
						} else if(!self.abort) {
							self.errorsReports.ppt = true;
							self.generateExcel();
						}
					} else if(!self.ajax && !self.abort) {
						self.errorsReports.ppt = true;
						self.generateExcel();
					}
				} catch(e) {
					if(!self.abort) {
						self.errorsReports.ppt = true;
						self.generateExcel();
					}
				}
			});
		} else {
			self.generateExcel();
		}
	}

	// Gráfica para .ppt
	graphsPpt(object, QuestQuantity) {
		let self = this;

		try {
			let positionId = object[self.iChart].length - 1;
			let steps = pf.const.language.RSC51 + '<br>' + pf.const.language.RSC52;
			$(`#downloadCardText_${self.idReport}`).html(steps);

			let pptJson = {
				data: {
					imgAnswer: '',
					imgGender: '',
					imgAge: '',
					imgStates: '',
				}
			};

			// Una vez por pregunta, pasamos la data y el tipo de grafica
			function recursiveGraphPpt(object, n) {
				if(!self.ajax) {
					let graph = '';
					let url_base64jpWC = '';

					let dataObject = [];
					// Obtenemos objeto con la data del tipo de grafico
					switch(n) {
						case 0:
							for(let x = 0; x < object[self.iChart].length; x++) {
								if(object[self.iChart][x] === null) {
									dataObject.push(0);
								} else {
									dataObject.push(object[self.iChart][x].answers);
								}
							}
							break;
						case 1:
							for(let x = 0; x < object[self.iChart].length; x++) {
								if(object[self.iChart][x] === null) {
									dataObject.push(0);
								} else {
									dataObject.push(object[self.iChart][x].gender);
								}
							}
							break;
						case 2:
							for(let x = 0; x < object[self.iChart].length; x++) {
								if(object[self.iChart][x] === null) {
									dataObject.push(0);
								} else {
									dataObject.push(object[self.iChart][x].age);
								}
							}
							break;
						case 3:
							for(let x = 0; x < object[self.iChart].length; x++) {
								if(object[self.iChart][x] === null) {
									dataObject.push(0);
								} else {
									dataObject.push(object[self.iChart][x].states);
								}
							}
							break;
					}

					// Comprobamos si la data lleva WordCloud
					let positionDataObject = dataObject.length - 1;
					if(dataObject[positionDataObject].labels[0] === 'Others') {
						// WORDCLOUD
						// Los valores de survey y answer los recogerá de los atributos
					} else {
						// GRÁFICA
						// Miramos la cantidad de etiquetas que hay
						let quantity = dataObject[positionDataObject].labels.length;

						// COLORES
						let gradient = [];
						if(quantity == 2) {
							gradient = [self.colorsHex[0], self.colorsHex[1]];
						} else {
							if(self.typeColors == 1) {
								gradient = generateColors(self.colorsHex[0], self.colorsHex[1], quantity);
							} else {
								gradient = arrayColors(self.colorsHex, quantity);
							}
						}

						let yAxe = [{
							display: false,
							stacked: true,
							ticks: {
								fontSize: 16,
								max: 100
							}
						}];

						// Obtenemos el canvas donde printara la grafica
						let ctx = document.getElementById('result_graph_ppt').getContext('2d');

						// generamos el objeto con la data de la grafica
						let data = {};
						data['labels'] = self.encuestasPpt;
						data['datasets'] = [];

						let arrayGen = ['Masculino', 'Femenino'];
						// Bucle para obtener todas las etiquetas
						for(let i = 0; i < quantity; i++) {
							let label = dataObject[positionDataObject].labels[i];
							if(n === 1) {
								label = arrayGen[i];
							}

							// COLORES
							let color;
							color = gradient[i];
							let obj = {
								label: label,
								data: [],
								backgroundColor: color,
								borderWidth: 2
							};
							// Generacion grafica stacked, sacamos las series de la grafica
							switch(n) {
								case 0:
									for(let j = 0; j < object[self.iChart].length; j++) {
										if(object[self.iChart][j] === null) {
											obj.data.push(0);
										} else {
											obj.data.push(object[self.iChart][j].answers.datasets.data[i]);
										}
									}
									break;
								case 1:
									for(let j = 0; j < object[self.iChart].length; j++) {
										if(object[self.iChart][j] === null) {
											obj.data.push(0);
										} else {
											obj.data.push(object[self.iChart][j].gender.datasets.data[i]);
										}
									}
									break;
								case 2:
									for(let j = 0; j < object[self.iChart].length; j++) {
										if(object[self.iChart][j] === null) {
											obj.data.push(0);
										} else {
											obj.data.push(object[self.iChart][j].age.datasets.data[i]);
										}
									}
									break;
								case 3:
									for(let j = 0; j < object[self.iChart].length; j++) {
										if(object[self.iChart][j] === null) {
											obj.data.push(0);
										} else {
											obj.data.push(object[self.iChart][j].states.datasets.data[i]);
										}
									}
									break;
							}

							// Insertamos el objeto con las series en el dataset de las graficas
							data['datasets'].push(obj);
						}
						// Opciones de las graficas
						let options = {
							responsive: true,
							maintainAspectRatio: true,
							legend: {
								display: true,
								position: 'right',
								onClick: false
							},
							title: {
								display: true,
								text: '',
								fontSize: 16,
								padding: 20
							},
							scales: {
								xAxes: [{
									stacked: true,
									ticks: {
										display: true,
										autoSkip: false
									}
								}],
								yAxes: yAxe
							},
							tooltips: {
								enabled: false
							},
							plugins: {
								datalabels: {
									color: 'white',
									font: {
										weight: 'bold'
									},
									formatter(value, context) {
										return value;
									}
								}
							}
						}

						// Titulo de las graficas
						switch(n) {
							case 0:
								// ANSWERS
								options.title.text = pf.const.language.RSC150 + ' (%)';
								break;
							case 1:
								// GENDER
								options.title.text = pf.const.language.RSC151 + ' (%)';
								break;
							case 2:
								// AGE
								options.title.text = pf.const.language.RSC152 + ' (%)';
								break;
							case 3:
								// STATES
								options.title.text = pf.const.language.RSC153 + ' (%)';
								break;
							default:
								break;
						}

						Chart.defaults.global.defaultFontSize = parseInt(self.fontSize);
						Chart.defaults.global.defaultFontFamily = self.fontName;

						// generamos la grafica
						self.chart = new Chart(ctx, {
							type: 'bar',
							data: data,
							options: options
						});
					}

					/*Get image of canvas element*/
					setTimeout(function() {
						let url_base64jp = document.getElementById('result_graph_ppt').toDataURL('image/jpg');
						// Comprobamos que tipo de grafica hemos generado
						switch(n) {
							case 0:
								// Comprobamos si hay una grafica o wordCloud
								let positionWC = dataObject.length - 1;
								if(dataObject[positionWC].labels[0] === 'Others') {
									// Si es wordCloud obtenemos el de la pregunta mas reciente
									let position = object[self.iChart].length - 1;
									let rest = 1;
									while(object[self.iChart][position] == null) {
										position = object[self.iChart].length - rest;
										rest++;
									}
									let params = [self.idPollArray[self.idPollArray.length - 1], object[self.iChart][position].question];
									self.paramsWc.push(params);

									// Palabras (1) o frases (2)
									let wordsOrPhrases = 2;

									if(object[self.iChart][position].data[0].tipoPregunta == 'S' || object[self.iChart][position].data[0].tipoPregunta == 'Q') {
										wordsOrPhrases = 1;
									}

									let src = self.wordCloudURL + '/?a=' + self.idPollArray[self.idPollArray.length - 1] + '&b=' + object[self.iChart][position].question + '&c=&d=&e=&f=&g=' + self.primaryColor + '&h=' + self.secundaryColor + '&i=' + wordsOrPhrases + '&j=' + self.numberWordsWordcloud;

									window.addEventListener('message', loadWordCloud);
									function loadWordCloud(event) {
										pptJson.data.imgAnswer = event.data;
										window.removeEventListener('message', loadWordCloud);
									}
									$('#result_word_cloud').attr('src', src);
								} else {
									pptJson.data.imgAnswer = url_base64jp;
								}
								break;
							case 1:
								pptJson.data.imgGender = url_base64jp;
								break;
							case 2:
								pptJson.data.imgAge = url_base64jp;
								break;
							case 3:
								pptJson.data.imgStates = url_base64jp;
								break;
						}
						// Aumentamos el tipo de grafica
						n++;
						//Comprobamos si hemos hecho las 4 graficas
						if(n < 4) {
							recursiveGraphPpt(object, n);
						} else {
							self.arrayPpt.push(pptJson);
							self.iChart++;
							if(self.iChart < self.QuestQuantity) {
								self.graphsPpt(object);
							} else {
								self.returnPptData();
							}
						}
					}, 5000);
				}
			}
			return recursiveGraphPpt(object, 0);
		} catch(e) {
			if(!self.abort) {
				self.errorsReports.ppt = true;
				self.generateExcel();
			}
		}
	}

	finishReports() {
		let self = this;

		let content = '<p>' + pf.const.language.RSC55 + '</p>';
		let useBootstrap = true;

		if(self.errorsReports.word || self.errorsReports.ppt || self.errorsReports.excel) {
			content += '<p>' + pf.const.language.RSC546 + ':</p><ul>';
			useBootstrap = false;
		}
		if(self.errorsReports.word) {
			content += '<li>' + pf.const.language.RSC536 + '</li>';
		}
		if(self.errorsReports.ppt) {
			content += '<li>' + pf.const.language.RSC538 + '</li>';
		}
		if(self.errorsReports.excel) {
			content += '<li>' + pf.const.language.RSC540 + '</li>';
		}
		if(self.errorsReports.ppt && self.errorsReports.word) {
			content += '<li>' + pf.const.language.RSC542 + '</li>';
		}
		if(self.errorsReports.word || self.errorsReports.ppt || self.errorsReports.excel) {
			content += '</ul>';
		}

		removeLoader();
		if(!self.ajax) {
			$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC55 + ' - ' + self.namePoll);
			$(`#downloadCardText_${self.idReport}`).html(content);
			$(`#${self.idReport}`).find('#statusIcon').html(stcmbackend.svg.checkCircleWithoutColors);
			$(`#${self.idReport}`).find('#statusIcon').css('color', 'green');

			$(`#${self.idReport}`).removeClass('runningReport');
			$(`#buttonWrapper${self.idReport}`).html(`
				<button id="cancelGeneratedReport" type="button" class="btn new-style-cancel">${pf.const.language.RSC57}</button>
				<button id="dowloadGeneratedReport" type="button" class="btn new-style-accept">${pf.const.language.RSC56}</button>
			`);
			CardGeneratorController.updateIcon();
			CardGeneratorController.showOnScreenNotification(self.idReport,pf.const.language.RSC55, 'check-circle');
			$(`#${self.idReport}`).find('#dowloadGeneratedReport').off().on('click', ()=>{
				let url = stcm.const.downloads + '/' + self.user + '/' + self.timestamp + '_Analitic_Acumulativo_Mostreo.zip';
				$('#dowloadIframe').attr('src', url);
				CardGeneratorController.deleteNotification(this.idReport);

				setTimeout(function() {
					self.deleteFiles();
				}, 1000 * 60);
			})
			$(`#${this.idReport}`).find('#cancelGeneratedReport').off().on('click', ()=>{
				self.deleteFiles();
				CardGeneratorController.deleteNotification(this.idReport);
			});
		}
	}

	deleteFiles() {
		let self = this;
		let token = sessionStorage['STCMBackEnd:token'];
		let reqName = 'deleteFilesUser';
		let reqLabel = 'deleteFilesUser' + self.idReport;
		this.reqLabel = reqLabel;

		let form = new FormData();
		form.append('action', reqName);
		form.append('token', token);
		form.append('user', self.user);

		let reqData = {
			url: stcm.const.serverAPI,
			method: 'POST',
			timeout: stcm.const.AJAX_TIMEOUT,
			processData: false,
			mimeType: 'application/x-www-form-urlencoded',
			contentType: false,
			data: form
		};
		pf.ajax.request(reqLabel, reqData);
		$(document).off(reqLabel);

		$(document).on(reqLabel, function(event, response) {
			//
		});
	}

	deletePpt(filename) {
		let token = sessionStorage['STCMBackEnd:token'];
		let reqName = 'deletePpt';
		let reqLabel = 'deletePpt' + self.idReport;
		this.reqLabel = reqLabel;

		let form = new FormData();
		form.append('action', reqName);
		form.append('token', token);
		form.append('filename', filename);

		let reqData = {
			url: stcm.const.serverAPI,
			method: 'POST',
			timeout: stcm.const.AJAX_TIMEOUT,
			processData: false,
			mimeType: 'application/x-www-form-urlencoded',
			contentType: false,
			data: form
		};
		pf.ajax.request(reqLabel, reqData);
		$(document).off(reqLabel);

		$(document).on(reqLabel, function(event, response) {
			//
		});
	}

	returnPptData() {
		let self = this;
		let token = sessionStorage['STCMBackEnd:token'];
		let idTenant = sessionStorage['STCMBackEnd:idTenant'];
		let reqName = 'printPptComparative';
		let reqLabel = 'printPptComparative' + self.idReport;
		this.reqLabel = reqLabel;
		let steps = pf.const.language.RSC53 + '<br>' + pf.const.language.RSC54;
		$(`#downloadCardText_${self.idReport}`).html(steps);

		self.dataPpt.forEach(function(currentValue, index, arr) {
			currentValue.forEach(function(currentValue, index, arr) {
				if(currentValue != null) {
					if(currentValue.answers.labels[0] === 'Others') {
						//
					} else {
						delete currentValue.data;
					}
				}
			});
		});

		let graphs = JSON.stringify(self.arrayPpt);
		let data = JSON.stringify(self.dataPpt);
		let wcPpt = JSON.stringify(self.wcPpt);
		let questionsPpt = JSON.stringify(self.questionsPpt);
		let encuestasPpt = JSON.stringify(self.encuestasPpt);
		let paramsWc = JSON.stringify(self.paramsWc);
		let generalCharts = JSON.stringify(self.generalCharts);

		let form = new FormData();
		form.append('action', reqName);
		form.append('token', token);
		form.append('idTenant', idTenant);
		form.append('graphs', graphs);
		form.append('data', data);
		form.append('wcPpt', wcPpt);
		form.append('questionsPpt', questionsPpt);
		form.append('encuestasPpt', encuestasPpt);
		form.append('user', self.user);
		form.append('paramsWc', paramsWc);
		form.append('generalCharts', generalCharts);
		form.append('timestamp', self.timestamp);
		form.append('isWc', self.reports.wc);

		let reqData = {
			url: stcm.const.serverAPI,
			method: 'POST',
			timeout: stcm.const.AJAX_TIMEOUT_REPORTS,
			processData: false,
			mimeType: 'application/x-www-form-urlencoded',
			contentType: false,
			data: form
		};
		pf.ajax.request(reqLabel, reqData);
		$(document).off(reqLabel);
		$(document).on(reqLabel, function(event, response) {
			try {
				let resp = JSON.parse(response.resData.response);
				if(resp.status === 'OK') {
					self.generateExcel();
				} else if(!self.abort) {
					self.errorsReports.ppt = true;
					self.generateExcel();
					if(resp.result == 'Not authorized') {
						pf.ajax.setWindowLocationIndex();
					}
				}
			} catch(e) {
				if(!self.abort) {
					self.errorsReports.ppt = true;
					self.generateExcel();
					if(resp.result == 'Not authorized') {
						pf.ajax.setWindowLocationIndex();
					}
				}
			}
		});
	}

	// FALTARIA COMPROBAR FUNCIONAMIENTO EN COMPARATIVA
	generateExcel() {
		let self = this;

		if(self.reports.excel) {
			let token = sessionStorage['STCMBackEnd:token'];
			let survey = self.idPollArray;
			let reqName = 'generateExcelComparativo';
			let reqLabel = 'generateExcelComparativo' + self.idReport;
			this.reqLabel = reqLabel;
			let steps = pf.const.language.RSC534 + '<br>' + pf.const.language.RSC533 + '...';
			$(`#downloadCardTitle_${self.idReport}`).html(pf.const.language.RSC547 + ' ' + pf.const.language.RSC540 + ' - '+self.namePoll);
			$(`#downloadCardText_${self.idReport}`).html(steps);

			let headersExcel = '';
			if(self.numPregPerf < 4) {
				/*
					RSC1436 = Rotación
					RSC123 = Nombre
					RSC999 = Folio
					RSC564 = Estado
					RSC601 = Región ABI
					RSC607 = Ciudad
					RSC565 = Edad
					RSC1917 = Rango de edad
					RSC151 = Género
					RSC1948 = Segmentación
					RSC560 = Asesor
					RSC126 = Activo
				*/
				headersExcel = pf.const.language.RSC1436 + ',' + pf.const.language.RSC123 + ',' + pf.const.language.RSC999 + ',' + pf.const.language.RSC564 + ',' + pf.const.language.RSC601 + ',' + pf.const.language.RSC607 + ',' + pf.const.language.RSC565 + ',' + pf.const.language.RSC1917 + ',' + pf.const.language.RSC151 + ',' + pf.const.language.RSC1948 + ',' + pf.const.language.RSC560 + ',' + pf.const.language.RSC126;
			} else {
				/*
					RSC1436 = Rotación
					RSC123 = Nombre
					RSC999 = Folio
					RSC564 = Estado
					RSC601 = Región ABI
					RSC607 = Ciudad
					RSC565 = Edad
					RSC1917 = Rango de edad
					RSC151 = Género
					RSC598 = NSE
					RSC1990 = Rango NSE
					RSC1948 = Segmentación
					RSC560 = Asesor
					RSC126 = Activo
				*/
				headersExcel = pf.const.language.RSC1436 + ',' + pf.const.language.RSC123 + ',' + pf.const.language.RSC999 + ',' + pf.const.language.RSC564 + ',' + pf.const.language.RSC601 + ',' + pf.const.language.RSC607 + ',' + pf.const.language.RSC565 + ',' + pf.const.language.RSC1917 + ',' + pf.const.language.RSC151 + ',' + pf.const.language.RSC598 + ',' + pf.const.language.RSC1990 + ',' + pf.const.language.RSC1948 + ',' + pf.const.language.RSC560 + ',' + pf.const.language.RSC126;
			}

			if(sessionStorage['STCMBackEnd:Consumer'] == 1) {
				headersExcel += ',' + pf.const.language.RSC1899; // Consumidor
			}

			let parent_qid = '0';
			if(self.columnName != '') {
				let questionArray = self.columnName.split('X');
				parent_qid = questionArray[questionArray.length - 1];
			}

			let form = new FormData();
			form.append('action', reqName);
			form.append('token', token);
			form.append('survey', survey);
			form.append('idProjectsArray', self.idProjectsArray);
			form.append('idMissionsArray', self.idMissionsArray);
			form.append('numPreguntasPerfilacionEnAnalyticMostreo', self.numPregPerf);
			form.append('user', self.user);
			form.append('name', self.idPollNameArray);
			form.append('timestamp', self.timestamp);
			form.append('excelDataOpt', self.excelDataOpt);
			form.append('headersExcel', headersExcel);
			form.append('parent_qid', parent_qid);
			form.append('questionIdOut', self.questionIdOut);
			form.append('consumo', sessionStorage['STCMBackEnd:Consumer']);

			let reqData = {
				url: stcm.const.serverAPI,
				method: 'POST',
				timeout: stcm.const.AJAX_TIMEOUT_REPORTS,
				processData: false,
				mimeType: 'application/x-www-form-urlencoded',
				contentType: false,
				data: form
			};

			pf.ajax.request(reqLabel, reqData);
			$(document).off(reqLabel);
			$(document).on(reqLabel, function(event, response) {
				try {
					let resp = JSON.parse(response.resData.response);
					if(resp.status == 'KO') {
						self.errorsReports.excel = true;
					} else {
						self.errorsReports.excel = false;
					}
					self.finishReports();
				} catch(e) {
					self.errorsReports.excel = true;
					self.finishReports();
				}
			});
		} else {
			self.finishReports();
		}
	}
}