let ProductoEncuestaController = {
	url: null,
	token: null,
	idProduct: null,
	productTemplate: null,
	idMisionProduct: null,
	sid: null,
	config: null,
	stampMission: null,
	misionObjective: null,
	descMisionObjective: null,

	resetData() {
		let self = this;

		self.url = null;
		self.idProduct = atob(sessionStorage.getItem('idProductToCreate'));
		self.stampMission = sessionStorage.getItem('stampMissionProduct');
		self.idMisionProduct = sessionStorage.getItem('idMisionProduct');
		self.token = sessionStorage['STCMBackEnd:token'];
		self.sid = sessionStorage.getItem('stepByStepEncuesta');
		self.productTemplate = sessionStorage.getItem('productTemplate');
		self.misionObjective = sessionStorage.getItem('misionObjective');
		self.descMisionObjective = sessionStorage.getItem('descMisionObjective');
		self.config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
	},

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

		window.onmessage = (event) => {
			let data = event.data;
			if(data.action == 'resultImportTemplateFromSTCM') {
				self.sid = data.value;
				sessionStorage.setItem('stepByStepEncuesta', self.sid);
				self.setMisionObjetivo();
				self.redirectToSurvey();
			}
		}

		// Footer
		// Botón de anterior
		$('#previousStep').show();
		$('#previousStep').html(stcmbackend.svg.arrowLeftShortWithoutColor28 + pf.const.language.RSC2094);
		$('#previousStep').attr('title', pf.const.language.RSC2094);

		// Pasos
		let footerSteps = `
			<span class="font-weight-bold d-inline-block mx-3">1. ${pf.const.language.RSC2095}</span>
			<span class="font-weight-bold d-inline-block mx-3">2. ${pf.const.language.RSC2094}</span>
			<span class="font-weight-bold d-inline-block mx-3 text-decoration main-color-text p-2">3. ${pf.const.language.RSC110}</span>
			<span class="font-weight-bold d-inline-block mx-3">4. ${pf.const.language.RSC2096}</span>
			<span class="font-weight-bold d-inline-block mx-3">5. ${pf.const.language.RSC2097}</span>
		`;
		$('#stepContainer').html(footerSteps);

		// Botón de siguiente
		$('#subsequentStep').html(pf.const.language.RSC2096 + stcmbackend.svg.arrowRightShortWithoutColor28);
		$('#subsequentStep').attr('title', pf.const.language.RSC2096);

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

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

		// Valores de configuración
		if(self.config.URLEncuestasSession != '') {
			self.url = self.config.URLEncuestasSession + '&s=1';
		} else {
			if(self.config.URLEncuestas == '' || self.config.URLEncuestas == undefined || self.config.URLEncuestas == null) {
				let warningTitle = pf.const.language.RSC61;
				let warningContent = pf.const.language.RSC993;
				pf.utils.showInfoDialog(warningTitle, warningContent);
				return;
			}
			self.url = self.config.URLEncuestas + 'index.php/admin';
		}

		self.printIframe();

		// Volver a Producto / Misión
		$('#previousStep').off().on('click', function() {
			window.location.href = '#!producto_mision_edit';
		});

		// Ir a Producto / Criterios
		$('#subsequentStep').off().on('click', function() {
			// Control nuevo / editar
			if(sessionStorage['editProductProject'] == '1') {
				window.location.href = '#!producto_criterio_edit';
			} else {
				// Controlar si ya se ha estado para enviar a editar en lugar de nuevo
				if(sessionStorage['productCriteria'] == '1') {
					window.location.href = '#!producto_criterio_edit';
				} else {
					window.location.href = '#!producto_criterio_new';
				}
			}
		});
	},

	setMisionObjetivo() {
		let self = this;

		let parameters = {
			idmision: self.idMisionProduct,
			idEncuesta: self.sid,
			descencuesta: self.idMisionProduct,
			objetivo: self.misionObjective,
			descobjetivo: self.descMisionObjective,
			stampMission: self.stampMission
		};
		ajaxComunCallWithCallback('setMisionObjetivoAndUpdateSurveyExpiration', parameters, function() {
			//
		});
	},

	toDataUrl(url, name, callback) {
		var xhr = new XMLHttpRequest();
		xhr.onload = function() {
			var blob = xhr.response;
			var file = new File([blob], name, {type: blob.type});
			callback(file);
		};
		xhr.open('GET', url);
		xhr.responseType = 'blob';
		xhr.send();
	},

	duplicateSurvey() {
		let self = this;

		var templateUrl = stcm.const.downloads + '/templates/' + self.productTemplate;
		self.toDataUrl(templateUrl, self.productTemplate, function(file) {
			$('#sIframe')[0].contentWindow.postMessage({
				action: 'importTemplateFromSTCM',
				value: file,
				survey: self.idMisionProduct
			}, '*');
		}, false);
	},

	redirectToSurvey() {
		let self = this;

		let sidUrl = self.config.URLEncuestas + 'index.php/admin/survey/sa/view/surveyid/' + self.sid;
		$('#sIframe').attr('src', sidUrl);
		setTimeout(function() {
			self.finishLoading();
		}, 3000);
	},

	printIframe() {
		let self = this;

		if(self.sid != null && self.sid != 'null') {
			self.url = self.config.URLEncuestas + 'index.php/admin/survey/sa/view/surveyid/' + self.sid;
		}
		self.renderIframe();
	},

	renderIframe() {
		let self = this;

		let iframe = `
			<div class="ml-1">
				<iframe id="sIframe" src="${self.url}" class="d-none w-100 he-cal-100vh-n66 border-0" allowfullscreen></iframe>
				<div id="surveyStepByStepLoader" class="animated fadeIn loaderspinner loadingMessageIframe">
					<div id="loader" class="color-loader"></div>
				</div>
			</div>
		`;

		$('#iframeSurveysProduct').html(iframe);
		self.bindIframeLoader();
	},

	bindIframeLoader() {
		let self = this;

		$('#sIframe').on('load', function() {
			if(self.sid == null || self.sid == 'null') {
				self.duplicateSurvey();
			} else {
				self.finishLoading();
			}
		});
	},

	finishLoading() {
		removeLoader();
		$('.loadingMessageIframe').remove();
		$('#sIframe').removeClass('d-none');
	}
};