let CPGLicensesController = {
	user: null,
	language: '',
	countries: [],
	licensesAssignedCountry: {},
	licensesFreeCountry: {},
	licensesUsedCountry: {},
	data: {},

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.countries = [];
		self.licensesAssignedCountry = {};
		self.licensesFreeCountry = {};
		self.licensesUsedCountry = {};
		self.data = {};
	},

	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.RSC1716 + ' - ' + pf.const.language.RSC519);

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

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

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

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

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

		// Iniciar spinner
		addLoader();

		ajaxComunCallWithCallback('getLicencesByCountry', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					// Licencias asignadas por país
					self.licensesAssignedCountry[ajaxReturn.result[i].pais] = parseInt(ajaxReturn.result[i].licencias);
					self.licensesUsedCountry[ajaxReturn.result[i].pais] = 0;
				}

				ajaxComunCallWithCallback('getSocialLabsLicencesByCPG', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						let size = ajaxReturn.result.cpgs.length;
						for(let i = 0; i < size; i ++) {
							self.licensesUsedCountry[ajaxReturn.result.cpgs[i].country] += parseInt(ajaxReturn.result.cpgs[i].numLicencesUsed);
		
							if(ajaxReturn.result.cpgs[i].country in self.data) {
								self.data[ajaxReturn.result.cpgs[i].country].push(ajaxReturn.result.cpgs[i]);
							} else {
								self.data[ajaxReturn.result.cpgs[i].country] = [ajaxReturn.result.cpgs[i]];
							}
						}
		
						$('#licensesContainer').html('');
		
						let counter = 0;
						for(let element in self.data) {
							self.countries.push(element);
							self.renderData(self.data[element], counter);
		
							counter++;
						}

						self.getFreeLicences(self.countries[0], 0);
		
						// Collapse
						addEventArrowTableHeader();
		
						// Fin de spinner
						removeLoader();
					}
				}, false);
			}
		}, false);
	},

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

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

	applyEvents() {
		let self = this;

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

	getFreeLicences(country, counter) {
		let self = this;

		let parameters = {
			country: country
		}
		ajaxComunCallWithCallback('getFreeLicences', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.licensesFreeCountry[country] = parseInt(ajaxReturn.result);
				$('#to-assign' + counter).text(ajaxReturn.result);

				let cero = self.licensesAssignedCountry[country] - self.licensesFreeCountry[country] - self.licensesUsedCountry[country];
				$('#cpg-0-' + counter).text(cero);

				counter++;
				if(counter < self.countries.length) {
					self.getFreeLicences(self.countries[counter], counter);
				}
			}
		}, false);
	},

	renderData(element, counter) {
		let self = this;

		let licensesCountry = `
			<div class="row p-2 glass-effect">
				<div class="col-12 p-0">
					<!-- Header -->
					<div class="d-flex justify-content-between p-0 c-pointer">
						<div class="d-flex align-items-center">
							<!-- Título de sección -->
							<span class="section-title mx-3">${pf.const.language.RSC519} ${element[0].country.toUpperCase()}: ${self.licensesAssignedCountry[element[0].country]}</span>
						</div>

						<!-- Botón Collapse -->
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#resultTable${counter}" data-arrow="down" data-sub="3">
							<svg class="bi bi-chevron-down ml-1" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
								<path fill-rule="evenodd" d="M1.646 4.646a.5.5 0 01.708 0L8 10.293l5.646-5.647a.5.5 0 01.708.708l-6 6a.5.5 0 01-.708 0l-6-6a.5.5 0 010-.708z" clip-rule="evenodd"/>
							</svg>
						</button>
					</div>

					<!-- Body -->
					<div id="resultTable${counter}" class="m-0 px-3 pt-3 pb-2 collapse show section-body">
						<div class="pr-3 text-right">
							<h6 class="mb-0"><strong>${pf.const.language.RSC2495}: </strong><span id="to-assign${counter}"></span> (${pf.const.language.RSC2496}: <span id="cpg-0-${counter}"></span>)<span></span></h6>
						</div>

						<!-- Acciones de contenedor -->
						<div class="d-flex justify-content-end pt-3">
							<!-- Botón descargar excel -->
							<button id="export${counter}" type="button" class="btn button-excel exportTitle secondary-button ma-le-5">
								<svg class="bi bi-download icon-color" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
									<path fill-rule="evenodd" d="M.5 8a.5.5 0 01.5.5V12a1 1 0 001 1h12a1 1 0 001-1V8.5a.5.5 0 011 0V12a2 2 0 01-2 2H2a2 2 0 01-2-2V8.5A.5.5 0 01.5 8z" clip-rule="evenodd"/>
									<path fill-rule="evenodd" d="M5 7.5a.5.5 0 01.707 0L8 9.793 10.293 7.5a.5.5 0 11.707.707l-2.646 2.647a.5.5 0 01-.708 0L5 8.207A.5.5 0 015 7.5z" clip-rule="evenodd"/>
									<path fill-rule="evenodd" d="M8 1a.5.5 0 01.5.5v8a.5.5 0 01-1 0v-8A.5.5 0 018 1z" clip-rule="evenodd"/>
								</svg>
								<span>${pf.const.language.RSC47}</span>
							</button>
						</div>

						<table id="registers${counter}" class="table table-striped tRegs"></table>
					</div>
				</div>
			</div>
		`;

		$('#licensesContainer').append(licensesCountry);

		let excelTitle = pf.const.language.RSC1716 + ' - ' + pf.const.language.RSC519 + " " + element[0].country.toUpperCase();

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC1540}">${pf.const.language.RSC1540}</th>
					<th scope="col" title="${pf.const.language.RSC1541}">${pf.const.language.RSC1541}</th>
					<th scope="col" title="${pf.const.language.RSC519}">${pf.const.language.RSC519}</th>
					<th scope="col" title="${pf.const.language.RSC1663}">${pf.const.language.RSC1663}</th>
					<th scope="col" title="${pf.const.language.RSC1664}">${pf.const.language.RSC1664}</th>
				</tr>
			</thead>

			<thead class="filtersResult${counter}">
				<tr>
					<td>id</td>
					<td>razonSocial</td>
					<td>nombreComercial</td>
					<td>licencias</td>
					<td>usadas</td>
					<td>libre</td>
				</tr>
			</thead>

			<tbody>
		`;

		let licenciasCPG = 0;
		let usoCPG = 0;
		let libresCPG = 0;

		let size = element.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-country="${element[0].country}" data-index="${i}">
					<td class="text-truncate" title="${element[i].idCPG}">${element[i].idCPG}</td>
					<td class="text-truncate" title="${element[i].razonSocial}">${element[i].razonSocial}</td>
					<td class="text-truncate" title="${element[i].nombreComercial}">${element[i].nombreComercial}</td>
					<td class="text-truncate" title="${(element[i].numLicencias || '0')}">
						<span id="licSpan-${counter}-${i}" class="d-none">${(element[i].numLicencias || '0')}</span>
						<input type="number" class="form-control licInput" value="${(element[i].numLicencias || '0')}" title="${(element[i].numLicencias || '0')}" data-country="${element[0].country}" data-index="${i}">
					</td>
					<td class="text-truncate" title="${element[i].numLicencesUsed}">
						<div class="d-flex justify-content-between">
							${element[i].numLicencesUsed}
							<button type="button" class="btn table-button main-color-text viewUsers mt-1 mr-2" data-cpg="${element[i].idCPG}">
								${stcmbackend.svg.bigEyeWithoutColor}
							</button>
						</div>
					</td>
					<td class="text-truncate" title="${element[i].numLicencesFree}">${element[i].numLicencesFree}</td>
				</tr>
			`;

			// Cálculo de totales
			licenciasCPG += (parseInt(element[i].numLicencias) || 0);
			usoCPG += parseInt(element[i].numLicencesUsed);
			libresCPG += parseInt(element[i].numLicencesFree);
		}

		table += `
			</tbody>

			<tfoot>
				<tr>
					<td class="font-weight-bold">Total:</td>
					<td></td>
					<td></td>
					<td id="licenciasCPG${counter}" class="font-weight-bold pl-3"></td>
					<td id="usoCPG${counter}" class="font-weight-bold"></td>
					<td id="libresCPG${counter}" class="font-weight-bold"></td>
				</tr>
			</tfoot>
		`;

		$('#registers' + counter).html(table);

		// Totales en footer de tabla
		$(`#licenciasCPG${counter}`).text(licenciasCPG);
		$(`#usoCPG${counter}`).text(usoCPG);
		$(`#libresCPG${counter}`).text(libresCPG);

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

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

		let dataTable = $('#registers' + counter).DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 0},
				{width: '70px', targets: 3},
				{width: '90px', targets: 4},
				{width: '60px', targets: 5}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

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

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

		self.tableEvents();

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

	tableEvents() {
		let self = this;

		// Modificar el número de licencias
		$('.licInput').off().on('blur', function() {
			let index = $(this).data('index');
			let country = $(this).data('country');
			let value = $(this).val();
			$(this).prop('title', value);

			if(value < self.data[country][index].numLicencesUsed) {
				self.data[country][index].numLicencias = self.data[country][index].numLicencesUsed;
				$(this).val(self.data[country][index].numLicencesUsed);

				let warningTitle = pf.const.language.RSC1716;
				let warningContent = pf.const.language.RSC1758;
				pf.utils.showInfoDialog(warningTitle, warningContent);
			} else {
				self.data[country][index].numLicencias = value;
			}
		});

		// Ver usuarios de CPG
		$('.viewUsers').off().on('click', function() {
			let cpg = $(this).data('cpg');

			let parameters = {
				idCPG: cpg
			};
			ajaxComunCallWithCallback('getSocialLabsLicencesDetailByCPG', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					$('#modalCPGDetail').modal('show');
					let cpgUsers = ajaxReturn.result;

					self.renderCPGDetail(cpgUsers);
				}
			});
		});
	},

	setSocialLabsLicencesByCPG() {
		let self = this;

		// Comprobación de número de licencias asignadas y creación de array de objetos con los CPGs
		let cpgs = [];
		for(let element in self.data) {
			let licencias = 0;
			let size = self.data[element].length;
			for(let i = 0; i < size; i++) {
				licencias += parseInt((self.data[element][i].numLicencias || 0));

				let obj = {
					idCPG: self.data[element][i].idCPG,
					numLicencias: (self.data[element][i].numLicencias || '0')
				};

				cpgs.push(obj);
			}

			let slotsAvailable = self.licensesFreeCountry[element] + self.licensesUsedCountry[element];

			if(slotsAvailable < licencias) {
				let warningTitle = pf.const.language.RSC1716;
				let warningContent = pf.const.language.RSC1724 + ' - ' + element;
				pf.utils.showInfoDialog(warningTitle, warningContent);
				return;
			}
		}

		let parameters = {
			cpgs: JSON.stringify(cpgs)
		};
		ajaxComunCallWithCallback('setSocialLabsLicencesByCPG', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.result === 'Licences updated successfully') {
					let successTitle = pf.const.language.RSC1716;
					let successContent = pf.const.language.RSC1668;
					pf.utils.showInfoDialog(successTitle, successContent);

					loadHTML('inc/cpg/cpg_licenses.html', 'wrapper', CPGLicensesController);
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = ajaxReturn.result;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}
			}
		});
	},

	renderCPGDetail(cpgUsers) {
		let self = this;

		let nameSurnameHead = `
			<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
			<th scope="col" title="${pf.const.language.RSC1626}">${pf.const.language.RSC1626}</th>
			<th scope="col" title="${pf.const.language.RSC1627}">${pf.const.language.RSC1627}</th>
		`;
		let nameSurnameFilter = `
			<td>name</td>
			<td>apellido1</td>
			<td>apellido2</td>
		`;

		// Control GDPR
		if(sessionStorage['STCMBackEnd:GDPR'] == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<table id="tableCPGDetail" class="table table-hover tRegs">
				<thead>
					<tr>
						${nameSurnameHead}
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						<th scope="col" title="${pf.const.language.RSC438}">${pf.const.language.RSC438}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						${nameSurnameFilter}
						<td>email</td>
						<td>type</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = cpgUsers.length;
		for(let i = 0; i < size; i++) {
			let nameSurnameBody = `
				<td class="text-truncate" title="${cpgUsers[i].userNombre || ''}">${cpgUsers[i].userNombre || ''}</td>
				<td class="text-truncate" title="${cpgUsers[i].userApellidos || ''}">${cpgUsers[i].userApellidos || ''}</td>
				<td class="text-truncate" title="${cpgUsers[i].userApellidos2 || ''}">${cpgUsers[i].userApellidos2 || ''}</td>
			`;

			// Control GDPR
			if(sessionStorage['STCMBackEnd:GDPR'] == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${cpgUsers[i].token}">${cpgUsers[i].token}</td>
					<td class="text-truncate" title="${cpgUsers[i].type}">${cpgUsers[i].type}</td>
				</tr>
			`;
		}

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

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

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

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

		let dataTable = $('#tableCPGDetail').DataTable({
			retrieve: true,
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2360,
				className: 'd-none',
				title: pf.const.language.RSC2360,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

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