stcmbackend.catalogos = {
	sharedEvents(self) {
		// Vover a Catálogos
		$('#back').on('click', function() {
			window.location.href = '#!catalogos';
		});

		// Carga de imagen principal
		$('#mainPictureIMG').on('click', function() {
			$('#mainPicture').trigger('click');
		});
		$('#mainPicture').change(function(evt) {
			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.mainPicture = file;
				let src = URL.createObjectURL(evt.target.files[0]);
				$('#btn_mainPicture').show();
				$('#mainPictureIMG').attr('src', src);
				$('#morePictures').show();
			}
		});
	},

	renderArticles(self) {
		let table = `
			<table id="tableArticles" class="table table-hover tRegs">
				<thead>
					<tr>
						<th class="text-center" scope="col" title="">
							<div class="div-global-selection">
								<input type="checkbox" class="globalSelection">
							</div>
						</th>
						<th scope="col" title="${pf.const.language.RSC1898}">${pf.const.language.RSC1898}</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>
					</tr>
				</thead>

				<thead class="filtersArticles">
					<tr>
						<td>selector</td>
						<td>img</td>
						<td>name</td>
						<td>description</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.articles.length;
		for(let i = 0; i < size; i++) {
			if(self.articles[i].enabled == '0') {
				continue;
			}

			let checked = '';
			if(self.articles[i].checked === 1) {
				checked = 'checked';
			}

			let imgPrincipalArray = self.articles[i].imgPrincipal.split('/');

			// Carpeta
			let raiz = stcm.const.downloads + 'articulos/' + self.articles[i].codArt + '/' + imgPrincipalArray[imgPrincipalArray.length - 1];

			table += `
				<tr class="c-pointer" data-id="${self.articles[i].codArt}" data-index="${i}">
					<td class="text-center" data-id="${self.articles[i].codArt}">
						<div class="div-single-selection">
							<input type="checkbox" class="selection" data-index="${i}" ${checked}>
						</div>
					</td>
					<td class="text-center text-truncate">
						<img src="${raiz}" class="border ob-fit-cont" height="80" width="80">
					</td>
					<td class="text-truncate" title="${self.articles[i].articulo}">${self.articles[i].articulo}</td>
					<td class="text-truncate" title="${self.articles[i].descripcion}">${self.articles[i].descripcion}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

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

			if(title == 'selector' || title == 'img') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#tableArticles').DataTable({
			retrieve: true,
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '150px', orderable: false, targets: 1}
			],
			aaSorting: []
		});

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

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

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

		stcmbackend.catalogos.tableArticlesEvents(self);

		$('#tableArticles').on('draw.dt', function() {
			stcmbackend.catalogos.tableArticlesEvents(self);
		});

		// Selección de múltiples articulos
		$('#selectArticles').off().on('click', function() {
			self.articlesChecked = [];

			let size = self.articles.length;
			for(let i = 0; i < size; i++) {
				if(self.articles[i].checked === 1) {
					self.articlesChecked.push(self.articles[i]);
				}
			}

			$('#closeArticles').trigger('click');

			stcmbackend.catalogos.tableArticlesChecked(self);
		});
	},

	tableArticlesEvents(self) {
		inputControl();

		// Seleccionar por tr
		$('#tableArticles tbody tr').off().on('click', function() {
			let index = $(this).data('index');
			let checked = $(this).find('.selection').prop('checked');

			if(!checked) {
				self.articles[index].checked = 1;
				$(this).find('.selection').prop('checked', true);
			} else {
				self.articles[index].checked = 0;
				$(this).find('.selection').prop('checked', false);
			}

			inputControl();
		});

		// Seleccionar por checbox
		$('.selection').off().on('change', function() {
			let index = $(this).data('index');
			let checked = $(this).prop('checked');

			if(checked) {
				self.articles[index].checked = 0;
				$(this).prop('checked', false);
			} else {
				self.articles[index].checked = 1;
				$(this).prop('checked', true);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelection').off().on('change', function() {
			if(this.checked) {
				$('.selection').each(function() {
					if(!$(this).prop('checked')) {
						$(this).prop('checked', false);
						$(this).trigger('change');
					}
				});
			} else {
				$('.selection').each(function() {
					if($(this).prop('checked')) {
						$(this).prop('checked', true);
						$(this).trigger('change');
					}
				});
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	},

	tableArticlesChecked(self) {
		let table = `
			<table id="tableArticlesChecked" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1898}">${pf.const.language.RSC1898}</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.RSC126}">${pf.const.language.RSC126}</th>
						<th scope="col" title=""></th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.articlesChecked.length;
		for(let i = 0; i < size; i++) {
			let imgPrincipalArray = self.articlesChecked[i].imgPrincipal.split('/');

			// Carpeta
			let raiz = stcm.const.downloads + 'articulos/' + self.articlesChecked[i].codArt + '/' + imgPrincipalArray[imgPrincipalArray.length - 1];

			table += `
				<tr data-id="${self.articlesChecked[i].codArt}">
					<td class="text-center text-truncate">
						<img src="${raiz}" class="border ob-fit-cont" height="80" width="80">
					</td>
					<td class="text-truncate" title="${self.articlesChecked[i].articulo}">${self.articlesChecked[i].articulo}</td>
					<td class="text-truncate" title="${self.articlesChecked[i].descripcion}">${self.articlesChecked[i].descripcion}</td>
					<td class="text-center">
						<span class="d-none">${(self.articlesChecked[i].enabled == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(self.articlesChecked[i].enabled == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate text-center">
						<button type="button" class="btn btn-eye loadFile searchInfo" data-toggle="modal" data-target="#infoModal" data-id="${self.articlesChecked[i].codArt}">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer circle-container delete" data-id="${self.articlesChecked[i].codArt}" data-index="${i}">
							${stcmbackend.svg.trash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

		let dataTable = $('#tableArticlesChecked').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '120px', orderable: false, targets: 0},
				{width: '60px', targets: 3},
				{width: '30px', orderable: false, targets: 4},
				{width: '30px', orderable: false, targets: 5}
			],
			aaSorting: []
		});

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

		stcmbackend.catalogos.tableArticlesCheckedEvents(self);

		$('#articles').on('draw.dt', function() {
			stcmbackend.catalogos.tableArticlesCheckedEvents(self);
		});
	},

	tableArticlesCheckedEvents(self) {
		$('.delete').off().on('click', function() {
			let index = $(this).data('index');
			let id = $(this).data('id');
			self.articlesChecked.splice(index, 1);
			stcmbackend.catalogos.tableArticlesChecked(self);

			let size = self.articles.length;
			for(let i = 0; i < size; i++) {
				if(self.articles[i].codArt == id) {
					self.articles[i]['checked'] = 0;
					break;
				}
			}
			$('#tableArticles').dataTable().fnDestroy();
			stcmbackend.catalogos.renderArticles(self);
		});

		// Información de artículo
		$('.searchInfo').off().on('click', function() {
			let id = $(this).data('id');

			stcmbackend.catalogos.getRewardsArticlesByID(id, self);
		});
	},

	getRewardsArticlesByID(id, self) {
		let parameters = {
			codArt: id
		};
		ajaxComunCallWithCallback('getRewardsArticlesByID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.dataArticle = ajaxReturn.result;
				stcmbackend.catalogos.renderDataArticle(self);
			}
		});
	},

	renderDataArticle(self) {
		// Título
		$('#artTitle').text(self.dataArticle['0'].articulo);
		// Descripción
		$('#articleDesc').text(self.dataArticle['0'].descripcion);

		let pathArray = self.dataArticle['0'].imgPrincipal.split('/');
		let raiz = stcm.const.downloads + 'articulos/' + self.dataArticle['0'].codArt + '/' + pathArray[pathArray.length - 1];

		// Imagen central
		$('#mainIMGArticle').attr('src', raiz + '?stamp=' + new Date().getTime());

		// Otras imágenes
		let othersIMG = `
			<div class="px-2 pb-2">
				<img src="${raiz}" class="border c-pointer changeIMG" height="80" width="80">
			</div>
		`;
		let size = self.dataArticle.imagenes.length;
		for(let i = 0; i < size; i++) {
			let patOthershArray = self.dataArticle.imagenes[i].img.split('/');

			// Control de imagen por defecto
			if(patOthershArray[patOthershArray.length - 1] == 'articulo.png') {
				continue;
			}

			let raizOthers = stcm.const.downloads + 'articulos/' + self.dataArticle['0'].codArt + '/' + patOthershArray[patOthershArray.length - 1];

			let othersIMGBlock = `
				<div class="px-2 pb-2">
					<img src="${raizOthers}" class="border c-pointer changeIMG" height="80" width="80">
				</div>
			`;

			othersIMG += othersIMGBlock;
		}

		$('#othersIMGArticle').html(othersIMG);

		$('.changeIMG').off().on('click', function() {
			let src = $(this).attr('src');

			// Imagen central
			$('#mainIMGArticle').attr('src', src + '?stamp=' + new Date().getTime());
		});

		// Tabla de países
		let table = `
			<table id="tableArticleCountries" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC1936}">${pf.const.language.RSC1936}</th>
						<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
						<th scope="col" title="${pf.const.language.RSC953}">${pf.const.language.RSC953}</th>
					</tr>
				</thead>

				<tbody>
		`;

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

		let sizeC = self.dataArticle.countries.length;
		for(let i = 0; i < sizeC; i ++) {
			if(allowedCountries.indexOf(self.dataArticle.countries[i].country) == -1) {
				continue;
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.dataArticle.countries[i].country}">${self.dataArticle.countries[i].country}</td>
					<td class="text-truncate" title="${self.dataArticle.countries[i].disponible}">${self.dataArticle.countries[i].disponible}</td>
					<td class="text-truncate" title="${self.dataArticle.countries[i].value}">${self.dataArticle.countries[i].value}</td>
					<td class="text-truncate" title="${self.dataArticle.countries[i].currency}">${self.dataArticle.countries[i].currency}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

		let tableArticleCountries = $('#tableArticleCountries').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			ordering: false,
			autoWidth: false
		});

		// Ocultar botones de tabla
		hideTableButtons('tableArticleCountries');
	}
};