let ArticulosCatalogoEditController = {
	user: null,
	language: '',
	idArticle: '',
	data: '',
	imagesURL: '',
	maxSize: 0,
	otherPicturesIMG: [],
	mainPicture: null,
	otherPictures: [],
	countries: [],
	countriesArticles: [],
	mainPictureControl: '',
	imgControl: [],

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.idArticle = atob(sessionStorage.getItem('idArticle'));
		self.data = '';
		self.imagesURL = '';
		self.maxSize = 0;
		self.otherPicturesIMG = [];
		self.mainPicture = null;
		self.otherPictures = [];
		self.countries = [];
		self.countriesArticles = [];
		self.mainPictureControl = '';
		self.imgControl = [];
	},

	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.RSC1892 + ' - ' + 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 + 'articulos/articulo.png';
		$('#mainPictureIMG').attr('src', self.imagesURL);
		$('#btn_mainPicture').hide();

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

		addLoader();
		self.getRewardsArticlesByID();

		// Collapse
		addEventArrowTableHeader();

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

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

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

	applyEvents() {
		let self = this;

		stcmbackend.articulos.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';
		});

		// Actualizar artículo
		$('#save').click(function() {
			self.updateRewardsArticle();
		});
	},

	getRewardsArticlesByID() {
		let self = this;

		let parameters = {
			codArt: self.idArticle
		};
		ajaxComunCallWithCallback('getRewardsArticlesByID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				self.renderArticle();
				self.getCountries();

				let size = self.data.imagenes.length;
				if(size < 1) {
					self.otherPicturesIMG[0] = self.imagesURL;
					self.otherPictures[0] = null;
					self.imgControl[0] = 'new';
				} else {
					for(let i = 0; i < size; i++) {
						let img = self.data.imagenes[i].img.split('/');
						let raiz = stcm.const.downloads + 'articulos/' + self.idArticle + '/' + img[img.length - 1];
						self.otherPicturesIMG[i] = raiz;
						self.otherPictures[i] = null;
						self.imgControl[i] = self.data.imagenes[i].img;
					}

					if(self.otherPicturesIMG[self.otherPicturesIMG.length - 1] != stcm.const.downloads + 'articulos/' + self.idArticle + '/articulo.png') {
						self.otherPicturesIMG.push(self.imagesURL);
						self.otherPictures.push(null);
						self.imgControl.push('new');
					}
				}

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

	renderArticle() {
		let self = this;

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

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

	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') {
						self.countries.push(ajaxReturn.result[i]);
					}
				}

				self.renderCountriesEnabled();

				removeLoader();
			}
		}, 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.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>
						<th scope="col" class="pl-2">
							<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>iso</td>
						<td>country</td>
						<td>amount</td>
						<td>value</td>
						<td>coin</td>
						<td>select</td>
					</tr>
				</thead>

				<tbody>
		`;

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

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

			// Onjeto para controlar los artículos por país
			let obj = {
				iso: self.countries[i].isocode,
				name: self.countries[i].descripcion,
				value: 0,
				currency: self.countries[i].currency,
				amount: 0,
				enabled: 0
			}

			let cSize = self.data.countries.length;
			for(let j = 0; j < cSize; j++) {
				if(self.data.countries[j].country == self.countries[i].isocode) {
					obj.value = self.data.countries[j].value;
					obj.amount = self.data.countries[j].disponible;
					obj.currency = self.data.countries[j].currency;
					obj.enabled = 1;
				}
			}

			// Array de objetos articulo/país
			self.countriesArticles.push(obj);

			let value = obj.value;
			let amount = obj.amount;
			let currency = obj.currency;

			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="text-truncate">
						<span id="amount${index}" class="d-none">${amount}</span>
						<input id="amountInput${index}" type="number" class="form-control amountInput" value="${amount}" title="${amount}" data-index="${index}">
					</td>
					<td class="text-truncate">
						<span id="value${index}" class="d-none">${value}</span>
						<input id="valueInput${index}" type="number" class="form-control valueInput" value="${value}" title="${value}" data-index="${index}">
					</td>
					<td class="text-truncate p-1">
						<select id="coin_${index}" class="custom-select coinSelect" data-index="${index}">
							<option value="${self.countries[i].currency}" ${(currency == self.countries[i].currency ? 'selected' : '')}>${self.countries[i].currency}</option>
							<option value="points" ${(currency == 'points' ? 'selected' : '')}>${pf.const.language.RSC1897}</option>
						</select>
					</td>
					<td class="pl-2">
						<div class="custom-control custom-switch">
							<input id="${self.countries[i].isocode}" type="checkbox" class="custom-control-input uSwitch" ${(obj.enabled == 1 ? 'checked' : '')} data-index="${index}">
							<label for="${self.countries[i].isocode}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
				</tr>
			`;

			index++;
		}

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

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

		// Setup - add a text input to each footer cell
		$('#countries .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 tableCountries = $('#tableCountries').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			ordering: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 0},
				{width: '130px', targets: 2},
				{width: '100px', targets: 3},
				{width: '100px', targets: 4},
				{width: '30px', targets: 5}
			],
			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');
		});

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

		stcmbackend.articulos.tableCountriesEnabledEvents(self, true);
	},

	otherPicturesRender() {
		let self = this;

		let picturesIMG = '';
		let size = self.otherPicturesIMG.length;
		for(let i = 0; i < size; i++) {
			let trash = '';
			if(self.otherPicturesIMG[i] === self.imagesURL || self.otherPicturesIMG[i].indexOf('articulo.png') !== -1) {
				trash = 'd-none';
			}
			picturesIMG += `
				<div class="col-12 col-lg-4 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">
						<img id="otherPicture_${i}IMG" src="${self.otherPicturesIMG[i]}" class="border c-pointer loadPicture ob-fit-cont" alt="Logo" height="100" width="100" data-index="${i}">
					</div>
					<button id="btn_otherPicture_${i}" type="button" class="btn btn-nav deletePicture ${trash}" data-index="${i}">
						${stcmbackend.svg.trash}
					</button>
				</div>
			`;
		}

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

		self.otherPicturesEvents();
	},

	otherPicturesEvents() {
		let self = this;

		// 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.otherPictures[index] = file;
				let src = URL.createObjectURL(evt.target.files[0]);
				self.otherPicturesIMG[index] = src;
				self.imgControl[index] = 'new';

				if(index === (self.otherPicturesIMG.length - 1)) {
					self.otherPicturesIMG.push(self.imagesURL);
				}

				self.otherPicturesRender();
			}
		});

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

			self.otherPicturesIMG.splice(index, 1);
			self.otherPictures.splice(index, 1);
			self.imgControl.splice(index, 1);

			self.otherPicturesRender();
		});
	},

	updateRewardsArticle() {
		let self = this;

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

		let articulo = $('#name').val().trim();
		if(articulo == '') {
			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.RSC1893;
			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.countriesArticles.length
		for(let i = 0; i < size; i++) {
			if(self.countriesArticles[i].enabled == 1) {
				// ISO#value#currency#amount
				let string = self.countriesArticles[i].iso + '#' + self.countriesArticles[i].value + '#' + self.countriesArticles[i].currency + '#' + self.countriesArticles[i].amount;

				country.push(string);
			}
		}

		let parameters = {
			codArt: self.idArticle,
			articulo: articulo,
			descripcion: descripcion,
			enabled: enabled,
			imgPrincipal: self.mainPicture,
			mainPictureControl: self.mainPictureControl,
			path: stcm.const.downloads + 'articulos/',
			country: country,
			imgControl: self.imgControl
		};

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

		ajaxComunCallWithCallback('updateRewardsArticle', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC1893;
				let successContent = pf.const.language.RSC1918;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!articulos_catalogo';
			}
		});
	}
};