let CatalogosEditController = {
	user: null,
	language: '',
	idCatalogue: '',
	data: '',
	imagesURL: '',
	maxSize: 0,
	countriesCatalogue: [],
	countries: [],
	articles: null,
	articlesChecked: [],
	mainPicture: null,
	mainPictureControl: '',
	articlesCatalogue: [],
	addArticle: [],
	deleteArticle: [],
	dataArticle: null,
	loaders: {},

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.idCatalogue = atob(sessionStorage.getItem('idCatalogue'));
		self.data = '';
		self.imagesURL = '';
		self.maxSize = 0;
		self.countriesCatalogue = [];
		self.countries = [];
		self.articles = null;
		self.articlesChecked = [];
		self.mainPicture = null;
		self.mainPictureControl = '';
		self.articlesCatalogue = [];
		self.addArticle = [];
		self.deleteArticle = [];
		self.dataArticle = null;
		self.loaders = {
			getPaises: false,
			getAllRewardsArticles: 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.RSC1885 + ' - ' + pf.const.language.RSC225);

		// 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');

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

		// Imagenes por defecto
		self.imagesURL = stcm.const.downloads + 'catalogos/catalogo.png';
		$('#mainPictureIMG').attr('src', self.imagesURL);
		$('#btn_mainPicture').hide();

		self.loadLanguage();
		self.applyEvents();

		addLoader();
		self.getRewardsCatalogsByID();

		// Collapse
		addEventArrowTableHeader();

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

	loadLanguage() {
		pf.rsc.translateByTag('text');
		pf.rsc.translateByTag('placeholder');

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

	applyEvents() {
		let self = this;

		stcmbackend.catalogos.sharedEvents(self);

		// Borrar imagen principal
		$('#btn_mainPicture').on('click', function() {
			$('#mainPicture').val(null);
			$('#btn_mainPicture').hide();
			$('#mainPictureIMG').attr('src', self.imagesURL + '?stamp=' + new Date().getTime());
			self.mainPicture = null;
			self.mainPictureControl = 'new';
		});

		// Modal de artículos
		$('#btn-addArticles').on('click', function() {
			if(!self.articles) {
				self.getAllRewardsArticles();
			} else {
				// Tabla de resultados
				stcmbackend.catalogos.renderArticles(self);
			}
		});

		// Actualizar catálogo
		$('#save').click(function() {
			self.updateRewardsCatalog();
		});
	},

	getRewardsCatalogsByID() {
		let self = this;

		let parameters = {
			codCatalog: self.idCatalogue
		};
		ajaxComunCallWithCallback('getRewardsCatalogsByID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result['0'];

				let sizeA = ajaxReturn.result.articles.length;
				for(let i = 0; i < sizeA; i++) {
					self.articlesCatalogue.push(ajaxReturn.result.articles[i].codArt);
				}

				let sizeC = ajaxReturn.result.countries.length;
				for(let i = 0; i < sizeC; i++) {
					self.countriesCatalogue.push(ajaxReturn.result.countries[i].country);
				}

				self.renderCatalogue();
				self.getCountries();
				self.getAllRewardsArticles();
			}
		}, false);
	},

	renderCatalogue() {
		let self = this;

		$('#name').val(self.data.catalogo);
		// Activo
		if(self.data.enabled == '1') {
			$('#enabled').prop('checked', true);
		}
		$('#description').val(self.data.descripcion);

		let imgPrincipalArray = self.data.imgPrincipal.split('/');
		let raiz = stcm.const.downloads + 'catalogos/' + self.idCatalogue + '/' + imgPrincipalArray[imgPrincipalArray.length - 1];
		$('#mainPictureIMG').attr('src', raiz);
		if(imgPrincipalArray[imgPrincipalArray.length - 1] != 'catalogo.png') {
			$('#btn_mainPicture').show();
			self.mainPictureControl = self.data.imgPrincipal;
		} else {
			self.mainPictureControl = 'new';
		}

		let start = '';
		if(self.data.fechaInicio) {
			let startArray = self.data.fechaInicio.split(' ');
			start = startArray[0];
		}
		$('#startDate').val(start);
		let end = '';
		if(self.data.fechaFin) {
			let endArray = self.data.fechaFin.split(' ');
			end = endArray[0];
		}
		$('#endDate').val(end);
	},

	getCountries() {
		let self = this;

		ajaxComunCallWithCallback('getPaises', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					if(ajaxReturn.result[i].enabled == '1') {
						ajaxReturn.result[i]['checked'] = 0;
						if(self.countriesCatalogue.indexOf(ajaxReturn.result[i].isocode) !== -1) {
							ajaxReturn.result[i]['checked'] = 1;
						}
						self.countries.push(ajaxReturn.result[i]);
					}
				}

				self.renderCountriesEnabled();

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

	renderCountriesEnabled() {
		let self = this;

		let table = `
			<table id="tableCountries" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="ISO"">
							ISO
						</th>
						<th scope="col" title="${pf.const.language.RSC549}">
							${pf.const.language.RSC549}
							<span class="float-right">${pf.const.language.RSC278}:</span>
						</th>
						<th scope="col" class="pl-0">
							<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>

				<tbody>
		`;

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

		let size = self.countries.length;
		for(let i = 0; i < size; i ++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.countries[i].isocode) == -1) {
				continue;
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.countries[i].isocode}">${self.countries[i].isocode}</td>
					<td class="text-truncate" title="${self.countries[i].descripcion}">${self.countries[i].descripcion}</td>
					<td class="pl-0">
						<div class="custom-control custom-switch">
							<input id="${self.countries[i].isocode}" type="checkbox" class="custom-control-input uSwitch" ${(self.countries[i].checked == '1' ? 'checked' : '')} data-index="${i}">
							<label for="${self.countries[i].isocode}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

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

		let tableCountries = $('#tableCountries').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			searching: false,
			ordering: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 0},
				{width: '30px', targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1935,
				className: 'd-none',
				title: pf.const.language.RSC1935,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

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

		// Si todos los checkbox están seleccionados, se selecciona el checkbox principal, y viceversa
		// Comprobación 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);

			for(obj in self.countries) {
				if(this.checked) {
					self.countries[obj].checked = 1;
				} else {
					self.countries[obj].checked = 0;
				}
			}
		});

		// Si todos los checkbox están seleccionados, se selecciona el checkbox principal, y viceversa 
		$('.uSwitch').on('click', function() {
			let index = $(this).data('index');
			if(this.checked) {
				self.countries[index].checked = 1;
			} else {
				self.countries[index].checked = 0;
			}

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

	getAllRewardsArticles() {
		let self = this;

		ajaxComunCallWithCallback('getAllRewardsArticles', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.articles = ajaxReturn.result;
				let size = self.articles.length;
				for(let i = 0; i < size; i++) {
					self.articles[i]['checked'] = 0;
					if(self.articlesCatalogue.indexOf(self.articles[i].codArt) !== -1) {
						self.articles[i]['checked'] = 1;
						self.articlesChecked.push(self.articles[i]);
					}
				}

				// Tabla de artículos en catálogo
				stcmbackend.catalogos.tableArticlesChecked(self);

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

	updateRewardsCatalog() {
		let self = this;

		// Control de los valores Nombre y Dexcripción
		let formIncomplete = false;

		let catalogo = $('#name').val().trim();
		if(catalogo == '') {
			formIncomplete = true;
			$('#name').addClass('is-invalid');
			$('[for="name"]').addClass('is-invalid');
		} else {
			$('#name').removeClass('is-invalid');
			$('[for="name"]').removeClass('is-invalid');
		}

		let descripcion = $('#description').val().trim();
		if(descripcion == '') {
			formIncomplete = true;
			$('#description').addClass('is-invalid');
			$('[for="description"]').addClass('is-invalid');
		} else {
			$('#description').removeClass('is-invalid');
			$('[for="description"]').removeClass('is-invalid');
		}

		// Comprobación
		if(formIncomplete) {
			let alertTitle = pf.const.language.RSC1886;
			let alertText = pf.const.language.RSC101;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return;
		}

		let enabled = ($('#enabled').prop('checked') ? '1' : '0');

		// Country
		let country = [];
		let size = self.countries.length
		for(let i = 0; i < size; i++) {
			if(self.countries[i].checked == 1) {
				let string = self.countries[i].isocode;

				country.push(string);
			}
		}

		let fechaInicio = $('#startDate').val();
		let fechaFin = $('#endDate').val();

		let fi = new Date(fechaInicio);
		let ff = new Date(fechaFin);

		if(ff <= fi && ff !== '') {
			$('#endDate').addClass('is-invalid');
			$('[for="endDate"]').addClass('is-invalid');
			let alertTitle = pf.const.language.RSC1886;
			let alertText = pf.const.language.RSC1928;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return;
		} else {
			$('#endDate').removeClass('is-invalid');
			$('[for="endDate"]').removeClass('is-invalid');
		}

		// Articles
		let articles = [];
		let sizeA = self.articlesChecked.length
		for(let i = 0; i < sizeA; i++) {
			let string = self.articlesChecked[i].codArt;

			articles.push(string);
		}

		// Artículos para añadir
		let addArticle = [];
		let sizeAC = articles.length;
		for(let i = 0; i < sizeAC; i++) {
			if(self.articlesCatalogue.indexOf(articles[i]) === -1) {
				addArticle.push(articles[i]);
			}
		}

		// Artículos para borrar
		let deleteArticle = [];
		let sizeCA = self.articlesCatalogue.length;
		for(let i = 0; i < sizeCA; i++) {
			if(articles.indexOf(self.articlesCatalogue[i]) === -1) {
				deleteArticle.push(self.articlesCatalogue[i]);
			}
		}

		let parameters = {
			codCatalog: self.idCatalogue,
			catalogo: catalogo,
			descripcion: descripcion,
			enabled: enabled,
			imgPrincipal: self.mainPicture,
			mainPictureControl: self.mainPictureControl,
			country: country,
			fechaInicio: fechaInicio,
			fechaFin: fechaFin,
			addArticle: addArticle,
			deleteArticle: deleteArticle,
			path: stcm.const.downloads + 'catalogos/'
		};
		ajaxComunCallWithCallback('updateRewardsCatalog', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1885;
				let successContent = pf.const.language.RSC1933;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!catalogos';
			}
		});
	}
};