let CatalogacionAsesoresController = {
	typeColors: null,
	fontSize: null,
	fontName: null,
	colorsRGB: [],
	colorsHex: [],
	cataloging: '',
	arrayCataloging: [],
	counter: [],
	percentage: [],
	data: '',
	total: 0,
	countriesToSee: [],
	countriesToSeeDesc: '',
	myChart: null,
	graphFlag: false,

	reset() {
		let self = this;

		self.typeColors = null;
		self.fontSize = null;
		self.fontName = null;
		self.colorsRGB = [];
		self.colorsHex = [];
		self.cataloging = '';
		self.arrayCataloging = [];
		self.counter = [];
		self.percentage = [];
		self.data = '';
		self.total = 0;
		self.countriesToSee = [];
		self.countriesToSeeDesc = '';
		self.myChart = null;
		self.graphFlag = false;
	},

	setEvents() {
		let self = this;
		self.reset();

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC39);

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

		let nav = `
			<div class="d-flex flex-row-reverse">
				${createSubOptionCountrySimple(jsonsubopt.country)}
			</div>
		`;

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

		self.loadLang();

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.typeColors = config.UsarColorDegradado;
		self.fontSize = config.SizeFontAnalytics;
		self.fontName = config.FontAnalytics;

		if(!config.RGBFin || config.RGBFin === '') {
			self.colorsRGB[0] = '000,000,255';
			self.colorsHex[0] = rgb2hex('rgb(000,000,255)');
		} else {
			if(self.typeColors == 1) {
				self.colorsRGB[0] = config.RGBFin;
				self.colorsHex[0] = rgb2hex('rgb(' + config.RGBFin + ')');
			} else {
				self.colorsRGB = [];
				for(let i = 0; i < config.colores.length; i++) {
					self.colorsRGB.push(config.colores[i].color);
				}
			}
		}

		if(!config.RGBInicio || config.RGBInicio === '') {
			self.colorsRGB[1] = '255,000,000';
			self.colorsHex[1] = rgb2hex('rgb(255,000,000)');
		} else {
			if(self.typeColors == 1) {
				self.colorsRGB[1] = config.RGBInicio;
				self.colorsHex[1] = rgb2hex('rgb(' + config.RGBInicio + ')');
			} else {
				self.colorsHex = [];
				for(let i = 0; i < config.colores.length; i++) {
					self.colorsHex.push(rgb2hex('rgb(' + config.colores[i].color + ')'));
				}
			}
		}

		self.applyEvents();

		$('#mGraphs').hide();
		$('#data-table').hide();

		// Control de países permitidos por el administrador si solo hay uno
		let countries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let countriesDesc = atob(sessionStorage['STCMBackEnd:userCountriesDesc']);
		let cataloging_country = sessionStorage['home:cataloging_country'];
		let cataloging_country_desc = sessionStorage['home:cataloging_country_desc'];
		if(countries.length === 1) {
			self.countriesToSee = countries;
			self.countriesToSeeDesc = countriesDesc;
			$('#country').val(self.countriesToSeeDesc);
			$('#country').attr('title', self.countriesToSeeDesc);

			// Cargar tabla
			self.getCatalogacionesM();
		} else if(cataloging_country != undefined) {
			self.countriesToSee = cataloging_country;
			self.countriesToSeeDesc = cataloging_country_desc;
			$('#country').val(self.countriesToSeeDesc);
			$('#country').attr('title', self.countriesToSeeDesc);
			sessionStorage.removeItem('home:cataloging_country');
			sessionStorage.removeItem('home:cataloging_country_desc');

			// Cargar tabla
			self.getCatalogacionesM();
		}

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// País
		let countryModal = new TableCountries(1, 'catalogacionAsesores');
		$('#searchCountry').on('click', function() {
			countryModal.setEvents();
		});
	},

	getCatalogacionesM() {
		let self = this;

		$('#mGraphs').show();
		$('#data-table').show();

		// Iniciar spinner
		addLoader();

		ajaxComunCallWithCallback('getCatalogacionesM', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.cataloging = ajaxReturn.result;

				self.arrayCataloging = [];
				self.counter = [];
				let size = self.cataloging.length;
				for(let i = 0; i < size; i++) {
					self.arrayCataloging.push(self.cataloging[i].catalogacion);
					self.counter.push(0);
				}

				let parameters = {
					country: self.countriesToSee.toString()
				};
				ajaxComunCallWithCallback('getCatalogacionesConsejeros', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.data = ajaxReturn.result;

						// Gráfica
						self.catalogingGraph();
						self.graphsEvents();

						// Tabla de resultados
						self.renderData();
						$('#exportCataloging').prop('disabled', false);

						// Finalizar spinner
						removeLoader();
					}
				}, false);
			}
		}, false);
	},

	catalogingGraph() {
		let self = this;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let index = self.arrayCataloging.indexOf(self.data[i].descCatalogacion);
			if(index != -1) {
				self.counter[index]++;
			} else {
				self.arrayCataloging.push(self.data[i].descCatalogacion);
				self.counter.push(1);
			}
		}

		// Porcentajes
		let total = 0;
		let counterSize = self.counter.length;
		for(let i = 0; i < counterSize; i++) {
			total += self.counter[i];
		}
		self.total = total;

		for(let j = 0; j < counterSize; j++) {
			let percentage = (self.counter[j] * 100 / total).toFixed(1);
			self.percentage.push(percentage);
		}

		// COLORES
		let gradient = arrayColors(self.colorsHex, self.arrayCataloging.length);

		Chart.defaults.global.defaultFontSize = self.fontSize;
		Chart.defaults.global.defaultFontFamily = self.fontName;

		let titleText = pf.const.language.RSC32 + ': ' + total;

		let options = {
			layout: {
				padding: {
					top: -20
				}
			},
			title: {
				display: true,
				text: titleText,
				padding: 26
			},
			scales: {
				xAxes: [{
					barPercentage: 0.5,
					ticks: {
						display: true,
						autoSkip: false
					}
				}],
				yAxes: [{
					display: false,
					ticks: {
						fontSize: 14,
						beginAtZero: true
					}
				}]
			},
			responsive: true,
			maintainAspectRatio: false,
			legend: {
				display: true,
				position: 'right',
				onClick: false
			},
			legend: {
				display: false
			},
			tooltips: {
				enabled: false
			},
			plugins: {
				datalabels: {
					color: 'black',
					font: {
						weight: 'bold'
					},
					anchor: 'end',
					align: 'end',
					formatter(value, context) {
						return value;
					}
				}
			}
		}

		// Ticks X en horizontal con salto de linea
		// Ancho del contenedor de la gráfica
		let divParentWidth = $('#graphCataloging').parent().css('width');
		// Número de columnas de la gráfica
		let nColumns = self.arrayCataloging.length;
		// Ancho del contenedor entre el número de columnas
		let maxwidth = Math.floor(parseInt(divParentWidth) / nColumns);
		// Ancho de la columna entre el tamaño de la fuente
		//let maxwidthFont = Math.floor(maxwidth / 18);
		let maxwidthFont = Math.ceil(maxwidth / self.fontSize) + 2;

		// Etiquetas del eje X
		let xLabels = self.arrayCataloging;
		// Comprobación de la primera palabra de los labes para ejecutar formato horizontal o diagonal
		let controlH = true;
		let xSize = xLabels.length;
		for(let i = 0; i < xSize; i++) {
			let words = xLabels[i].toString().split(' ');
			let wSize = words.length;
			for(let j = 0; j < wSize; j++) {
				if(words[j].length > maxwidthFont) {
					controlH = false;
					break;
				}
			}
			if(!controlH) {
				break;
			}
		}

		if(controlH) {
			options.scales.xAxes[0].ticks['minRotation'] = 0;
			options.scales.xAxes[0].ticks['maxRotation'] = 0;

			options.scales.xAxes[0].ticks['callback'] = function(value, index, values) {
				let formmatedvalue = formatLabel(value, maxwidthFont);
				return formmatedvalue;
			}
		} else {
			options.scales.xAxes[0].ticks['callback'] = function(value, index, values) {
				if(value.length < 18) {
					return value;
				} else {
					return value.substr(0, 14) + '...';
				}
			};
		}

		if(self.graphFlag) {
			self.myChart.destroy();
		} else {
			self.graphFlag = true;
		}

		let ctx = $('#graphCataloging');
		// Radio de ángulos
		options.cornerRadius = 6;
		self.myChart = new Chart(ctx, {
			type: 'bar',
			data: {
				labels: self.arrayCataloging,
				datasets: [{
					data: self.counter,
					backgroundColor: gradient,
				}]
			},
			options: options
		});
	},

	// Gráfica a pantalla completa
	graphsEvents() {
		let self = this;

		let graphAsesores;
		$('#mGraphs .section-body').off().on('click', function() {
			$('#graphicsViewer').show();

			// COLORES
			let gradient = arrayColors(self.colorsHex, self.arrayCataloging.length);

			let ctx = document.getElementById('graphViewer').getContext('2d');

			Chart.defaults.global.defaultFontSize = self.fontSize;
			Chart.defaults.global.defaultFontFamily = self.fontName;

			let titleText = pf.const.language.RSC32 + ': ' + self.total;

			let options = {
				layout: {
					padding: {
						top: 0
					}
				},
				responsive: true,
				maintainAspectRatio: false,
				scales: {
					xAxes: [{
						barPercentage: 0.5,
						ticks: {
							display: true,
							autoSkip: false
						}
					}],
					yAxes: [{
						display: false,
						ticks: {
							beginAtZero: true
						}
					}]
				},
				legend: {
					display: false
				},
				title: {
					display: true,
					text: titleText,
					padding: 26,
					fontSize: 20
				},
				tooltips: {
					enabled: false
				},
				plugins: {
					datalabels: {
						color: 'black',
						font: {
							weight: 'bold'
						},
						anchor: 'end',
						align: 'end',
						formatter(value, context) {
							return value;
						}
					}
				}
			}

			// Ancho del contenedor de la gráfica
			let divParentWidth = $('#graphViewer').parent().css('width');
			// Número de columnas de la gráfica
			let nColumns = self.arrayCataloging.length;
			// Ancho del contenedor entre el número de columnas
			let maxwidth = Math.floor(parseInt(divParentWidth) / nColumns);
			// Ancho de la columna entre el tamaño de la fuente
			let maxwidthFont = Math.ceil(maxwidth / self.fontSize) + 2;

			// Etiquetas del eje X
			let xLabels = self.arrayCataloging;
			// Comprobación de la primera palabra de los labes para ejecutar formato horizontal o diagonal
			let controlH = true;
			let xSize = xLabels.length;
			for(let i = 0; i < xSize; i++) {
				let words = xLabels[i].toString().split(' ');
				let wSize = words.length;
				for(let j = 0; j < wSize; j++) {
					if(words[j].length > maxwidthFont) {
						controlH = false;
						break;
					}
				}
				if(!controlH) {
					break;
				}
			}

			if(controlH) {
				options.scales.xAxes[0].ticks['minRotation'] = 0;
				options.scales.xAxes[0].ticks['maxRotation'] = 0;

				options.scales.xAxes[0].ticks['callback'] = function(value, index, values) {
					let formmatedvalue = formatLabel(value, maxwidthFont);
					return formmatedvalue;
				}
			}

			// Radio de ángulos
			options.cornerRadius = 6;
			let dataChart = {
				type: 'bar',
				data: {
					labels: self.arrayCataloging,
					datasets: [{
						data: self.counter,
						backgroundColor: gradient
					}]
				},
				options: options
			};

			graphAsesores = new Chart(ctx, dataChart);
		});

		$('#downloadGraph').off().on('click', function() {
			/* Get image of canvas element */
			let url_base64jp = document.getElementById('graphViewer').toDataURL('image/jpg');
			/* get download button (tag: <a></a>) */
			let a = document.getElementById('downloadGraph');
			/* insert chart image url to download button (tag: <a></a>) */
			a.href = url_base64jp;
		});

		$('#closeGraphic').off().on('click', function() {
			graphAsesores.destroy();
			$('#graphicsViewer').hide();
		});
	},

	renderData() {
		let self = this;

		$('#data-table').show();

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		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>Nombre</td>
			<td>Apellido 1</td>
			<td>Apellido 2</td>
		`;

		// Control GDPR
		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<table id="registers" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						${nameSurnameHead}
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						<th scope="col" title="${pf.const.language.RSC186}">${pf.const.language.RSC186}</th>
						<th scope="col" title="${pf.const.language.RSC186} OK">${pf.const.language.RSC186} OK</th>
						<th scope="col" title="${pf.const.language.RSC186} KO">${pf.const.language.RSC186} KO</th>
						<th scope="col" title="${pf.const.language.RSC124}">${pf.const.language.RSC124}</th>
						<th scope="col" title="${pf.const.language.RSC309}">${pf.const.language.RSC309}</th>
						<th scope="col" title="${pf.const.language.RSC125}">${pf.const.language.RSC125}</th>
						<th scope="col" title="${pf.const.language.RSC126}">${pf.const.language.RSC126}</th>
						<th scope="col" title="${pf.const.language.RSC187}">${pf.const.language.RSC187}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>pais</td>
						${nameSurnameFilter}
						<td>E-mail</td>
						<td>NumMisiones</td>
						<td>NumMisionesOK</td>
						<td>NumMisionesKO</td>
						<td>consejero</td>
						<td>staff</td>
						<td>clabe</td>
						<td>enabled</td>
						<td>Catalogacion</td>
					</tr>
				</thead>

				<tbody>
		`;

		// 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(allowedCountries.indexOf(self.data[i].questionPais) == -1) {
				continue;
			}

			let nameSurnameBody = `
				<td class="text-truncate" title="${self.data[i].nameUser}">${self.data[i].nameUser}</td>
				<td class="text-truncate" title="${(self.data[i].apellidoUser == null ? '-' : self.data[i].apellidoUser)}">${(self.data[i].apellidoUser == null ? '-' : self.data[i].apellidoUser)}</td>
				<td class="text-truncate" title="-">-</td>
			`;

			// Control GDPR
			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.data[i].questionPais}">${self.data[i].questionPais}</td>
					${nameSurnameBody}
					<td class="text-truncate" title="${self.data[i].emailUser}">${self.data[i].emailUser}</td>
					<td class="text-truncate text-center" title="${self.data[i].totalMisionesUser}">${self.data[i].totalMisionesUser}</td>
					<td class="text-truncate text-center" title="${self.data[i].numMisionesOK}">${self.data[i].numMisionesOK}</td>
					<td class="text-truncate text-center" title="${self.data[i].numMisionesKO}">${self.data[i].numMisionesKO}</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].consejero == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].consejero == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].staff == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].staff == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].clabeInformada == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].clabeInformada == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].enabled == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.data[i].enabled == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${self.data[i].descCatalogacion}">${self.data[i].descCatalogacion}</td>
				</tr>
			`;
		}

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

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

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

			if(title == 'consejero' || title == 'staff' || title == 'clabe' || title == 'enabled') {
				value = optionsSelectAllYesNo();
			}

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

		let columnDefs = [
			{width: '45px', targets: 0},
			{width: '70px', targets: 8},
			{width: '45px', targets: 9},
			{width: '45px', targets: 10},
			{width: '50px', targets: 11}
		];

		// Control GDPR
		if(gdpr == '1') {
			columnDefs = [
				{width: '45px', targets: 0},
				{width: '70px', targets: 5},
				{width: '45px', targets: 6},
				{width: '45px', targets: 7},
				{width: '50px', targets: 8}
			];
		}

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC39,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			rowGroup: {
				endRender(rows, group) {
					return group + ': ' + pf.const.language.RSC146 + ' (' + rows.count() + ')';
				},
				dataSrc: 0
			},
			order: [[0, 'asc']]
		});

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

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

		dataTable.rowGroup().disable().draw();
		$('#nestBy').hide();

		// Creación de select principal de agrupamiento
		// Arrays de datos
		let name = [];

		$.each($('#registers thead th'), function() {
			name.push($(this).text());
		});

		let options1 = `<option value="-1">${pf.const.language.RSC130}</option>`;
		for(let i = 0; i < name.length; i++) {
			options1 += `<option value="${i}">${name[i]}</option>`;
		}
		$('#groupBy').html(options1);

		// Función de agrupamiento anidado
		function nestBy() {
			$('#nestBy').html('');
			let options2 = `<option value="-1">${pf.const.language.RSC131}</option>`;
			for(let i = 0; i < name.length; i++) {
				if(i == $('#groupBy').val()) {
					continue;
				} else {
					options2 += `<option value="${i}">${name[i]}</option>`;
				}
			}
			$('#nestBy').html(options2);

			// Evento de anidado
			$('#nestBy').off().on('change', function() {
				let valueGroup = $('#groupBy').val();

				if($('#nestBy').val() === '-1') {
					dataTable.rowGroup().dataSrc(valueGroup);
					dataTable.order([[valueGroup, 'asc']]).draw();
				} else {
					let valueNest = $('#nestBy').val();
					dataTable.rowGroup().dataSrc([valueGroup, valueNest]);
					dataTable.order([[valueGroup, 'asc'], [valueNest, 'asc']]).draw();
				}
			});
		}

		// Evento de agrupamiento
		$('#groupBy').on('change', function() {
			if($('#groupBy').val() === '-1') {
				dataTable.rowGroup().disable().draw();
				$('#nestBy').hide();
			} else {
				let value = $('#groupBy').val();

				dataTable.rowGroup().enable().draw();
				$('#nestBy').show();

				dataTable.rowGroup().dataSrc(value);
				dataTable.order([[value, 'asc']]).draw();

				// Recreación de agrupamiento secundario
				nestBy();
			}
		});

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

	clickEvents(data) {
		let self = this;

		self.countriesToSee = [];
		self.countriesToSeeDesc = '';

		let size = data.length;
		for(let i = 0; i < size; i++) {
			self.countriesToSee.push(data[i].isocode);
			self.countriesToSeeDesc += data[i].descripcion + ',';
		}
		self.countriesToSeeDesc = self.countriesToSeeDesc.substring(0, self.countriesToSeeDesc.length - 1);

		$('#country').val(self.countriesToSeeDesc);
		$('#country').attr('title', self.countriesToSeeDesc);

		// Cargar tabla
		self.getCatalogacionesM();
	}
};