let AdministradoresController = {
	usersAPI: null,
	arrayDelMult: [],

	reset() {
		let self = this;

		self.usersAPI = null;
		self.arrayDelMult = [];
	},

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

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

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

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

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

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

		$('#btn-newUser svg').css('width', '24px');
		$('#btn-newUser svg').css('height', '24px');

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

		ajaxComunCallWithCallback('getAllUsersAPI', {}, self.getAllUsersAPI);

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

		// Collapse
		addEventArrowTableHeader();
	},

	// Callback, como sale de zona pierde el 'this'
	getAllUsersAPI(ajaxReturn) {
		let self = AdministradoresController;

		if(ajaxReturn) {
			self.usersAPI = ajaxReturn.result;

			self.renderUsersAPI();
		}
	},

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

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

	applyEvents() {
		// Nuevo usuario administrador
		$('#btn-newUser').click(function() {
			window.location.href = '#!administradores_backend/nuevo';
		});
	},

	renderUsersAPI() {
		let self = this;

		let render = `
			<table id="registers" class="table table-hover">
				<thead>
					<tr>
						<th class="text-center" scope="col" title="">
							<div class="div-global-selection">
								<input type="checkbox" class="globalSelection">
							</div>
						</th>
						<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>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>selector</td>
						<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>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		// idTenant del administrador
		let idTenant = sessionStorage['STCMBackEnd:idTenant'];

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let idCPG = user.idCPG;
		let CPGAdmin = sessionStorage['STCMBackEnd:CPGAdmin'];
		let secAdmin = false;
		if(idCPG != '0' && CPGAdmin == '0') {
			secAdmin = true;
		}

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		$.each(self.usersAPI, function(i, value) {
			// Control de países permitidos
			if(self.usersAPI[i].country == '' || allowedCountries.indexOf(self.usersAPI[i].country) != -1) {
				// Edición de registro
				let edition = 'c-pointer editRow';
				let editAction = `
					<p class="dropdown-item editRow">
						${stcmbackend.svg.pencilWithoutColor}
						<span>${pf.const.language.RSC225}</span>
					</p>
				`;

				if(idTenant != self.usersAPI[i].idTenant || secAdmin) {
					edition = '';
					editAction = '';
				}

				// Eliminación de registro
				let deleteInput = `
					<div class="div-single-selection" data-id="${i}">
						<input type="checkbox" class="deleteSelection">
					</div>
				`;

				// Acciones de registro
				let actions = `
					<div id="dropdownActions${i}" class="div-dd-actions c-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
						${stcmbackend.svg.threeDotsVertical18}
					</div>

					<div class="dropdown-menu dropdown-menu-right shadow menu-actions" aria-labelledby="dropdownActions${i}" data-id="${i}">
						${editAction}
						<p class="dropdown-item deleteRow">
							${stcmbackend.svg.trashWithoutColor}
							<span>${pf.const.language.RSC95}</span>
						</p>
					</div>
				`;

				if(secAdmin) {
					deleteInput = '';
					actions = '';
				}

				render += `
					<tr data-id="${i}">
						<td class="text-center">
							${deleteInput}
						</td>
						<td class="text-ellipsis ${edition}" title="${self.usersAPI[i].name}">
							<span data-name="name" data-id="${i}">${self.usersAPI[i].name}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${self.usersAPI[i].apellido1}">
							<span data-name="apellido1" data-id="${i}">${self.usersAPI[i].apellido1}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${self.usersAPI[i].empresa}">
							<span data-name="empresa" data-id="${i}">${self.usersAPI[i].empresa}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${(self.usersAPI[i].departamento == null ? '' : self.usersAPI[i].departamento)}">
							<span data-name="departamento" data-id="${i}">${(self.usersAPI[i].departamento == null ? '' : self.usersAPI[i].departamento)}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${self.usersAPI[i].email}">
							<span data-name="email" data-id="${i}">${self.usersAPI[i].email}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${self.usersAPI[i].country}">
							<span data-name="country" data-id="${i}">${self.usersAPI[i].country}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${(self.usersAPI[i].lenguage == 'null' ? '-' : self.usersAPI[i].lenguage)}">
							<span data-name="lenguage" data-id="${i}">${(self.usersAPI[i].lenguage == 'null' ? '-' : self.usersAPI[i].lenguage)}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${(self.usersAPI[i].idTenant || '-')}">
							<span data-name="idTenant" data-id="${i}">${(self.usersAPI[i].idTenant || '-')}</span>
						</td>
						<td class="text-ellipsis ${edition}" title="${(self.usersAPI[i].idCPG || '-')}">
							<span data-name="idTenant" data-id="${i}">${(self.usersAPI[i].idCPG || '-')}</span>
						</td>
						<td class="text-center" data-id="${i}">
							${actions}
						</td>
					</tr>
				`;
			}
		});

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

		// Print usersAPI
		$('#resultTable').html(render);

		// 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 == 'selector' || title == 'acciones') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '200px', targets: 5},
				{width: '40px', targets: 6},
				{width: '60px', targets: 7},
				{width: '45px', targets: 8},
				{width: '45px', targets: 9},
				{width: '60px', orderable: false, targets: 10}
			],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC21,
				exportOptions: {
					columns: [1, 2, 3, 4, 5, 6, 7, 8, 9]
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
		});

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

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

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

		self.tableEvents();

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

	tableEvents() {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

		// Editar administrador
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			sessionStorage['STCMBackEnd:editUser'] = btoa(JSON.stringify(self.usersAPI[id]));
			window.location.href = '#!administradores_backend/editar';
		});

		// Eliminar administrador
		$('.deleteRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			// Comprobar si el usuario logueado es el usuario a borrar
			let userEmail = JSON.parse(sessionStorage['STCMBackEnd:user']);
			if(self.usersAPI[id].email == userEmail.email) {
				let alertTitle = pf.const.language.RSC21;
				let alertText = pf.const.language.RSC324;
				pf.utils.showInfoDialog(alertTitle, alertText);
			} else {
				let objInfo = {
					accept: {
						text: pf.const.language.RSC95
					},
					cancel: {
						text: pf.const.language.RSC57
					}
				};

				let alertTitle = pf.const.language.RSC21;
				let alertText = pf.const.language.RSC285;
				pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
					self.removeUser(id);
				}, function() {});
			}
		});

		// Array de eliminado múltiple
		$('.deleteSelection').off().on('change', function() {
			let value = $(this).prop('checked');
			let id = $(this).parent().data('id');

			// Comprobar si el usuario logueado es el usuario a seleccionar
			let userEmail = JSON.parse(sessionStorage['STCMBackEnd:user']);
			if(self.usersAPI[id].email == userEmail.email) {
				$(this).prop('checked', false);

				let alertTitle = pf.const.language.RSC21;
				let alertText = pf.const.language.RSC324;
				pf.utils.showInfoDialog(alertTitle, alertText);

				return false;
			}

			if(value) {
				self.arrayDelMult.push(id);
			} else {
				let index = self.arrayDelMult.indexOf(id);
				self.arrayDelMult.splice(index, 1);
			}

			// Eventos de los inputs individuales
			deleteSelectionInputActions(self.arrayDelMult);
		});

		// Función de borrado múltiple
		$('#multSelecDelete').off().on('click', function() {
			// Aviso de borrado múltiple
			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC21;
			let alertText = pf.const.language.RSC1698;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.removeUser();
			}, function() {});
		});
	},

	removeUser(id = false) {
		let self = this;

		let userEmail = JSON.parse(sessionStorage['STCMBackEnd:user']);

		let adminUsers = [];
		if(id !== false) {
			let obj = {
				email: self.usersAPI[id].email
			}
			adminUsers.push(obj);
		} else {
			let delSize = self.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				if(self.usersAPI[self.arrayDelMult[i]].email == userEmail.email) {
					let alertTitle = pf.const.language.RSC21;
					let alertText = pf.const.language.RSC324;
					pf.utils.showInfoDialog(alertTitle, alertText);
					return;
				}
				let obj = {
					email: self.usersAPI[self.arrayDelMult[i]].email
				}
				adminUsers.push(obj);
			}
			self.arrayDelMult = [];
		}

		let parameters = {
			adminUsers: JSON.stringify(adminUsers)
		};
		ajaxComunCallWithCallback('dropUserAPI', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let errorTitle = pf.const.language.RSC95;
				let errorContent = pf.const.language.RSC286;
				pf.utils.showInfoDialog(errorTitle, errorContent);

				ajaxComunCallWithCallback('getAllUsersAPI', {}, self.getAllUsersAPI);
			}
		});
	}
};