let WelcomeTourController = {
	numberOfImages: 0,
	imagesURL: '',
	inputToFill: '',
	rscDataAll: {},

	reset() {
		let self = this;

		self.numberOfImages = 0;
		self.imagesURL = '';
		self.inputToFill = '';
		self.rscDataAll = {};
	},

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

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

		// Añadir título
		$('#page-title').text(pf.const.language.RSC2134);

		// Opciones de header
		let jsonsubopt = {
			save: 'save',
			preview: 'preview',
			screen: 'screen'
		};

		let nav = `
			<div class="d-flex">
				${createSubOptionPreview(jsonsubopt.preview)}
				${createSubOptionAddScreen(jsonsubopt.screen)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>
		`;

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

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

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

		self.loadLanguage();
		self.getAllRSC();

		// Collapse
		addEventArrowTableHeader();

		$('#sortableImages').sortable();
		$('#sortableImages').disableSelection();

		// Imagen por defecto
		self.imagesURL = stcm.const.downloads + 'welcometour/welcometour.png';

		$('#addImage').click(function() {
			if(self.numberOfImages < 10) {
				self.numberOfImages++;
				$('#sortableImages').append(
					`<li id="" class="ui-state-default list-group-item liImage d-flex row align-items-center" role="button">
						<div class="col-lg-1 col-12">
							${stcmbackend.svg.arrowDownUpWithoutColor}
							<span id="index" class="text-primary"></span>
						</div>

						<div class="d-flex col-lg-2 col-5 justify-content-center pa-le-40">
							<img id="" class="targetImage border wel-tour-img" src="${self.imagesURL}">
							<button type="button" class="btn btn-nav btn-image">
								${stcmbackend.svg.pencil}
							</button>
							<input type="file" class="inputImage mt-2 d-none" accept="image/*">
							<span class="place-self-center text-center">
								<!-- Download -->
								<button type="button" class="btn btn-nav btn-image-download" value="${self.imagesURL}">
									${stcmbackend.svg.download}
								</button>
							</span>	
						</div>

						<div class="d-flex flex-column col-lg-7 col-5">
							<label>${pf.const.language.RSC112}</label>

							<div class="d-flex">
								<div class="input-group new-input-style">
									<input type="text" class="form-control titleInput" rsc="" disabled/>
									<div class="input-group-append">
										<button type="button" class="btn btn-outline-secondary searchRSCTitle" data-toggle="modal" data-target="#modalContainer">
											${stcmbackend.svg.threeDotsWithoutMargin}
										</button>
									</div>
								</div>

								<span id="" class="d-flex justify-content-center c-pointer deleteTitle pt-3 pl-2">
									${stcmbackend.svg.bigTrash}
								</span>
							</div>

							<label>${pf.const.language.RSC178}</label>

							<div class="d-flex">
								<div class="input-group new-input-style">
									<input type="text" class="form-control descriptionInput" rsc="" disabled/>
									<div class="input-group-append">
										<button type="button" class="btn btn-outline-secondary searchRSCDescription" data-toggle="modal" data-target="#modalContainer">
											${stcmbackend.svg.threeDotsWithoutMargin}
										</button>
									</div>
								</div>

								<span id="" class="d-flex justify-content-center c-pointer deleteDescription pt-3 pl-2">
									${stcmbackend.svg.bigTrash}
								</span>
							</div>
						</div>

						<div class="col-2 text-center">
							<button type="button" class="btn btn-outline-secondary deleteImage">${pf.const.language.RSC2162}</button>
						</div>
					</li>`
				);

				self.sortableItemsEvents();
			}
		});

		// Se actualizan los valores del índice (actualizar los valores de índice con los eventos de sortable.js da algunos errores)
		setInterval(function() {
			let i = 1;
			$('#sortableImages li').each(function() {
				$(this).find('#index').text(i);
				i++;
			});
		}, 1000);

		$('#save').click(function() {
			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.processData('save');
			}, function() {});
		});

		$('#preview').click(function() {
			self.processData('preview');
		});
	},

	processData(target) {
		let self = this;

		let sectionsArray = [];
		let imageArray = [];
		let emptyImages = false;
		let nImages = 0;

		addLoader();

		$('.liImage').each(function(index) {
			nImages++;
			let inputImage = $(this).find('.inputImage');
			let img = '';
			let type = '';
			let preloadedImage = false;
			if(inputImage[0].files.length != 0) {
				img = inputImage[0].files[0].name;
				type = inputImage[0].files[0].type;
				imageArray.push([inputImage[0].files[0], index]);
				inputImage.prev().prev().removeClass('border-danger');

				let inputTitle = $(this).find('.titleInput');
				let inputDescription = $(this).find('.descriptionInput');
				let section = {
					order: index + 1,
					imageName: img,
					title: inputTitle.attr('rsc') || '',
					description: inputDescription.attr('rsc') || '',
					type: type,
					preloadedImage: preloadedImage,
				}

				sectionsArray.push(section);
			} else if(inputImage.attr('loadedImage') == 'true') {
				preloadedImage = true;
				// Creación del file para las imágenes precargadas
				setTimeout(() => {
					fetch(inputImage.prev().prev().attr('src'))
					.then(res => res.blob())
					.then(blob => {
						const file = new File([blob], 'preloadedimage.png', blob);
						imageArray.push([file, index]);

						let inputTitle = $(this).find('.titleInput');
						let inputDescription = $(this).find('.descriptionInput');
						img = file.name;
						type = file.type;
						let section = {
							order: index + 1,
							imageName: img,
							title: inputTitle.attr('rsc') || '',
							description: inputDescription.attr('rsc') || '',
							type: type,
							preloadedImage: preloadedImage,
						}

						sectionsArray.push(section);
					});
				}, 100);
			} else {
				inputImage.prev().prev().addClass('border-danger');
				emptyImages = true;
			}
		});

		// Comprobar que haya una imágen como mínimo para guardar/previsualizar
		if(nImages == 0) {
			let successTitle = pf.const.language.RSC61;
			let successContent = target === 'save' ? pf.const.language.RSC2137 : pf.const.language.RSC2151;

			pf.utils.showInfoDialog(successTitle, successContent);
			removeLoader();
			return false;
		}

		if(emptyImages) {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC141
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};
			let alertTitle = pf.const.language.RSC654;
			let alertText = pf.const.language.RSC793;
			removeLoader();
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				//
			});
		} else {
			setTimeout(() => {
				// Verificación validez de los formatos de las imágenes
				let invalidImageFormat = false;

				sectionsArray.map(obj => {
					let format = obj.type.split('/')[1];
					if(format != 'png' && format != 'jpg' && format != 'jpeg' && format != 'bmp' && format != 'webp') {
						invalidImageFormat = true;
					}
				});
				if(invalidImageFormat) {
					let objInfo = {
						accept: {
							text: pf.const.language.RSC141
						},
						cancel: {
							text: pf.const.language.RSC57
						}
					};
					let alertTitle = pf.const.language.RSC654;
					let alertText = pf.const.language.RSC2136;
					removeLoader();
					pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
						//
					});
				} else {
					let orderedArray = [];
					for(let i = 0; i < imageArray.length; i++) {
						for(let j = 0; j < imageArray.length; j++) {
							if(imageArray[j][1] == i) {
								orderedArray.push(imageArray[j]);
							}
						}
					}
					removeLoader();
					if(target === 'save') {
						self.saveImages(sectionsArray, orderedArray);
					}
					if(target === 'preview') {
						self.previewImages(sectionsArray, orderedArray);
					}
				}
			}, 1000);
		}
	},

	loadLanguage() {
		pf.rsc.translateByTag('text');
	},

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

		// Limpiar el texto de la etiquetas html para ver su tamaño real
		let cleanText = data.descripcion.replaceAll('&lt;', '<').replaceAll('&gt;', '>');
		let textWithTags = cleanText;
		cleanText = cleanText.replace(/<[^>]*>?/g, '');

		if(($(self.inputToFill).hasClass('titleInput') && cleanText.length > 40) || ($(self.inputToFill).hasClass('descriptionInput') && cleanText.length > 180)) {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC141
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC1616;
			let alertText = $(self.inputToFill).hasClass('titleInput') ? pf.const.language.RSC2155 : pf.const.language.RSC2156;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				$(self.inputToFill).val(textWithTags);
				$(self.inputToFill).attr('rsc', data.id);
			}, function() {});
		} else {
			$(self.inputToFill).val(textWithTags);
			$(self.inputToFill).attr('rsc', data.id);
		}
	},

	saveImages(sectionsArray, imageArray) {
		let self = this;
		let parameters = {
			sectionsArray: JSON.stringify(sectionsArray),
			path: stcm.const.downloads + 'welcometour/'
		}

		// Otras imágenes
		let imgSize = imageArray.length;
		for(let i = 0; i < imgSize; i++) {
			parameters['img' + i] = imageArray[i][0];
		}

		ajaxComunCallWithCallback('setWelcomeTour', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC78;
				let successContent = pf.const.language.RSC948;
				pf.utils.showInfoDialog(successTitle, successContent);
				self.getAllRSC();
			}
		}, true);
	},

	getWelcomeTour() {
		let self = this;

		ajaxComunCallWithCallback('getWelcomeTour', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result;
				let details = ajaxReturn.details;
				$('#sortableImages').html('');
				self.numberOfImages = 0;
				for(let i = 0; i < size; i++) {
					self.numberOfImages++;
					let raiz = stcm.const.downloads + 'welcometour/images/' + details[i].image;
					$('#sortableImages').append(
						`<li id="" class="ui-state-default list-group-item liImage d-flex row align-items-center" role="button">
							<div class="col-lg-1 col-12">
								${stcmbackend.svg.arrowDownUpWithoutColor}
								<span id="index" class="text-primary"></span>
							</div>

							<div class="d-flex col-lg-2 col-5 justify-content-center pa-le-40">
								<img id="" class="targetImage border wel-tour-img" src="${(raiz + '?stamp=' + new Date().getTime() + '') || self.imagesURL}">
								<button type="button" class="btn btn-nav btn-image">
									${stcmbackend.svg.pencil}
								</button>
								<input type="file" class="inputImage mt-2 d-none" accept="image/*" loadedImage="true"/>
								<span class="place-self-center text-center">
									<!-- Download -->
									<button type="button" class="btn btn-nav btn-image-download" value="${(raiz) || self.imagesURL}">
										${stcmbackend.svg.download}
									</button>
								</span>	
							</div>

							<div class="d-flex flex-column col-lg-7 col-5">
								<label>${pf.const.language.RSC112}</label>

								<div class="d-flex">
									<div class="input-group new-input-style">
										<input type="text" class="form-control titleInput" rsc="${details[i].title}" value="${self.rscDataAll[details[i].title] || ''}" disabled>
										<div class="input-group-append">
											<button type="button" class="btn btn-outline-secondary searchRSCTitle" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsWithoutMargin}
											</button>
										</div>
									</div>

									<span id="" class="d-flex justify-content-center c-pointer deleteTitle pt-3 pl-2">
										${stcmbackend.svg.bigTrash}
									</span>
								</div>

								<label>${pf.const.language.RSC178}</label>

								<div class="d-flex">
									<div class="input-group new-input-style">
										<input type="text" class="form-control descriptionInput" rsc="${details[i].description}" value="${self.rscDataAll[details[i].description] || ''}" disabled>
										<div class="input-group-append">
											<button class="btn btn-outline-secondary searchRSCDescription" type="button" data-toggle="modal" data-target="#modalContainer">
												${stcmbackend.svg.threeDotsWithoutMargin}
											</button>
										</div>
									</div>

									<span id="" class="d-flex justify-content-center c-pointer deleteDescription pt-3 pl-2">
										${stcmbackend.svg.bigTrash}
									</span>
								</div>
							</div>

							<div class="col-2 text-center">
								<button type="button" class="btn btn-outline-secondary deleteImage">${pf.const.language.RSC2162}</button>
							</div>
						</li>`
					);
				}

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

	sortableItemsEvents() {
		let self = this;

		let i = 1;
		$('#sortableImages li').each(function() {
			$(this).find('#index').text(i);
			i++;
		});

		$('.inputImage').change(function() {
			self.loadImage(this);
		});

		// Cambiar imagen
		$('.btn-image').off().on('click', function() {
			$(this).next().trigger('click');
		});

		// Download imagen
		$('.btn-image-download').off().on('click', function() {
			self.downloadImage(this);
		});

		$('.deleteImage').off().on('click', function() {
			self.numberOfImages--;
			$(this).parent().parent().remove();
			let i = 1;
			$('#sortableImages li').each(function() {
				$(this).find('#index').text(i);
				i++;
			});
		});

		// No System RSC - Modal
		let rscModal = new TableNoSystemRSC(0, 'openRSCWelcomeTour');
		$('.searchRSCTitle').off().on('click', function() {
			self.inputToFill = $(this).parent().parent().children()[0];
			rscModal.setEvents();
		});

		$('.searchRSCDescription').off().on('click', function() {
			self.inputToFill = $(this).parent().parent().children()[0];
			rscModal.setEvents();
		});

		$('.deleteTitle').off().on('click', function() {
			$(this).parent().find('input').val('');
			$(this).parent().find('input').attr('rsc', '');
		});

		$('.deleteDescription').off().on('click', function() {
			$(this).parent().find('input').val('');
			$(this).parent().find('input').attr('rsc', '');
		});
	},

	loadImage(input) {
		if(input.files && input.files[0]) {
			let src = URL.createObjectURL(input.files[0]);
			$(input).prev().prev().attr('src', src);
		} else {
			$(input).prev().prev().attr('src', self.imagesURL);
		}
	},

	downloadImage(source) {
		const fileName = source.value.split('/').pop();
		var el = document.createElement('a');
		el.setAttribute('href', source.value);
		el.setAttribute('download', fileName);
		document.body.appendChild(el);
		el.click();
		el.remove();
	},

	getAllRSC() {
		let self = this;

		ajaxComunCallWithCallback('getAllRSC', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let rscData = ajaxReturn.result;

				// Dicionario completo
				let language = sessionStorage['STCMBackEnd:lenguage'];
				self.rscDataAll = {};
				let size = rscData.length;
				for(let i = 0; i < size; i++) {
					if(rscData[i].system == 0) {
						self.rscDataAll[rscData[i].idRSC] = rscData[i][language];
					}
				}

				self.getWelcomeTour();
			}
		}, true);
	},

	previewImages(sectionsArray, imageArray) {
		let self = this;

		let previewData = [];

		$('.liImage').each(function(index) {
			let obj = {
				img: $(this).find('.targetImage').attr('src'),
				title: $(this).find('.titleInput').val(),
				description: $(this).find('.descriptionInput').val()
			}
			previewData.push(obj);
		});

		self.previewFormat(previewData);
	},

	previewFormat(previewData) {
		let welcomeTour = {
			userViewWelcomeTour() {
				return jsxc.storage.getItem('welcomeTour');
			},

			isShowingWelcomeTour() {
				return $('.stcm_welcomeTour').length > 0;
			},

			showWelcomeTour(previewData) {
				let self = this;

				$('#previewImages').html('');

				$('<div class="stcm_welcomeTour"><span class="finishWT"></span>').appendTo('#previewImages');

				var template = self.renderTemplateWelcomeTour(previewData);

				$('.stcm_welcomeTour').append(template);
				$('.stcm_welcomeTour').append(template.template);
				$('.stcm_welcomeTour').append(template.templateicons);

				$('.slider').slick({
					arrows: false,
					dots: true,
					infinite: false,
					speed: 0,
					focusOnSelect: false,
					customPaging(slider, i) {
						return '<a><svg width="100%" height="100%" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6.215"></circle></svg><span></span></a>';
					},
				}).on('beforeChange', function(event, slick, currentSlide, nextSlide) {
					self.slideAction(currentSlide, nextSlide);
				}).on('afterChange', function(event, slick, currentSlide) {
					$('.item').eq(currentSlide).addClass('ready');
				});

				var elem = $('<div class="stcm_nav_slick">').append($('.slick-dots'));

				//append next button
				var btnPrev = `
					<button type="button" class="slick-prev slick-arrow slick-disabled dis-none" data-role="none" aria-label="Previous" role="button" aria-disabled="true">
						<span>${pf.const.language.RSC653}</span>
					</button>
				`;
				var btnNext = `
					<button type="button" class="slick-next slick-arrow d-block" data-role="none" aria-label="Next" role="button" aria-disabled="false">
						<span>${pf.const.language.RSC663}</span>
					</button>
				`;

				elem.prepend(btnPrev);
				elem.append(btnNext);

				$('.stcm_welcomeTour .onboard .slider').append(elem);

				self.setEventBtnsSlides();
				// Al cerrar welcome tour, poner el style de la barra normal segun estemos en login o dentro
			},

			slideAction(currentSlide, nextSlide) {
				$('.item').removeClass('from-right from-left ready');
				var c = (currentSlide < nextSlide) ? 'from-right' : 'from-left';
				$('.item').eq(nextSlide).addClass(c);
				$('#icon-'+nextSlide).removeClass('d-none');
				$('#icon-'+currentSlide).addClass('d-none');
			},

			setEventBtnsSlides() {
				$('.slick-prev').off('click').click(function() {
					var prevElem = $('li.slick-active').prev();
					var prevId = prevElem.attr('id');

					if(prevId == 'slick-slide00') {
						$('.slick-prev').hide();
					} else {
						$('.slick-prev').show();
					}

					var idPrev = $(prevElem).attr('id');
					$('li#'+idPrev).click();
				});

				$('.slick-next').off('click').click(function() {
					var nextElem = $('li.slick-active').next();

					if(nextElem.length > 0) {
						$('.slick-prev').show();
						var idNext = $(nextElem).attr('id');
						$('li#'+idNext).click();
					}
				});
			},

			renderElemWelcomeTour(object, i) {
				return `
					<div class="item" data-item="${i}">
						<div>
							<div class="tit">
								${object.title}
							</div>

							<div class="text">
								${object.description}
							</div>
						</div>
					</div>
				`;
			},

			renderTemplateWelcomeTour(data) {
				let self = this;

				var template = `
					<div class="onboard">
						<div class="slider">
				`;

				var templateIcons = '';
				var strClass = '';
				for(var i = 0; i < data.length; ++i) {
					template += self.renderElemWelcomeTour(data[i], i);
					if(i > 0) {
						strClass = 'd-none';
					}
					templateIcons += `<span id="icon-${i}" class="stcm_welcomeTourBgImage ${strClass}" style="background-image: url('${data[i].img}');"></span>`;
				};

				template += `
						</div>
					</div>
				`;

				return {'template': template, 'templateicons': templateIcons};
			}
		}

		// Primero tiene que cargar el html del modal para que los elementos de la librería 'slick' se inserten de manera correcta 
		$('#modalPreview').on('shown.bs.modal', function() {
			welcomeTour.showWelcomeTour(previewData);

			if($(window).height() <= 800) {
				$('.tit').css({'font-size': '1rem'});
				$('.text').css({'font-size': '0.8rem'});
			}
			window.addEventListener('resize', function(event) {
				if($(window).height() <= 800) {
					$('.tit').css({'font-size': '1rem'});
					$('.text').css({'font-size': '0.8rem'});
				} else {
					$('.tit').css({'font-size': '1.8rem'});
					$('.text').css({'font-size': '1.3rem'});
				};

			}, true);
		});

		$('#modalPreview').modal('toggle');
	}
};