let LicenciasController = {
	data: null,
	typePerf: null,
	dataintegration: '',
	color1RGB: '',
	flag: false,
	dataintegrationDetail: '',
	allowedCountries: '',
	warningIcon: '',

	reset() {
		let self = this;

		self.data = null;
		self.typePerf = '';
		self.dataintegration = '';
		self.color1RGB = '';
		self.flag = false;
		self.dataintegrationDetail = '';
		self.allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		self.warningIcon = '';
	},

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

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

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

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.typePerf = config.TipoPerfilacion;
		self.color1RGB = config.RGBInicio;
		if (self.typePerf == 2 || self.typePerf == 3) {
			addLoader();
			self.renderLicencias();
		} else {
			let errorTitle = pf.const.language.RSC519;
			let errorContent = pf.const.language.RSC590;
			pf.utils.showInfoDialog(errorTitle, errorContent);
		}

		// SVG de icono de alarma
		self.warningIcon = `
			<svg width="1.0625em" height="1em" viewBox="0 0 17 16" class="bi bi-exclamation-triangle" fill="rgb(${self.color1RGB})" xmlns="http://www.w3.org/2000/svg">
				<path fill-rule="evenodd" d="M7.938 2.016a.146.146 0 0 0-.054.057L1.027 13.74a.176.176 0 0 0-.002.183c.016.03.037.05.054.06.015.01.034.017.066.017h13.713a.12.12 0 0 0 .066-.017.163.163 0 0 0 .055-.06.176.176 0 0 0-.003-.183L8.12 2.073a.146.146 0 0 0-.054-.057A.13.13 0 0 0 8.002 2a.13.13 0 0 0-.064.016zm1.044-.45a1.13 1.13 0 0 0-1.96 0L.165 13.233c-.457.778.091 1.767.98 1.767h13.713c.889 0 1.438-.99.98-1.767L8.982 1.566z"/>
				<path d="M7.002 12a1 1 0 1 1 2 0 1 1 0 0 1-2 0zM7.1 5.995a.905.905 0 1 1 1.8 0l-.35 3.507a.552.552 0 0 1-1.1 0L7.1 5.995z"/>
			</svg>
		`;

		self.loadLang();
		self.applyEvents();
	},

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

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

	applyEvents() {
		let self = this;

		$('#export').off().on('click', function () {
			if (self.typePerf == 3) {
				self.exportExcel();
			} else {
				$('#inputFile').trigger('click');
			}
		});
	},

	renderLicencias() {
		let self = this;

		let parameters = {
			control: 'S0ci4LL4b5'
		};
		ajaxComunCallWithCallback('getStatusLicencesDetail', parameters, function (ajaxReturn) {
			if (ajaxReturn) {
				self.data = ajaxReturn.result;
				// Tablas de resultados
				if (self.typePerf == 2) {
					self.renderData();
				} else if (self.typePerf == 3) {
					// NSE
					let buttonRABI = `
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapseRegionesABI" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					`;
					$('#regionesabiTableTitle').html(pf.const.language.RSC602 + buttonRABI);

					// Región
					let buttonR = `
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapseRegiones" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					`;
					$('#regionesTableTitle').html(pf.const.language.RSC603 + buttonR);

					// Edad
					let buttonE = `
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapseEdad" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					`;
					$('#edadTableTitle').html(pf.const.language.RSC604 + buttonE);

					// Género
					let buttonG = `
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapseGenero" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					`;
					$('#generoTableTitle').html(pf.const.language.RSC605 + buttonG);

					// Administradores
					let buttonA = `
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapseAdmins" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					`;
					$('#adminsTableTitle').html(pf.const.language.RSC21 + buttonA);

					// Discriminante
					let buttonD = `
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapseDiscriminate" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					`;
					$('#discriminateTableTitle').html(pf.const.language.RSC617 + buttonD);

					self.renderDataRegionABI();
					self.renderDataRegion();
					self.renderDataEdad();
					self.renderDataGenero();
					self.renderDataAdministradores();
					self.renderDataDynamic();
					self.getQuestionDiscriminante();


					// Collapse
					$('.arrow').on('click', function () {
						let arrow = $(this).data('arrow');
						let direction = '';
						if (arrow == 'left') {
							direction = stcmbackend.svg.chevronDown;
							$(this).data('arrow', 'down');
						} else {
							direction = stcmbackend.svg.chevronRight;
							$(this).data('arrow', 'left');
						}
						$(this).html(direction);
						$(this).parent().parent().find('.collapse').collapse('toggle');
					});
				}
			}
		}, false);
	},

	percent(x, y) {
		if ((x == 0 && y == 0) || x == 0) {
			return '0%';
		}
		let result = 100 * x / y;
		result = result.toFixed(2);
		if (result) {
			result = result + '%';
		}

		return result
	},

	renderData() {
		let self = this;

		// Comprobación de array
		if (!Array.isArray(self.data)) {
			self.data = [];
		}

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC564}">${pf.const.language.RSC564}</th>
					<th scope="col" title="${pf.const.language.RSC519}">${pf.const.language.RSC519}</th>
					<th scope="col" title="${pf.const.language.RSC591}">${pf.const.language.RSC591}</th>
					<th scope="col" title="${pf.const.language.RSC592}">${pf.const.language.RSC592}</th>
					<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
					<th scope="col" title="${pf.const.language.RSC519}">${pf.const.language.RSC519}</th>
					<th scope="col" title="${pf.const.language.RSC591}">${pf.const.language.RSC591}</th>
					<th scope="col" title="${pf.const.language.RSC592}">${pf.const.language.RSC592}</th>
					<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
					<th scope="col" title="${pf.const.language.RSC519}">${pf.const.language.RSC519}</th>
					<th scope="col" title="${pf.const.language.RSC591}">${pf.const.language.RSC591}</th>
					<th scope="col" title="${pf.const.language.RSC592}">${pf.const.language.RSC592}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>estado</td>
					<td>licencias</td>
					<td>asignadas</td>
					<td>no activas</td>
					<td>edad</td>
					<td>licencias</td>
					<td>asignadas</td>
					<td>no activas</td>
					<td>genero</td>
					<td>licencias</td>
					<td>asignadas</td>
					<td>no activas</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for (let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate data1" title="${self.data[i].estado}">${self.data[i].estado}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfestadoslicencias}">${self.data[i].cmperfestadoslicencias}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfestadoslicenciasOCUPADAS}">${self.data[i].cmperfestadoslicenciasOCUPADAS}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfestadoslicenciasOCUPADASDisabled}">${self.data[i].cmperfestadoslicenciasOCUPADASDisabled}</td>
					<td class="text-truncate" title="${self.data[i].edad}">${self.data[i].edad}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfedadlicencias}">${self.data[i].cmperfedadlicencias}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfedadlicenciasOCUPADAS}">${self.data[i].cmperfedadlicenciasOCUPADAS}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfedadlicenciasOCUPADASDisabled}">${self.data[i].cmperfedadlicenciasOCUPADASDisabled}</td>
					<td class="text-truncate" title="${self.data[i].genero}">${self.data[i].genero}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfgenerolicencias}">${self.data[i].cmperfgenerolicencias}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfgenerolicenciasOCUPADAS}">${self.data[i].cmperfgenerolicenciasOCUPADAS}</td>
					<td class="text-truncate text-center" title="${self.data[i].cmperfgenerolicenciasOCUPADASDisabled}">${self.data[i].cmperfgenerolicenciasOCUPADASDisabled}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#licencesTable').DataTable({
			rowsGroup: [0, 1, 2, 3, 4, 5, 6, 7],
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC519,
				className: 'd-none',
				title: pf.const.language.RSC519,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);

					let mergeCells;
					let size = self.data.length;
					let estado = self.data[0].estado;
					let countEstado = 0;
					let initEstado = 3;
					let edad = self.data[0].edad;
					let countEdad = 0;
					let initEdad = 3;
					for (let i = 0; i < size; i++) {
						// ESTADOS
						if (self.data[i].estado == estado) {
							countEstado++;
							if (i == (size - 1)) {
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'A' + initEstado + ':A' + (initEstado + countEstado - 1),
									}
								}));
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'B' + initEstado + ':B' + (initEstado + countEstado - 1),
									}
								}));
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'C' + initEstado + ':C' + (initEstado + countEstado - 1),
									}
								}));
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'D' + initEstado + ':D' + (initEstado + countEstado - 1),
									}
								}));
							}
						} else {
							estado = self.data[i].estado;
							mergeCells = $('mergeCells', sheet);
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'A' + initEstado + ':A' + (initEstado + countEstado - 1),
								}
							}));
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'B' + initEstado + ':B' + (initEstado + countEstado - 1),
								}
							}));
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'C' + initEstado + ':C' + (initEstado + countEstado - 1),
								}
							}));
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'D' + initEstado + ':D' + (initEstado + countEstado - 1),
								}
							}));
							initEstado += countEstado;
							countEstado = 1;
						}

						// EDADES
						if (self.data[i].edad == edad) {
							countEdad++;
							if (i == (size - 1)) {
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'E' + initEdad + ':E' + (initEdad + countEdad - 1),
									}
								}));
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'F' + initEdad + ':F' + (initEdad + countEdad - 1),
									}
								}));
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'G' + initEdad + ':G' + (initEdad + countEdad - 1),
									}
								}));
								mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
									attr: {
										ref: 'H' + initEdad + ':H' + (initEdad + countEdad - 1),
									}
								}));
							}
						} else {
							edad = self.data[i].edad;
							mergeCells = $('mergeCells', sheet);
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'E' + initEdad + ':E' + (initEdad + countEdad - 1),
								}
							}));
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'F' + initEdad + ':F' + (initEdad + countEdad - 1),
								}
							}));
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'G' + initEdad + ':G' + (initEdad + countEdad - 1),
								}
							}));
							mergeCells[0].appendChild(_createNode(sheet, 'mergeCell', {
								attr: {
									ref: 'H' + initEdad + ':H' + (initEdad + countEdad - 1),
								}
							}));
							initEdad += countEdad;
							countEdad = 1;
						}
					}

					mergeCells.attr('count', mergeCells.attr('count') + 1);

					function _createNode(doc, nodeName, opts) {
						var tempNode = doc.createElement(nodeName);

						if (opts) {
							if (opts.attr) {
								$(tempNode).attr(opts.attr);
							}

							if (opts.children) {
								$.each(opts.children, function (key, value) {
									tempNode.appendChild(value);
								});
							}

							if (opts.text !== null && opts.text !== undefined) {
								tempNode.appendChild(doc.createTextNode(opts.text));
							}
						}

						return tempNode;
					}
				}
			}]
		});

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

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

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

	renderDataRegionABI() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC597}">${pf.const.language.RSC597}</th>
					<th scope="col" title="${pf.const.language.RSC598}">${pf.const.language.RSC598}</th>
					<th scope="col" title="${pf.const.language.RSC599}">${pf.const.language.RSC599}</th>
					<th scope="col" title="${pf.const.language.RSC600}">${pf.const.language.RSC600}</th>
					<th scope="col" title="${pf.const.language.RSC606}">${pf.const.language.RSC606}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersResultAbi">
				<tr>
					<td>pais</td>
					<td>regionABI</td>
					<td>sec</td>
					<td>licencias</td>
					<td>licenciasOcupadas</td>
					<td>porcentaje</td>
					<td>eye</td>
				</tr>
			</thead>

			<tbody>
		`;

		let warningSearch = false;

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

			let trStyle = '';

			if (parseInt(self.data.perfstatus_region_abi[i].licencias) < parseInt(self.data.perfstatus_region_abi[i].licenciasOcupadas)) {
				trStyle = `style="font-weight: bold; color:rgb(${self.color1RGB})"`;
				warningSearch = true;
			}

			table += `
				<tr ${trStyle}>
					<td class="text-truncate" title="${self.data.perfstatus_region_abi[i].pais}">${self.data.perfstatus_region_abi[i].pais}</td>
					<td class="text-truncate" title="${self.data.perfstatus_region_abi[i].region}">${self.data.perfstatus_region_abi[i].region}</td>
					<td class="text-truncate" title="${self.data.perfstatus_region_abi[i].sec}">${self.data.perfstatus_region_abi[i].sec}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_region_abi[i].licencias}">${self.data.perfstatus_region_abi[i].licencias}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_region_abi[i].licenciasOcupadas}">${self.data.perfstatus_region_abi[i].licenciasOcupadas}</td>
					<td class="text-truncate text-center" title="${self.percent(self.data.perfstatus_region_abi[i].licenciasOcupadas, self.data.perfstatus_region_abi[i].licencias)}">${self.percent(self.data.perfstatus_region_abi[i].licenciasOcupadas, self.data.perfstatus_region_abi[i].licencias)}</td>
					<td class="text-center">
						<button type="button" class="btn table-button main-color-text btn-eye-nse" data-country="${self.data.perfstatus_region_abi[i].pais}" data-region="${self.data.perfstatus_region_abi[i].region}" data-sec="${self.data.perfstatus_region_abi[i].sec}" data-toggle="modal" data-target="#infoLicenses">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td> 
				</tr>
			`;
		}

		if (warningSearch) {
			$('#regionesabiTableTitle').append(self.warningIcon);
		}

		table += `
			</tbody>

			<tfoot>
				<tr>
					<th>Total:</th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
				</tr>
			</tfoot>
		`;

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

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

			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTableAbi = $('#regionesabiTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{ width: '30px', targets: 6 }
			],
			aaSorting: [],
			footerCallback(row, data, start, end, display) {
				total = this.api()
					.column(3, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);

				total2 = this.api()
					.column(4, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);
				$(this.api().column(3).footer()).html(total);
				$(this.api().column(4).footer()).html(total2);
			},
		});

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

		// Apply the search
		applyTheSearch(dataTableAbi, 'filtersResultAbi');

		self.tableLicensesNSEEvents();

		$('#regionesabiTable').on('draw.dt', function () {
			self.tableLicensesNSEEvents();
		});
	},

	tableLicensesNSEEvents() {
		let self = this;

		$('.btn-eye-nse').off().on('click', function () {
			let country = $(this).attr('data-country');
			let region = $(this).attr('data-region');
			if (region == 'Valle de México') {
				region = 'Valle de Mexico';
			}
			let sec = $(this).attr('data-sec');

			let min;
			let max;
			if (region == 'Colombia') {
				//Process Ax and Ax/Ay data forms
				let match = sec.match(/A(\d+)(?:\/A(\d+))?/);
				min = parseInt(match[1]);
				max = match[2] ? parseInt(match[2]) : min;
			} else {
				// Process standard NSE forms
				let minIndex = sec.indexOf('(');
				let maxIndex = sec.indexOf('&');
				min = sec.substr((minIndex + 1), 1);
				max = sec.substr((maxIndex + 2), 1);
			}

			let data = [];
			let detalle = self.data.detalle;
			let size = detalle.length;
			for (let i = 0; i < size; i++) {
				if (detalle[i].country == country && detalle[i].regionABIAux == region
					&& detalle[i].ABI >= min && detalle[i].ABI <= max
					&& detalle[i].consumeAlcochol == 1) {
					data.push(detalle[i]);
				}
			}

			let title = pf.const.language.RSC602;
			let subTitle = country.toUpperCase() + ' - ' + region;
			self.renderDetalle(data, title, subTitle);
		});
	},

	renderDataRegion() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC597}">${pf.const.language.RSC597}</th>
					<th scope="col" title="${pf.const.language.RSC601}">${pf.const.language.RSC601}</th>
					<th scope="col" title="${pf.const.language.RSC599}">${pf.const.language.RSC599}</th>
					<th scope="col" title="${pf.const.language.RSC600}">${pf.const.language.RSC600}</th>
					<th scope="col" title="${pf.const.language.RSC606}">${pf.const.language.RSC606}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersRegion">
				<tr>
					<td>pais</td>
					<td>region</td>
					<td>regionABI</td>
					<td>licencias</td>
					<td>licenciasOcupadas</td>
					<td>porcentaje</td>
					<td>eye</td>
				</tr>
			</thead>

			<tbody>
		`;

		let warningSearch = false;

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

			let trStyle = '';

			if (parseInt(self.data.perfstatus_region[i].licencias) < parseInt(self.data.perfstatus_region[i].licenciasOcupadas)) {
				trStyle = `style="font-weight: bold; color:rgb(${self.color1RGB})"`;
				warningSearch = true;
			}

			table += `
				<tr ${trStyle}>
					<td class="text-truncate" title="${self.data.perfstatus_region[i].pais}">${self.data.perfstatus_region[i].pais}</td>
					<td class="text-truncate" title="${self.data.perfstatus_region[i].region}">${self.data.perfstatus_region[i].region}</td>
					<td class="text-truncate" title="${self.data.perfstatus_region[i].regionABI}">${self.data.perfstatus_region[i].regionABI}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_region[i].licencias}">${self.data.perfstatus_region[i].licencias}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_region[i].licenciasOcupadas}">${self.data.perfstatus_region[i].licenciasOcupadas}</td>
					<td class="text-truncate text-center" title="${self.percent(self.data.perfstatus_region[i].licenciasOcupadas, self.data.perfstatus_region[i].licencias)}">${self.percent(self.data.perfstatus_region[i].licenciasOcupadas, self.data.perfstatus_region[i].licencias)}</td>
					<td class="text-center">
						<button type="button" class="btn table-button main-color-text btn-eye-region" data-country="${self.data.perfstatus_region[i].pais}" data-region="${self.data.perfstatus_region[i].region}" data-abi="${self.data.perfstatus_region[i].regionABI}" data-toggle="modal" data-target="#infoLicenses">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
					</tr>
			`;
		}

		if (warningSearch) {
			$('#regionesTableTitle').append(self.warningIcon);
		}

		table += `
			</tbody>

			<tfoot>
				<tr>
					<th>Total:</th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
				</tr>
			</tfoot>
		`;

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

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

			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#regionesTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{ width: '30px', targets: 6 }
			],
			aaSorting: [],
			footerCallback(row, data, start, end, display) {
				total = this.api()
					.column(3, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);

				total2 = this.api()
					.column(4, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);
				$(this.api().column(3).footer()).html(total);
				$(this.api().column(4).footer()).html(total2);
			},
		});

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

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

		self.tableLicensesRegionEvents();

		$('#regionesTable').on('draw.dt', function () {
			self.tableLicensesRegionEvents();
		});
	},

	tableLicensesRegionEvents() {
		let self = this;

		$('.btn-eye-region').off().on('click', function () {
			let country = $(this).attr('data-country');
			let abi = $(this).attr('data-abi');
			if (abi == 'Valle de México') {
				abi = 'Valle de Mexico';
			}
			let region = $(this).attr('data-region');

			let data = [];
			let detalle = self.data.detalle;
			let size = detalle.length;
			for (let i = 0; i < size; i++) {

				// Old filter:
				// detalle[i].country == country && detalle[i].regionABI == abi && detalle[i].consumeAlcochol == 1
				if (detalle[i].country == country && detalle[i].region.trim() == abi && detalle[i].consumeAlcochol == 1) {
					data.push(detalle[i]);
				}
			}

			let title = pf.const.language.RSC603;
			let subTitle = country.toUpperCase() + ' - ' + region + ' - ' + abi;
			self.renderDetalle(data, title, subTitle);
		});
	},

	renderDataEdad() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC597}">${pf.const.language.RSC597}</th>
					<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
					<th scope="col" title="${pf.const.language.RSC599}">${pf.const.language.RSC599}</th>
					<th scope="col" title="${pf.const.language.RSC600}">${pf.const.language.RSC600}</th>
					<th scope="col" title="${pf.const.language.RSC606}">${pf.const.language.RSC606}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersAge">
				<tr>
					<td>pais</td>
					<td>region</td>
					<td>edad</td>
					<td>licencias</td>
					<td>licenciasOcupadas</td>
					<td>porcentaje</td>
					<td>eye</td>
				</tr>
			</thead>

			<tbody>
		`;

		let warningSearch = false;

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

			let trStyle = '';

			if (parseInt(self.data.perfstatus_edad[i].licencias) < parseInt(self.data.perfstatus_edad[i].licenciasOcupadas)) {
				trStyle = `style="font-weight: bold; color:rgb(${self.color1RGB})"`;
				warningSearch = true;
			}

			table += `
				<tr ${trStyle}>
					<td class="text-truncate" title="${self.data.perfstatus_edad[i].pais}">${self.data.perfstatus_edad[i].pais}</td>
					<td class="text-truncate" title="${self.data.perfstatus_edad[i].region}">${self.data.perfstatus_edad[i].region}</td>
					<td class="text-truncate" title="${self.data.perfstatus_edad[i].edad}">${self.data.perfstatus_edad[i].edad}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_edad[i].licencias}">${self.data.perfstatus_edad[i].licencias}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_edad[i].licenciasOcupadas}">${self.data.perfstatus_edad[i].licenciasOcupadas}</td>
					<td class="text-truncate text-center" title="${self.percent(self.data.perfstatus_edad[i].licenciasOcupadas, self.data.perfstatus_edad[i].licencias)}">${self.percent(self.data.perfstatus_edad[i].licenciasOcupadas, self.data.perfstatus_edad[i].licencias)}</td>
					<td class="text-center">
						<button type="button" class="btn table-button main-color-text btn-eye-age" data-country="${self.data.perfstatus_edad[i].pais}" data-region="${self.data.perfstatus_edad[i].region}" data-min="${self.data.perfstatus_edad[i].min}" data-max="${self.data.perfstatus_edad[i].max}" data-toggle="modal" data-target="#infoLicenses">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
				</tr>
			`;
		}

		if (warningSearch) {
			$('#edadTableTitle').append(self.warningIcon);
		}

		table += `
			</tbody>

			<tfoot>
				<tr>
					<th>Total:</th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
				</tr>
			</tfoot>
		`;

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

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

			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#edadTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{ width: '30px', targets: 6 }
			],
			aaSorting: [],
			footerCallback(row, data, start, end, display) {
				total = this.api()
					.column(3, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);

				total2 = this.api()
					.column(4, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);
				$(this.api().column(3).footer()).html(total);
				$(this.api().column(4).footer()).html(total2);
			},
		});

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

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

		self.tableLicensesAgeEvents();

		$('#edadTable').on('draw.dt', function () {
			self.tableLicensesAgeEvents();
		});
	},

	tableLicensesAgeEvents() {
		let self = this;

		$('.btn-eye-age').off().on('click', function () {
			let country = $(this).data('country');
			let region = $(this).data('region');
			if (region == 'Valle de México') {
				region = 'Valle de Mexico';
			}

			let min = parseInt($(this).data('min'));
			let max = parseInt($(this).data('max'));

			let data = [];
			let detalle = self.data.detalle;
			let size = detalle.length;
			for (let i = 0; i < size; i++) {
				if (detalle[i].country == country && detalle[i].regionABIAux == region && parseInt(detalle[i].edad) >= min && parseInt(detalle[i].edad) <= max && detalle[i].consumeAlcochol == 1) {
					data.push(detalle[i]);
				}
			}

			let title = pf.const.language.RSC604;
			let subTitle = country.toUpperCase() + ' - ' + region;
			self.renderDetalle(data, title, subTitle);
		});
	},

	renderDataGenero() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC597}">${pf.const.language.RSC597}</th>
					<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
					<th scope="col" title="${pf.const.language.RSC599}">${pf.const.language.RSC599}</th>
					<th scope="col" title="${pf.const.language.RSC600}">${pf.const.language.RSC600}</th>
					<th scope="col" title="${pf.const.language.RSC606}">${pf.const.language.RSC606}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersGender">
				<tr>
					<td>pais</td>
					<td>region</td>
					<td>genero</td>
					<td>licencias</td>
					<td>licenciasOcupadas</td>
					<td>porcentaje</td>
					<td>eye</td>
				</tr>
			</thead>

			<tbody>
		`;

		let warningSearch = false;

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

			let trStyle = '';

			if (parseInt(self.data.perfstatus_genero[i].licencias) < parseInt(self.data.perfstatus_genero[i].licenciasOcupadas)) {
				trStyle = `style="font-weight: bold; color:rgb(${self.color1RGB})"`;
				warningSearch = true;
			}

			table += `
				<tr ${trStyle}>
					<td class="text-truncate" title="${self.data.perfstatus_genero[i].pais}">${self.data.perfstatus_genero[i].pais}</td>
					<td class="text-truncate" title="${self.data.perfstatus_genero[i].region}">${self.data.perfstatus_genero[i].region}</td>
					<td class="text-truncate" title="${self.data.perfstatus_genero[i].genero}">${self.data.perfstatus_genero[i].genero}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_genero[i].licencias}">${self.data.perfstatus_genero[i].licencias}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_genero[i].licenciasOcupadas}">${self.data.perfstatus_genero[i].licenciasOcupadas}</td>
					<td class="text-truncate text-center" title="${self.percent(self.data.perfstatus_genero[i].licenciasOcupadas, self.data.perfstatus_genero[i].licencias)}">${self.percent(self.data.perfstatus_genero[i].licenciasOcupadas, self.data.perfstatus_genero[i].licencias)}</td>
					<td class="text-center">
						<button type="button" class="btn table-button main-color-text btn-eye-gender" data-country="${self.data.perfstatus_genero[i].pais}" data-region="${self.data.perfstatus_genero[i].region}" data-genero="${self.data.perfstatus_genero[i].genero}" data-toggle="modal" data-target="#infoLicenses">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
				</tr>
			`;
		}

		if (warningSearch) {
			$('#generoTableTitle').append(self.warningIcon);
		}

		table += `
			</tbody>

			<tfoot>
				<tr>
					<th>Total:</th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
					<th class="text-center"></th>
				</tr>
			</tfoot>
		`;

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

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

			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#generoTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{ width: '30px', targets: 6 }
			],
			aaSorting: [],
			footerCallback(row, data, start, end, display) {
				total = this.api()
					.column(3, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);

				total2 = this.api()
					.column(4, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);
				$(this.api().column(3).footer()).html(total);
				$(this.api().column(4).footer()).html(total2);
			},
		});

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

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

		self.tableLicensesGenderEvents();

		$('#generoTable').on('draw.dt', function () {
			self.tableLicensesGenderEvents();
		});
	},

	tableLicensesGenderEvents() {
		let self = this;

		$('.btn-eye-gender').off().on('click', function () {
			let country = $(this).attr('data-country');
			let region = $(this).attr('data-region');
			if (region == 'Valle de México') {
				region = 'Valle de Mexico';
			}
			let gender = $(this).attr('data-genero');

			let data = [];
			let detalle = self.data.detalle;
			let size = detalle.length;
			for (let i = 0; i < size; i++) {
				if (detalle[i].country == country && detalle[i].regionABIAux == region && detalle[i].genero == gender && detalle[i].consumeAlcochol == 1) {
					data.push(detalle[i]);
				}
			}

			let title = pf.const.language.RSC605;
			let subTitle = country.toUpperCase() + ' - ' + region + ' - ' + gender;
			self.renderDetalle(data, title, subTitle);
		});
	},

	renderDataAdministradores() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC600}">${pf.const.language.RSC600}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersAdmins">
				<tr>
					<td>pais</td>
					<td>licenciasOcupadas</td>
					<td>eye</td>
				</tr>
			</thead>

			<tbody>
		`;

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

			table += `
				<tr>
					<td class="text-truncate" title="${self.data.perfstatus_admins[i].pais}">${self.data.perfstatus_admins[i].pais}</td>
					<td class="text-truncate text-center" title="${self.data.perfstatus_admins[i].licenciasOcupadas}">${self.data.perfstatus_admins[i].licenciasOcupadas}</td>
					<td class="text-center">
						<button type="button" class="btn table-button main-color-text btn-eye-admins" data-country="${self.data.perfstatus_admins[i].pais}" data-toggle="modal" data-target="#infoLicenses">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>

			<tfoot>
				<tr>
					<th>Total:</th>
					<th class="text-center"></th>
					<th class="text-center"></th>
				</tr>
			</tfoot>
		`;

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

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

			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#adminsTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{ width: '30px', targets: 2 }
			],
			aaSorting: [],
			footerCallback(row, data, start, end, display) {
				total = this.api()
					.column(1, { page: 'current' })//numero de columna a sumar
					.data()
					.reduce(function (a, b) {
						return parseInt(a) + parseInt(b);
					}, 0);

				$(this.api().column(1).footer()).html(total);
			},
		});

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

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

		self.tableLicensesAdminsEvents();

		$('#adminsTable').on('draw.dt', function () {
			self.tableLicensesAdminsEvents();
		});
	},

	renderDataDynamic() {
		let self = this;

		let profilingSections = self.data.profiling_sections;
		let tables = '';
		profilingSections.forEach(section => {
			const { id_variable, name_variable, headers, data } = section;
			const keys = headers.map(header => header.key);

			let headRow = '';
			let headFilters = '';
			let tableHead = '';
			let tableBody = '';
			let tableFoot = '';

			headers.forEach(header => {
				headRow += `<th scope="col" title="${header.name}">${header.name}</th>`;
			});

			headers.forEach(header => {
				headFilters += `<td scope="col" title="${header.name}">${header.name}</td>`;
			});

			tableHead = `
				<thead>
					<tr>${headRow}</tr>
				</thead>
				<thead class="filters-dynamic-${id_variable}">
					<tr>${headFilters}</tr>
				</thead>`;

			data.forEach(entry => {
				let tableData = '';
				keys.forEach(key => {
					const titleAttr = `title="${entry[key]}"`;
					const className = !isNaN(parseFloat(entry[key])) && isFinite(entry[key]) ? 'text-truncate text-center' : 'text-truncate';
					tableData += `<td class="${className}" ${titleAttr}>${entry[key]}</td>`;
				});
				tableBody += `<tr>${tableData}</tr>`;
			});

			headers.forEach((_, index) => {
				const className = index > 0 ? 'text-center' : '';
				const content = index > 0 ? '' : 'Total:';
				tableFoot += `<th class="${className}">${content}</th>`;
			});

			tables += `
				<div class="mb-3">
					<h4 id="dynamic-${id_variable}-Title">
						${name_variable}
						<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#collapse-dynamic-${id_variable}" data-arrow="down">
							${stcmbackend.svg.chevronDown}
						</button>
					</h4>
					<div id="collapse-dynamic-${id_variable}" class="collapse show">
						<table id="dynamic-${id_variable}-Table" class="table table-hover tRegs">
							${tableHead}
							<tbody>${tableBody}</tbody>
							<tfoot><tr>${tableFoot}</tr></tfoot>
						</table>
					</div>
				</div>`;
		});

		// Add dynamic tables to DOM
		$('#dynamicProfilingSections').html(tables);

		// Create search boxes
		$('[class^="filters-dynamic-"] td').each(function () {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;
			if (title === 'edit') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}
			$(this).html(value);
		});

		// Setup tables
		profilingSections.forEach(section => {
			selector = 'dynamic-' + section.id_variable;

			const licenseIndices = section.headers.reduce((acc, header, index) => {
				if (header.key.includes("licenses")) {
					acc.push(index);
				}
				return acc;
			}, []);
			let dataTable = $(`#${selector}-Table`).DataTable({
				retrieve: true,
				language: pf.const.language_table,
				paging: false,
				autoWidth: false,
				columnDefs: [],
				aaSorting: [],
				footerCallback(row, data, start, end, display) {
					licenseIndices.forEach(licenseCol => {
						total = this.api()
							.column(licenseCol, { page: 'current' })
							.data()
							.reduce(function (a, b) {
								return parseInt(a) + parseInt(b);
							}, 0);
						$(this.api().column(licenseCol).footer()).html(total);
					});
				},
			});

			// Hide table buttons
			hideTableButtons(`${selector}-Table`);

			// Apply searching mechanism
			applyTheSearch(dataTable, `filters-${selector}`);
		});
	},

	tableLicensesAdminsEvents() {
		let self = this;

		$('.btn-eye-admins').off().on('click', function () {
			let country = $(this).attr('data-country');

			let data = [];
			let detalleAdmins = self.data.detalleAdmins;
			let size = detalleAdmins.length;
			for (let i = 0; i < size; i++) {
				if (detalleAdmins[i].country == country) {
					data.push(detalleAdmins[i]);
				}
			}

			let title = pf.const.language.RSC1798;
			let subTitle = country.toUpperCase();
			self.renderDetalleAdmins(data, title, subTitle);
		});
	},

	exportExcel() {
		let self = this;

		let rsc = {
			perfstatus_region_abi: {
				title: [pf.const.language.RSC602],
				headers: [pf.const.language.RSC550, pf.const.language.RSC597, pf.const.language.RSC598, pf.const.language.RSC599, pf.const.language.RSC600]
			},
			perfstatus_region: {
				title: [pf.const.language.RSC603],
				headers: [pf.const.language.RSC550, pf.const.language.RSC597, pf.const.language.RSC601, pf.const.language.RSC599, pf.const.language.RSC600]
			},
			perfstatus_genero: {
				title: [pf.const.language.RSC605],
				headers: [pf.const.language.RSC550, pf.const.language.RSC597, pf.const.language.RSC151, pf.const.language.RSC599, pf.const.language.RSC600]
			},
			perfstatus_edad: {
				title: [pf.const.language.RSC604],
				headers: [pf.const.language.RSC550, pf.const.language.RSC597, pf.const.language.RSC565, pf.const.language.RSC599, pf.const.language.RSC600]
			},
			dataintegration: {
				title: [pf.const.language.RSC617],
				headers: [pf.const.language.RSC550, pf.const.language.RSC618, pf.const.language.RSC519, pf.const.language.RSC600]
			},
		}

		self.data['dataintegration'] = self.dataintegration;

		let parameters = {
			data: JSON.stringify(self.data),
			rsc: JSON.stringify(rsc)
		};
		ajaxComunCallWithCallback('exportStatusLicences', parameters, function (ajaxReturn) {
			if (ajaxReturn) {
				window.location = stcm.const.downloads + '/' + ajaxReturn.response;
				setTimeout(function () {
					self.deleteFiles(ajaxReturn.response);
				}, 1000 * 20);
			}
		});
	},

	deleteFiles(filename) {
		let parameters = {
			filename: filename
		};
		ajaxComunCallWithCallbackVoid('deleteFileExcel', parameters);
	},

	getQuestionDiscriminante() {
		let self = this;

		ajaxComunCallWithCallbackOne('getQuestionDiscriminante', {}, function (ajaxReturn) {
			if (ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				self.dataintegration = resp.dataintegration_cdp;
				self.dataintegrationDetail = resp.detalle;

				self.renderQuestionDiscriminante();
				removeLoader();
			}
		}, false);
	},

	renderQuestionDiscriminante() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC618}">${pf.const.language.RSC618}</th>
					<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>
					<th scope="col" title="${pf.const.language.RSC519}">${pf.const.language.RSC519}</th>
					<th scope="col" title="${pf.const.language.RSC600}">${pf.const.language.RSC600}</th>
					<th scope="col" title="${pf.const.language.RSC606}">${pf.const.language.RSC606}</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersIntegration">
				<tr>
					<td>pais</td>
					<td>consumo</td>
					<td>genero</td>
					<td>licencias</td>
					<td>licenciasOcupadas</td>
					<td>porcentaje</td>
					<td>eye</td>
				</tr>
			</thead>

			<tbody>
		`;

		let warningSearch = false;

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

			let trStyle = '';

			if (parseInt(self.dataintegration[i].licencias) < parseInt(self.dataintegration[i].licencias_en_uso)) {
				trStyle = `style="font-weight: bold; color:rgb(${self.color1RGB})"`;
				warningSearch = true;
			}

			let consumo = self.dataintegration[i].consumo == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121;

			table += `
				<tr ${trStyle}>
					<td class="text-truncate" title="${self.dataintegration[i].isocode}">${self.dataintegration[i].isocode}</td>
					<td class="text-truncate" title="${consumo}">${consumo}</td>
					<td class="text-truncate" title="${self.dataintegration[i].questionGenero}">${self.dataintegration[i].questionGenero}</td>
					<td class="text-truncate" title="${self.dataintegration[i].licencias}">${self.dataintegration[i].licencias}</td>
					<td class="text-truncate" title="${self.dataintegration[i].licencias_en_uso}">${self.dataintegration[i].licencias_en_uso}</td>
					<td class="text-truncate text-center" title="${self.percent(self.dataintegration[i].licencias_en_uso, self.dataintegration[i].licencias)}">${self.percent(self.dataintegration[i].licencias_en_uso, self.dataintegration[i].licencias)}</td>
					<td class="text-center">
						<button type="button" class="btn table-button main-color-text btn-eye-discriminate" data-country="${self.dataintegration[i].isocode}" data-consumo="${self.dataintegration[i].consumo}" data-genero="${self.dataintegration[i].questionGenero}" data-toggle="modal" data-target="#infoLicenses">
							${stcmbackend.svg.bigEyeWithoutColor}
						</button>
					</td>
				</tr>
			`;
		}

		if (warningSearch) {
			$('#discriminateTableTitle').append(self.warningIcon);
		}

		table += `
			</tbody>
		`;

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

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

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

		let dataTable = $('#discriminateTable').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{ width: '30px', targets: 6 }
			],
			aaSorting: []
		});

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

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

		self.tableLicensesDiscriminateEvents();

		$('#discriminateTable').on('draw.dt', function () {
			self.tableLicensesDiscriminateEvents();
		});
	},

	tableLicensesDiscriminateEvents() {
		let self = this;

		$('.btn-eye-discriminate').off().on('click', function () {
			let country = $(this).attr('data-country');
			let consumo = $(this).attr('data-consumo');
			let gender = $(this).attr('data-genero');

			let data = [];
			let detalle = self.dataintegrationDetail;
			let size = detalle.length;
			for (let i = 0; i < size; i++) {
				if (detalle[i].country == country && detalle[i].genero == gender && detalle[i].consumeAlcochol == consumo) {
					data.push(detalle[i]);
				}
			}

			let title = pf.const.language.RSC617;
			let subTitle = country.toUpperCase() + ' - ' + pf.const.language.RSC618 + ': ' + (consumo == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121) + ' - ' + gender;
			self.renderDetalle(data, title, subTitle);
		});
	},

	renderDetalle(data, title, subTitle) {
		let self = this;

		$('#licensesTitle').html(title);
		$('#licensesSubTitle').text(subTitle);
		$('#tableLicensesFooter').html(`
			<button id="exportDetail" type="button" class="btn secondary-button" title="${pf.const.language.RSC47}">
				${stcmbackend.svg.download}
				<span>${pf.const.language.RSC47}</span>
			</button>
		`);

		if (self.flag) {
			$('#tableLicenses').dataTable().fnDestroy();
		} else {
			self.flag = true;
		}

		let regionHead = '';
		let regionFilter = '';
		let regionAuxHead = '';
		let regionAuxFilter = '';
		let consumoHead = `<th scope="col" title="${pf.const.language.RSC983}">${pf.const.language.RSC983}</th>`;
		let consumoFilter = `<td>consumeAlcohol</td>`;
		if (sessionStorage['STCMBackEnd:Consumer'] == '0') {
			consumoHead = '';
			consumoFilter = '';
		}
		if (title == pf.const.language.RSC617) {
			regionHead = `<th scope="col" title="${pf.const.language.RSC597}">${pf.const.language.RSC597}</th>`;
			regionFilter = `<td>region</td>`;
			regionAuxHead = `<th scope="col" title="${pf.const.language.RSC608}">${pf.const.language.RSC608}</th>`;
			regionAuxFilter = `<td>regionABIaux</td>`;
			consumoHead = '';
			consumoFilter = '';
		}

		let regionABIHead = `<th scope="col" title="${pf.const.language.RSC601}">${pf.const.language.RSC601}</th>`;
		let regionABIFilter = `<td>regionABI</td>`;
		if (title == pf.const.language.RSC603) {
			regionABIHead = '';
			regionABIFilter = '';
		}

		let genderHead = `<th scope="col" title="${pf.const.language.RSC151}">${pf.const.language.RSC151}</th>`;
		let genderFilter = `<td>genero</td>`;
		if (title == pf.const.language.RSC605 || title == pf.const.language.RSC617) {
			genderHead = '';
			genderFilter = '';
		}

		let table = `
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						${regionHead}
						${regionABIHead}
						${regionAuxHead}
						<th scope="col" title="${pf.const.language.RSC565}">${pf.const.language.RSC565}</th>
						${genderHead}
						<th scope="col" title="ABI">ABI</th>
						<th scope="col" title="${pf.const.language.RSC124}">${pf.const.language.RSC124}</th>
						${consumoHead}
						<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
					</tr>
				</thead>

				<thead class="filters">
					<tr>
						<td>usuario</td>
						<td>nombre</td>
						${regionFilter}
						${regionABIFilter}
						${regionAuxFilter}
						<td>edad</td>
						${genderFilter}
						<td>ABI</td>
						<td>consejero</td>
						${consumoFilter}
						<td>creacion</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = data.length;
		for (let i = 0; i < size; i++) {
			let name = data[i].userNombre + ' ' + data[i].userApellidos + ' ' + data[i].userApellidos2;
			let regionBody = '';
			let regionAuxBody = '';
			let consumoBody = `
				<td class="text-center">
					<span class="d-none">${(data[i].consumeAlcochol == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
					<input type="checkbox" disabled ${(data[i].consumeAlcochol == '1' ? 'checked' : '')}>
				</td>
			`;
			if (sessionStorage['STCMBackEnd:Consumer'] == '0') {
				consumoBody = '';
			}
			if (title == pf.const.language.RSC617) {
				regionBody = `<td class="text-truncate" title="${data[i].region}">${(data[i].region != '' ? data[i].region : '-')}</td>`;
				regionAuxBody = `<td class="text-truncate" title="${data[i].regionABIAux}">${(data[i].regionABIAux != '' ? data[i].regionABIAux : '-')}</td>`;
				consumoBody = '';
			}

			let regionABIBody = `<td class="text-truncate" title="${data[i].regionABI}">${(data[i].regionABI != '' ? data[i].regionABI : '-')}</td>`;
			if (title == pf.const.language.RSC603) {
				regionABIBody = '';
			}

			let genderBody = `<td class="text-truncate" title="${data[i].genero}">${(data[i].genero != '' ? data[i].genero : '-')}</td>`;
			if (title == pf.const.language.RSC605 || title == pf.const.language.RSC617) {
				genderBody = '';
			}

			table += `
				<tr>
					<td class="text-truncate" title="${data[i].usuario}">${(data[i].usuario != '' ? data[i].usuario : '-')}</td>
					<td class="text-truncate" title="${name.trim()}">${name.trim()}</td>
					${regionBody}
					${regionABIBody}
					${regionAuxBody}
					<td class="text-center text-truncate" title="${data[i].edad}">${(data[i].edad != '' ? data[i].edad : '-')}</td>
					${genderBody}
					<td class="text-center text-truncate" title="${data[i].ABI}">${(data[i].ABI != '' ? data[i].ABI : '-')}</td>
					<td class="text-center">
						<span class="d-none">${(data[i].consejero == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(data[i].consejero == '1' ? 'checked' : '')}>
					</td>
					${consumoBody}
					<td class="text-truncate" title="${data[i].creationDate}">${(data[i].creationDate != '' ? data[i].creationDate : '-')}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#tableLicenses').html(table);
		$('.modal-body').addClass('pt-0');

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

			if (title == 'consejero' || title == 'consumeAlcohol') {
				value = optionsSelectAllYesNo();
			}

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

		let columnDefs = [];

		switch (title) {
			// Licencias por NSE
			case pf.const.language.RSC602:
				columnDefs = [
					{ width: '40px', targets: 3 },
					{ width: '70px', targets: 4 },
					{ width: '30px', targets: 5 },
					{ width: '75px', targets: 6 }
				];
				break;
			// Licencias por Region
			case pf.const.language.RSC603:
				columnDefs = [
					{ width: '40px', targets: 2 },
					{ width: '70px', targets: 3 },
					{ width: '30px', targets: 4 },
					{ width: '75px', targets: 5 }
				];
				break;
			// Licencias por Edad
			case pf.const.language.RSC604:
				columnDefs = [
					{ width: '40px', targets: 3 },
					{ width: '70px', targets: 4 },
					{ width: '30px', targets: 5 },
					{ width: '75px', targets: 6 }
				];
				break;
			// Licencias por Género
			case pf.const.language.RSC605:
				columnDefs = [
					{ width: '40px', targets: 3 },
					{ width: '30px', targets: 4 },
					{ width: '75px', targets: 5 }
				];
				break;
			// Integración
			case pf.const.language.RSC617:
				columnDefs = [
					{ width: '40px', targets: 5 },
					{ width: '30px', targets: 6 },
					{ width: '75px', targets: 7 }
				];
				break;
		}

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

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

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

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

		// Apply the search
		applyTheSearch(dataTable, 'filters');
	},

	renderDetalleAdmins(data, title, subTitle) {
		let self = this;

		$('#licensesTitle').html(title +
			`<button id="exportDetail" type="button" class="btn-nav btn button-excel" title="${pf.const.language.RSC47}">
				${stcmbackend.svg.download}
				<span class="d-none d-xl-inline">${pf.const.language.RSC47}</span>
			</button>`
		);
		$('#licensesSubTitle').text(subTitle);

		if (self.flag) {
			$('#tableLicenses').dataTable().fnDestroy();
		} else {
			self.flag = true;
		}

		let table = `
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC185}">${pf.const.language.RSC185}</th>
						<th scope="col" title="${pf.const.language.RSC137}">${pf.const.language.RSC137}</th>
						<th scope="col" title="${pf.const.language.RSC138}">${pf.const.language.RSC138}</th>
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC552}">${pf.const.language.RSC552}</th>
						<th scope="col" title="${pf.const.language.RSC1625}">${pf.const.language.RSC1625}</th>
						<th scope="col" title="${pf.const.language.RSC1716}">${pf.const.language.RSC1716}</th>
					</tr>
				</thead>

				<thead class="filters">
					<tr>
						<td>Nombre</td>
						<td>Apellidos</td>
						<td>Empresa</td>
						<td>Departamento</td>
						<td>Email</td>
						<td>Pais</td>
						<td>Idioma</td>
						<td>tenant</td>
						<td>cpg</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = data.length;
		for (let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-ellipsis" title="${data[i].name}">
						<span data-name="name" data-id="${i}">${data[i].name}</span>
					</td>
					<td class="text-ellipsis" title="${data[i].apellido1}">
						<span data-name="apellido1" data-id="${i}">${data[i].apellido1}</span>
					</td>
					<td class="text-ellipsis" title="${data[i].empresa}">
						<span data-name="empresa" data-id="${i}">${data[i].empresa}</span>
					</td>
					<td class="text-ellipsis" title="${(data[i].departamento == null ? '' : data[i].departamento)}">
						<span data-name="departamento" data-id="${i}">${(data[i].departamento == null ? '' : data[i].departamento)}</span>
					</td>
					<td class="text-ellipsis" title="${data[i].email}">
						<span data-name="email" data-id="${i}">${data[i].email}</span>
					</td>
					<td class="text-ellipsis" title="${data[i].country}">
						<span data-name="country" data-id="${i}">${data[i].country}</span>
					</td>
					<td class="text-ellipsis" title="${(data[i].lenguage == 'null' ? '-' : data[i].lenguage)}">
						<span data-name="lenguage" data-id="${i}">${(data[i].lenguage == 'null' ? '-' : data[i].lenguage)}</span>
					</td>
					<td class="text-ellipsis" title="${(data[i].idTenant || '-')}">
						<span data-name="idTenant" data-id="${i}">${(data[i].idTenant || '-')}</span>
					</td>
					<td class="text-ellipsis" title="${(data[i].idCPG || '-')}">
						<span data-name="idTenant" data-id="${i}">${(data[i].idCPG || '-')}</span>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#tableLicenses').html(table);
		$('.modal-body').addClass('pt-0');

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

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

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

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

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

		// Apply the search
		applyTheSearch(dataTable, 'filters');
	}
};