let ProductosController = {
	user: null,
	language: null,
	data: null,
	projects: null,

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = null;
		self.projects = null;
	},

	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.RSC2068);

		// Opciones de header
		let jsonsubopt = {
			new: 'new'
		};

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

		$('#searchProduct').prop('placeholder', pf.const.language.RSC2069);

		// Imagenes para Proyecto nuevo y Proyecto existente
		let srcImgNew = stcm.const.downloads + 'products/new_project.png';
		$('#newProductIMG').attr('src', srcImgNew);
		let srcImgEdit = stcm.const.downloads + 'products/existing_project.png';
		$('#editProductIMG').attr('src', srcImgEdit);

		self.loadLang();

		ajaxComunCallWithCallback('getAllProductsAnaquel', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				self.renderData();
			}
		});

		self.applyEvents();
	},

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

	applyEvents() {
		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!productos_new';
		});
	},

	renderData() {
		let self = this;

		let products = '';

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

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

			let menuButton = '';
			if(self.data[i].system != '1') {
				menuButton = `
					<div id="dropdownMenuButton" class="product_menu_b border text-center c-pointer" data-id="${self.data[i].idProduct}" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
						${stcmbackend.svg.threeDotsVerticalBig}
					</div>
					<div class="dropdown-menu dropdown-menu-right shadow" aria-labelledby="dropdownMenuButton" data-id="${self.data[i].idProduct}">
						<a href="#" class="dropdown-item ddEdit">${pf.const.language.RSC225}</a>
						<a href="#" class="dropdown-item ddDelete">${pf.const.language.RSC95}</a>
					</div>
				`;
			}

			let srcImg = stcm.const.downloads + 'products/default_img/' + self.data[i].image;

			products += `
				<!-- Producto -->
				<div class="product_menu_card_6 m-0 p-3 align-self-stretch">
					<div class="card p-2 h-100 new_edit_project products-shadow-style" data-product="${self.data[i].idProduct}" data-survey="${self.data[i].isSurvey}">
						<img src="${srcImg}" class="card-img-top w-100" alt="Product Cover">
						<div class="card-body border-top c-pointer">
							<h5 class="card-title product_title text-center two_lines_truncate product-card">${self.data[i].name}</h5>
							<p class="card-text text-center four_lines_truncate">${self.data[i].description}</p>
						</div>
					</div>
					${menuButton}
				</div>
			`;
		}

		$('#productsContainer').html(products);

		self.dataEvents();
	},

	dataEvents() {
		let self = this;

		// Buscar producto por tecla
		$('#searchProduct').on('keyup', function() {
			let value = $('#searchProduct').val().toLowerCase();

			$('.product_menu_card_6').show();

			$('.product-card').each(function() {
				let title = $(this).text().toLowerCase();

				if(!title.includes(value)) {
					$(this).parent().parent().parent().hide();
				}
			});
		});

		// Buscar producto por pegado
		$('#searchProduct').on('paste', function() {
			setTimeout(function() {
				let value = $('#searchProduct').val().toLowerCase();

				$('.product_menu_card_6').show();

				$('.product-card').each(function() {
					let title = $(this).text().toLowerCase();

					if(!title.includes(value)) {
						$(this).parent().parent().parent().hide();
					}
				});
			}, 200);
		});

		// Editar producto
		$('.ddEdit').off().on('click', function(e) {
			e.preventDefault();
			let idProduct = $(this).parent().data('id');

			sessionStorage.setItem('idProduct', btoa(idProduct));
			window.location.href = '#!productos_edit';
		});

		// Eliminar producto
		$('.ddDelete').off().on('click', function(e) {
			e.preventDefault();
			let idProduct = $(this).parent().data('id');

			self.deleteProductsAnaquel(idProduct);
		});

		// Modal para crear / editar proyecto
		$('.new_edit_project').off().on('click', function() {
			let idProduct = $(this).data('product');
			let survey = $(this).data('survey');
			$('#newProductProject').data('product', idProduct);
			$('#newProductProject').data('survey', survey);
			$('#editProductProject').data('product', idProduct);
			$('#editProductProject').data('survey', survey);
			$('#modalNewEdit').modal('toggle');
		});

		// Proyecto nuevo a través de producto
		$('#newProductProject').off().on('click', function() {
			$('#modalNewEdit').modal('toggle');
			setTimeout(function() {
				let idProduct = $('#newProductProject').data('product');
				let survey = $('#newProductProject').data('survey');
				sessionStorage.setItem('idProductToCreate', btoa(idProduct));
				sessionStorage.setItem('productToCreateIsSurvey', btoa(survey));
				sessionStorage.setItem('productTemplate', '');
				sessionStorage.setItem('idProjectProduct', '');
				sessionStorage.setItem('numberRecords', '');
				sessionStorage.setItem('stampMissionProduct', '');
				sessionStorage.setItem('idMisionProduct', '');
				sessionStorage.setItem('productCriteria', '');
				sessionStorage.setItem('stepByStepEncuesta', null);
				sessionStorage.setItem('editProductProject', '0');
				window.location.href = '#!producto_proyecto_new';
			}, 300);
		});

		// Modal con todos los proyectos
		$('#editProductProject').off().on('click', function() {
			$('#modalNewEdit').modal('toggle');
			$('#modalProjectsTable').modal('toggle');

			ajaxComunCallWithCallback('getCMBPProjects', {}, function(ajaxReturn) {
				if(ajaxReturn) {
					self.projects = ajaxReturn.result;

					self.renderProjects();
				}
			});
		});
	},

	renderProjects() {
		let self = this;

		let table = `
			<table id="tableProjects" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC143}">${pf.const.language.RSC143}</th>
						<th scope="col" title="${pf.const.language.RSC144}">${pf.const.language.RSC144}</th>
						<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
					</tr>
				</thead>

				<thead class="filtersProjectsResult">
					<tr>
						<td>name</td>
						<td>pais</td>
						<td>leader</td>
						<td>client</td>
						<td>creationDate</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.projects.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.projects[i].country != '' && allowedCountries.indexOf(self.projects[i].country) == -1) {
				continue;
			}

			table += `
				<tr class="c-pointer projectSelected" data-id="${self.projects[i].id}">
					<td class="text-truncate" title="${self.projects[i].NombreProyecto}">${self.projects[i].NombreProyecto}</td>
					<td class="text-truncate" title="${self.projects[i].country}">${self.projects[i].country}</td>
					<td class="text-truncate" title="${self.projects[i].LiderProyecto}">${self.projects[i].LiderProyecto}</td>
					<td class="text-truncate" title="${self.projects[i].ClienteInterno}">${self.projects[i].ClienteInterno}</td>
					<td class="text-truncate" title="${self.projects[i].FechaDeAlta}">${self.projects[i].FechaDeAlta}</td>
				</tr>
			`;
		}

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

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

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

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

		let dataTable = $('#tableProjects').DataTable({
			retrieve: true,
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '40px', targets: 1},
				{width: '140px', targets: 4}
			],
			order: [[4, 'desc']]
		});

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

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

		self.projectsTableEvents();

		$('#resultTable').on('draw.dt', function() {
			self.projectsTableEvents();
		});
	},

	projectsTableEvents() {
		$('.projectSelected').off().on('click', function() {
			let idProjectProduct = $(this).data('id');
			$('#modalProjectsTable').modal('toggle');

			setTimeout(function() {
				let idProduct = $('#editProductProject').data('product');
				let survey = $('#editProductProject').data('survey');
				sessionStorage.setItem('idProductToCreate', btoa(idProduct));
				sessionStorage.setItem('productToCreateIsSurvey', btoa(survey));
				sessionStorage.setItem('productTemplate', '');
				sessionStorage.setItem('idProjectProduct', idProjectProduct);
				sessionStorage.setItem('numberRecords', '');
				sessionStorage.setItem('stampMissionProduct', '');
				sessionStorage.setItem('idMisionProduct', '');
				sessionStorage.setItem('productCriteria', '');
				sessionStorage.setItem('stepByStepEncuesta', null);
				sessionStorage.setItem('editProductProject', '1');
				window.location.href = '#!producto_proyecto_edit';
			}, 300);
		});
	},

	deleteProductsAnaquel(idProduct) {
		let parameters = {
			idProduct: idProduct
		};
		ajaxComunCallWithCallback('deleteProductsAnaquel', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2048;
				let successContent = pf.const.language.RSC2076;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/productos/productos.html', 'wrapper', ProductosController);
			}
		});
	}
};