let StoresNewController = {
	user: null,
	defaultImage: '',
	maxSize: 0,
	storeImages: [],
	storeImagesFile: [],
	acceptStoreImages: [],
	acceptStoreImagesFile: [],
	storeObj: {},
	noImgMain: true,
	items: [],
	loaders: {},

	reset() {
		let self = this;

		self.user = null;
		self.defaultImage = stcm.const.downloads + 'image.png';
		self.maxSize = 0;
		self.storeImages = [];
		self.storeImagesFile = [];
		self.acceptStoreImages = [];
		self.acceptStoreImagesFile = [];
		self.storeObj = {
			nombre: '',
			direccion: '',
			idComercioType: '',
			telefono: '',
			email: '',
			personaContacto: '',
			horarioApertura: '',
			horarioCierre: '',
			numCajas: '',
			numRefrigeradores: '',
			latitude: '',
			longitude: '',
			altitude: '',
			accuracy: '',
			abiertaPublico: '',
			ventanilla: '',
			apertura24H: ''
		};
		self.noImgMain = true;
		self.items = [];
		self.loaders = {
			getAllComerciosType: false,
			getAllItems: false
		};
	},

	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('.', '_');

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

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

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

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

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

		// Ocultar carrusel
		$('#respCarousel').hide();

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

		// Imagen por defecto
		self.storeImages[0] = {
			imgPath: self.defaultImage,
			main: '0'
		};

		// Inicio de spinner
		addLoader();

		ajaxComunCallWithCallback('getAllComerciosType', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let options = '';
				for(let i = 0; i < ajaxReturn.result.length; i ++) {
					options += `<option value="${ajaxReturn.result[i].id}">${ajaxReturn.result[i].descripcion}</option>`;
				}

				$('#idComercioType').html(options);

				// Control de spinner
				self.loaders.getAllComerciosType = true;
				spinnerControl(self.loaders);
			}
		}, false);

		ajaxComunCallWithCallback('getAllItems', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.items = ajaxReturn.result;

				for(let i = 0; i < self.items.length; i++) {
					self.items[i]['selected'] = false;
				}

				self.renderItems();

				// Control de spinner
				self.loaders.getAllItems = true;
				spinnerControl(self.loaders);
			}
		}, false);

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

		// Collapse
		addEventArrowTableHeader();

		// Pintar texto de label
		changeLabelsColor();
	},

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

		// TITLES
		$('.acceptTitle').attr('title', pf.const.language.RSC141);
	},

	applyEvents() {
		let self = this;

		// Añadir imágenes
		$('#addImage').off().on('click', function() {
			self.imagesRender();
			$('#modalPictures').modal('show');
		});

		// Aceptar modal de imágenes
		$('#acceptImages').off().on('click', function() {
			$('#modalPictures').modal('hide');
			for(let i = 0; i < self.storeImages.length; i++) {
				let obj = {
					imgPath: self.storeImages[i].imgPath,
					main: self.storeImages[i].main
				};
				self.acceptStoreImages[i] = obj;
			}
			self.acceptStoreImagesFile = self.storeImagesFile;

			// Mostrar u ocultar carrusel según proceda
			if(self.acceptStoreImages.length > 0 && self.acceptStoreImages[0].imgPath != self.defaultImage) {
				$('#respCarousel').show();
				self.carousel();
			} else {
				$('#respCarousel').hide();
			}
		});

		// Volver a tiendas
		$('#back').off().on('click', function() {
			window.location.href = '#!show_all_stores';
		});

		// Guardar nueva tienda
		$('#save').off().on('click', function() {
			self.getFormStore();
		});
	},

	carousel() {
		let self = this;

		let carouselImgs = '';
		let first = true;
		let size = self.acceptStoreImages.length;

		for(let i = 0; i < size; i++) {
			if(self.acceptStoreImages[i].imgPath == self.defaultImage) {
				continue;
			}

			if(first) {
				carouselImgs += `
					<div class="carousel-item active">
						<img src="${self.acceptStoreImages[i].imgPath}" class="img-fluid d-inline-block">
					</div>
				`;

				first = false;
			} else {
				carouselImgs += `
					<div class="carousel-item">
						<img src="${self.acceptStoreImages[i].imgPath}" class="img-fluid d-inline-block">
					</div>
				`;
			}
		}

		$('#carouselInner').html(carouselImgs);
		$('.carousel').carousel();
	},

	imagesRender() {
		let self = this;

		let picturesIMG = '';
		let size = self.storeImages.length;
		for(let i = 0; i < size; i++) {
			// Clase para borrar imagen que no se aplica a la imagen por defecto
			let trash = 'deletePicture';

			// Clase para seleccionar imagen principal en caso de que no haya imagen de GS1 o cargar nueva imagen en caso de que sea la de por defecto
			let loadPicture = ' c-pointer selectMain';

			// Estilo para mostrar o no imagen principal
			let selectMain = 'display: none;';

			if(self.storeImages[i].imgPath === self.defaultImage) {
				trash = 'd-none';
				loadPicture = ' c-pointer loadPicture';
			}
			if(self.storeImages[i].main === '_main_') {
				trash = 'd-none';
				loadPicture = '';
				selectMain = '';
			}
			picturesIMG += `
				<div class="col-3 d-flex flex-column">
					<input id="otherPicture_${i}" type="file" class="d-none mb-3 loadPictureInput" accept="image/*" data-index="${i}">
					<div id="otherPicture_${i}IMGdiv" class="d-flex justify-content-center h-100">
						<div class="position-relative">
							<img id="otherPicture_${i}IMG" src="${self.storeImages[i].imgPath}" class="ob-fit-cont border${loadPicture}" alt="img" height="130" width="130" data-index="${i}">
							<div class="btn-eye pos-abs-t6-l6-rad-50" style="${selectMain}">
								${stcmbackend.svg.checkBigCircleWithoutColor}
							</div>
						</div>
					</div>
					<button id="btn_otherPicture_${i}" type="button" class="btn btn-nav ${trash}" data-index="${i}">
						${stcmbackend.svg.trash}
					</button>
				</div>
			`;
		}

		$('#picturesContainer').html(picturesIMG);

		self.imagesEvents();
	},

	imagesEvents() {
		let self = this;

		// Seleccionar imagen principal
		$('.selectMain').off().on('click', function() {
			let index = $(this).data('index');

			for(let i = 0; i < self.storeImages.length; i++) {
				if(i == index) {
					self.storeImages[i].main = '_main_';
				} else {
					self.storeImages[i].main = '0';
				}
			}

			self.imagesRender();
		});

		// Carga de otras imágenes
		$('.loadPicture').off().on('click', function() {
			let index = $(this).data('index');
			$('#otherPicture_' + index).trigger('click');
		});
		$('.loadPictureInput').off().on('change', function(evt) {
			let index = $(this).data('index');
			let file = evt.target.files[0];
			if(file.size > self.maxSize) {
				let alertTitle = pf.const.language.RSC1909;
				let alertText = pf.const.language.RSC1337;
				pf.utils.showInfoDialog(alertTitle, alertText);
			} else {
				self.storeImagesFile[index] = file;
				let src = URL.createObjectURL(evt.target.files[0]);
				self.storeImages[index].imgPath = src;
				if(self.noImgMain) {
					self.noImgMain = false;
					self.storeImages[index].main = '_main_';
				} else {
					self.storeImages[index].main = '0';
				}

				let obj = {
					imgPath: self.defaultImage,
					main: '0'
				};
				self.storeImages.push(obj);

				self.imagesRender();
			}
		});

		// Borrar imágenes secundarias
		$('.deletePicture').off().on('click', function() {
			let index = $(this).data('index');
			$('.otherPicture_' + index).val(null);

			self.storeImages.splice(index, 1);
			self.storeImagesFile.splice(index, 1);

			self.imagesRender();
		});
	},

	renderItems() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC1674}">${pf.const.language.RSC1674}</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
					<th scope="col" title="${pf.const.language.RSC1822}">${pf.const.language.RSC1822}</th>
					<th scope="col" title="${pf.const.language.RSC2374}">${pf.const.language.RSC2374}</th>
					<th scope="col" title="${pf.const.language.RSC2378}">${pf.const.language.RSC2378}</th>
					<th scope="col" title="${pf.const.language.RSC1048}">${pf.const.language.RSC1048}</th>
					<th scope="col">
						<div class="custom-control custom-switch">
							<input id="allSwitchs" type="checkbox" class="custom-control-input">
							<label for="allSwitchs" class="custom-control-label c-pointer"></label>
						</div>
					</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>barcode</td>
					<td>nombre</td>
					<td>descripcion</td>
					<td>categoria</td>
					<td>marca</td>
					<td>contenido</td>
					<td>unidadMedida</td>
					<td>select</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.items.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].barcode}">${'\0' + self.items[i].barcode}</td>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].nombre}">${self.items[i].nombre}</td>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].descripcion}">${self.items[i].descripcion}</td>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].categoria}">${self.items[i].categoria}</td>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].marca}">${self.items[i].marca}</td>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].contenido}">${self.items[i].contenido}</td>
					<td class="text-truncate c-pointer editRow" title="${self.items[i].unidadMedida}">${self.items[i].unidadMedida}</td>
					<td>
						<div class="custom-control custom-switch">
							<input id="${self.items[i].idItem}" type="checkbox" class="custom-control-input uSwitch" data-index="${i}">
							<label for="${self.items[i].idItem}" class="custom-control-label c-pointer"></label>
						</div>
					</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 === 'select') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '30px', orderable: false, targets: 7}
			],
			exportOptions: {
				columns: [0, 1, 2, 3, 4, 5, 6]
			},
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1892,
				className: 'd-none',
				title: pf.const.language.RSC1892,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

		self.itemsTableEvents(dataTable);

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

	itemsTableEvents() {
		let self = this;

		// Estado de checkbox inicial
		if($('.uSwitch').length == $('.uSwitch:checked').length) {
			$('#allSwitchs').prop('checked', true);
		} else {
			$('#allSwitchs').prop('checked', false);
		}

		// La id del elemento principal modifica los elementos secundarios a través de su clase
		$('#allSwitchs').on('click', function() {
			$('.uSwitch').prop('checked', this.checked);

			$('.uSwitch').each(function() {
				let index = $(this).data('index');
				self.items[index].selected = this.checked;
			});
		});

		// Si todos los checkbox están seleccionados, se selecciona el checkbox principal, y viceversa
		$('.uSwitch').on('click', function() {
			if($('.uSwitch').length == $('.uSwitch:checked').length) {
				$('#allSwitchs').prop('checked', true);
			} else {
				$('#allSwitchs').prop('checked', false);
			}

			let index = $(this).data('index');
			self.items[index].selected = this.checked;
		});
	},

	getFormStore() {
		let self = this;

		let check = true;

		// Nombre
		let nombre = $('#nombre').val().trim();
		if(nombre == '') {
			check = false;
			$('#nombre').addClass('is-invalid');
			$('[for="nombre"]').addClass('is-invalid');
		} else {
			$('#nombre').removeClass('is-invalid');
			$('[for="nombre"]').removeClass('is-invalid');
		}

		// Tipo de comercio
		let idComercioType = $('#idComercioType').val();
		if(idComercioType == '') {
			check = false;
			$('#idComercioType').addClass('is-invalid');
			$('[for="idComercioType"]').addClass('is-invalid');
		} else {
			$('#idComercioType').removeClass('is-invalid');
			$('[for="idComercioType"]').removeClass('is-invalid');
		}

		// Comprobación
		if(!check) {
			let alertTitle = pf.const.language.RSC2473;
			let alertText = pf.const.language.RSC101;
			pf.utils.showInfoDialog(alertTitle, alertText);
		} else {
			self.storeObj = {
				nombre: nombre,
				direccion: $('#direccion').val().trim(),
				idComercioType: idComercioType,
				telefono: $('#telefono').val().trim(),
				email: $('#email').val().trim(),
				personaContacto: $('#personaContacto').val().trim(),
				horarioApertura: $('#horarioApertura').val(),
				horarioCierre: $('#horarioCierre').val(),
				numCajas: $('#numCajas').val(),
				numRefrigeradores: $('#numRefrigeradores').val(),
				latitude: $('#latitude').val(),
				longitude: $('#longitude').val(),
				altitude: $('#altitude').val(),
				accuracy: $('#accuracy').val(),
				abiertaPublico: ($('#abiertaPublico').prop('checked') ? '1' : '0'),
				ventanilla: ($('#ventanilla').prop('checked') ? '1' : '0'),
				apertura24H: ($('#apertura24H').prop('checked') ? '1' : '0')
			};
			self.setComercios();
		}
	},

	setComercios() {
		let self = this;

		// Articulos en tienda
		let items = [];
		let size = self.items.length;
		for(let i = 0; i < size; i++) {
			if(self.items[i].selected) {
				items.push(self.items[i].idItem);
			}
		}

		let parameters = {
			nombre: self.storeObj.nombre,
			direccion: self.storeObj.direccion,
			idComercioType: self.storeObj.idComercioType,
			telefono: self.storeObj.telefono,
			email: self.storeObj.email,
			personaContacto: self.storeObj.personaContacto,
			horarioApertura: self.storeObj.horarioApertura,
			horarioCierre: self.storeObj.horarioCierre,
			numCajas: self.storeObj.numCajas,
			numRefrigeradores: self.storeObj.numRefrigeradores,
			latitude: self.storeObj.latitude,
			longitude: self.storeObj.longitude,
			altitude: self.storeObj.altitude,
			accuracy: self.storeObj.accuracy,
			abiertaPublico: self.storeObj.abiertaPublico,
			ventanilla: self.storeObj.ventanilla,
			apertura24H: self.storeObj.apertura24H,
			acceptStoreImages: JSON.stringify(self.acceptStoreImages),
			items: JSON.stringify(items)
		};

		// Imágenes
		let imgSize = self.acceptStoreImagesFile.length;
		for(let i = 0; i < imgSize; i++) {
			parameters['img' + i] = self.acceptStoreImagesFile[i];
		}

		ajaxComunCallWithCallback('setComercios', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2473;
				let successContent = pf.const.language.RSC2492;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!show_all_stores';
			}
		});
	}
};