class TableUsers {
	constructor(type = 0, actions, country = '', consejero = '', enabled = '', staff = '', admin = '') {
		this.type = type;
		this.actionsTable = actions;
		this.data = null;
		this.members = [];
		this.modality = null;
		this.admin = null;
		this.surname = true;
		this.country = country;
		this.consejero = consejero;
		this.enabled = enabled;
		this.staff = staff;
		this.admin = admin;
		// Obtener gestión de GDPR y ocultar en caso necesario las columnas nombre y apellidos
		this.gdpr = sessionStorage['STCMBackEnd:GDPR'];
	}

	setEvents(modality = 'tableModal', admin = null) {
		let self = this;

		self.modality = modality;
		if(admin) {
			self.data = admin;
			self.renderTable();
		} else if(self.data) {
			self.renderTable();
		} else {
			self.requestUsers();
		}
	}

	requestUsers() {
		let self = this;

		clearGeneralModal();

		let parameters = {
			country: self.country,
			consejero: self.consejero,
			enabled: self.enabled,
			staff: self.staff,
			admin: self.admin
		};
		ajaxComunCallWithCallback('getAllUsers', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				self.renderTable();
			}
		});
	}

	renderTable() {
		let self = this;

		let headerCheckbox = '';
		let filterCheckbox = '';

		// Si la tabla de modal es de selección múltiple
		if(self.type === 1) {
			headerCheckbox = `
				<th class="text-center" scope="col" title="">
					<div class="div-global-selection">
						<input type="checkbox" class="globalSelection">
					</div>
				</th>
			`;

			filterCheckbox = `<td>selector</td>`;

			let acceptButton = `
				<button id="selectMembers" type="button" class="btn main-button" title="${pf.const.language.RSC141}">
					<span>${pf.const.language.RSC141}</span>
				</button>
			`;

			$('#divModalFooter').html(acceptButton);
		}

		let role = '';
		let roleLabel = '';
		let edit = '';
		let editLabel = '';
		if(this.modality == 'tableModal') {
			role = `<th scope="col" title="${pf.const.language.RSC277}">${pf.const.language.RSC277}</th>`;
			roleLabel = ' <td>Role</td>';
		} else {
			edit = `<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>`;
			editLabel = '<td>acciones</td>';
		}

		// Nombre en header
		let nameHeader = `<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>`;
		let nameFilter = `<td>Nombre</td>`;

		// Apellidos en header
		let surnamesHeader = `
			<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 surnameFilter = `
			<td>Apellido 1</td>
			<td>Apellido 2</td>
		`;

		if(!self.surname) {
			surnamesHeader = '';
			surnameFilter = '';
		}

		// Control GDPR
		if(self.gdpr == '1') {
			nameHeader = '';
			nameFilter = '';
			surnamesHeader = '';
			surnameFilter = '';
		}

		let table = `
			<table id="${this.modality}" class="table table-hover tr-pointer tRegs">
				<thead>
					<tr>
						${headerCheckbox}
						${nameHeader}
						${surnamesHeader}
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						<th scope="col" title="${pf.const.language.RSC134}">${pf.const.language.RSC134}</th>
						<th scope="col" title="${pf.const.language.RSC185}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC124}">${pf.const.language.RSC124}</th>
						<th scope="col" title="${pf.const.language.RSC126}">${pf.const.language.RSC126}</th>
						${role}
						${edit}
					</tr>
				</thead>

				<thead class="filtersUser">
					<tr>
						${filterCheckbox}
						${nameFilter}
						${surnameFilter}
						<td>E-mail</td>
						<td>perfil</td>
						<td>country</td>
						<td>consejero</td>
						<td>Enabled</td>
						${roleLabel}
						${editLabel}
					</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].country) == -1 && self.data[i].staff != '1') {
				continue;
			}

			// Comprobar si es el administrador para no incluirlo
			if(self.data[i].id != self.admin) {
				let bodyCheckbox = '';

				// Si la tabla de modal es de selección múltiple
				if(self.type === 1) {
					let checked = '';
					for(let j = 0; j < self.members.length; j++) {
						if(self.actionsTable === 'popUps') {
							if(self.members[j].idUser == self.data[i].email) {
								checked = 'checked';
							}
						} else {
							if(self.members[j].id == self.data[i].id) {
								checked = 'checked';
							}
						}
					}

					bodyCheckbox = `
						<td class="text-center">
							<div class="div-single-selection">
								<input type="checkbox" class="selection" ${checked}>
							</div>
						</td>
					`;
				}

				// Apellidos en body
				let surnameBody = `
					<td class="nameUser text-truncate editRow" title="${self.data[i].nameUser}">${self.data[i].nameUser}</td>
					<td class="text-truncate editRow" title="${(self.data[i].userApellidos && self.data[i].userApellidos != 'null' ? self.data[i].userApellidos : '-')}">${(self.data[i].userApellidos && self.data[i].userApellidos != 'null' ? self.data[i].userApellidos : '-')}</td>
					<td class="text-truncate editRow" title="${(self.data[i].userApellidos2 && self.data[i].userApellidos2 != 'null' ? self.data[i].userApellidos2 : '-')}">${(self.data[i].userApellidos2 && self.data[i].userApellidos2 != 'null' ? self.data[i].userApellidos2 : '-')}</td>
				`;

				if(!self.surname) {
					let surname1 = '';
					if(self.data[i].userApellidos && self.data[i].userApellidos != 'null') {
						surname1 = self.data[i].userApellidos 
					}

					let surname2 = '';
					if(self.data[i].userApellidos2 && self.data[i].userApellidos2 != 'null') {
						surname2 = self.data[i].userApellidos2 
					}

					let completName = self.data[i].nameUser + ' ' + surname1 + ' ' + surname2;
					surnameBody = `<td class="nameUser text-truncate editRow" title="${completName}">${completName}</td>`;
				}

				let roleValue = '';
				let editValue = '';
				if(this.modality == 'tableModal') {
					roleValue = `
						<td class="editRow" title="${(self.data[i].role == null ? '' : self.data[i].role)}">${(self.data[i].role == null ? '' : self.data[i].role)}</td>
					`;
				} else {
					editValue = `
						<td class="text-center">
							<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}">
								<p class="dropdown-item editRow m-0">
									${stcmbackend.svg.pencilWithoutColor}
									<span>${pf.const.language.RSC225}</span>
								</p>
							</div>
						</td>
					`;
				}

				// Control GDPR
				if(self.gdpr == '1') {
					surnameBody = '';
				}

				table += `
					<tr id="${self.data[i].id}" class="user_selected edit-group" data-id="${i}">
						${bodyCheckbox}
						${surnameBody}
						<td class="text-truncate editRow" title="${self.data[i].email}">${self.data[i].email}</td>
						<td class="text-truncate editRow" title="${self.data[i].profile}">${self.data[i].profile}</td>
						<td class="text-truncate editRow" title="${(self.data[i].country == undefined ? '-' : self.data[i].country)}">${(self.data[i].country == undefined ? '-' : self.data[i].country)}</td>
						<td class="text-center editRow">
							<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 editRow">
							<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>
						${roleValue}
						${editValue}
					</tr>
				`;
			}
		}

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

		if(this.modality == 'tableModal') {
			$('#headerModalTitle').text(pf.const.language.RSC2);
			$('#divTableModal').html(table);
		} else {
			$('#resultTable').html(table);
		}

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

			if(title == 'Enabled' || title == 'consejero') {
				value = optionsSelectAllYesNo();
			} else if(title == 'acciones' || title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let tableUsers = '';
		let columnDefs = [];
		if(self.modality != 'tableModal') {
			// Cambio de columnas para apellidos
			if(self.surname) {
				columnDefs = [
					{width: '60px', targets: 5},
					{width: '60px', targets: 6},
					{width: '60px', targets: 7},
					{width: '60px', orderable: false, targets: 8}
				];

				if(self.gdpr == '1') {
					columnDefs = [
						{width: '60px', targets: 2},
						{width: '60px', targets: 3},
						{width: '60px', targets: 4},
						{width: '60px', orderable: false, targets: 5}
					];
				}
			} else {
				columnDefs = [
					{width: '60px', targets: 3},
					{width: '60px', targets: 4},
					{width: '60px', targets: 5},
					{width: '60px', orderable: false, targets: 6}
				];

				if(self.gdpr == '1') {
					columnDefs = [
						{width: '60px', targets: 2},
						{width: '60px', targets: 3},
						{width: '60px', targets: 4},
						{width: '60px', orderable: false, targets: 5}
					];
				}
			}

			tableUsers = $('#' + this.modality).DataTable({
				language: pf.const.language_table,
				autoWidth: false,
				aaSorting: [],
				columnDefs: columnDefs,
				retrieve: true,
				paging: true,
				pageLength: 25,
				dom: 'Bfrtip',
				buttons: [{
					extend: 'excelHtml5',
					text: pf.const.language.RSC129,
					className: 'd-none',
					title: pf.const.language.RSC2,
					customize(xlsx) {
						dataTablesExcelCustomize(xlsx);
					}
				}]
			});
		} else {
			// Cambio de columnas para apellidos
			if(self.surname) {
				columnDefs = [
					{width: '60px', targets: 5},
					{width: '80px', targets: 6},
					{width: '70px', targets: 7},
					{width: '70px', targets: 8}
				];

				if(self.type === 1) {
					columnDefs = [
						{width: '25px', orderable: false, targets: 0},
						{width: '60px', targets: 6},
						{width: '80px', targets: 7},
						{width: '70px', targets: 8},
						{width: '70px', targets: 9}
					];
				}

				if(self.gdpr == '1') {
					columnDefs = [
						{width: '60px', targets: 2},
						{width: '80px', targets: 3},
						{width: '70px', targets: 4},
						{width: '70px', targets: 5}
					];

					if(self.type === 1) {
						columnDefs = [
							{width: '25px', orderable: false, targets: 0},
							{width: '60px', targets: 3},
							{width: '80px', targets: 4},
							{width: '70px', targets: 5},
							{width: '70px', targets: 6}
						];
					}
				}
			} else {
				columnDefs = [
					{width: '60px', targets: 3},
					{width: '80px', targets: 4},
					{width: '70px', targets: 5},
					{width: '70px', targets: 6}
				];

				if(self.type === 1) {
					columnDefs = [
						{width: '25px', orderable: false, targets: 0},
						{width: '60px', targets: 4},
						{width: '80px', targets: 5},
						{width: '70px', targets: 6},
						{width: '70px', targets: 7}
					];
				}

				if(self.gdpr == '1') {
					columnDefs = [
						{width: '60px', targets: 2},
						{width: '80px', targets: 3},
						{width: '70px', targets: 4},
						{width: '70px', targets: 5}
					];

					if(self.type === 1) {
						columnDefs = [
							{width: '25px', orderable: false, targets: 0},
							{width: '60px', targets: 3},
							{width: '80px', targets: 4},
							{width: '70px', targets: 5},
							{width: '70px', targets: 6}
						];
					}
				}
			}

			tableUsers = $('#' + this.modality).DataTable({
				language: pf.const.language_table,
				scrollY: 300,
				scroller: false,
				paging: true,
				pageLength: 25,
				columnDefs: columnDefs,
				autoWidth: false,
				aaSorting: []
			});
		}

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

		// Ocultar botones de tabla
		hideTableButtons(this.modality);

		// Apply the search
		applyTheSearch(tableUsers, 'filtersUser');

		if(self.modality != 'tableModal') {
			// Exportar tabla
			$('#exportUsers').off().on('click', function() {
				$('#resultTable .buttons-excel').trigger('click');
			});
		}

		if(self.type === 0) {
			$('#' + this.modality + ' tbody').off().on('click', '.editRow', function() {
				self.eventsTable($(this).parent().data('id'));
				$('#closeUser').trigger('click');
				sessionStorage['editUserCountry'] = btoa(self.country);
			});
		} else {
			self.multiSelectTableEvents();

			$('#tableModal').on('draw.dt', function() {
				self.multiSelectTableEvents();
			});

			// Selección de múltiples miembros
			$('#selectMembers').off().on('click', function() {
				addLoader();
				$('#closeUser').trigger('click');
				setTimeout(function() {
					tableUsers.destroy();
					self.members = [];

					let positionMember = '';
					$('#tableModal tr').each(function() {
						let cheked = $(this).find('.selection');
						if(cheked.prop('checked')) {
							positionMember = $(this).data('id');
							self.members.push(self.data[positionMember]);
						}
					});
					self.eventsTable(0);
					removeLoader();
				}, 500);
			});
		}
	}

	multiSelectTableEvents() {
		inputControl();

		// Selección por tr
		$('#tableModal tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			inputControl();
		});

		// Selección por input check
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelection').off().on('change', function() {
			if($('.globalSelection').prop('checked')) {
				$('.selection').prop('checked', true);
			} else {
				$('.selection').prop('checked', false);
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	}

	eventsTable(id) {
		let self = this;

		let response = '';
		if(self.type === 0) {
			response = self.data[id];
		} else {
			response = self.members;
		}

		switch(self.actionsTable) {
			case 'newGroups':
				GruposNuevoController.clickEvents(response);
				break;
			case 'editGroups':
				GruposEditarController.clickEvents(response);
				break;
			case 'DifusionNewAdmin':
			case 'DifusionNewCrew':
				DifusionNewController.clickEvents(response);
				break;
			case 'DifusionEditAdmin':
			case 'DifusionEditCrew':
				DifusionEditController.clickEvents(response);
				break;
			case 'users':
				UsuariosController.clickEvents(response);
				break;
			case 'editUser':
				UsuariosEditarController.clickEvents(response);
				break;
			case 'newUser':
				UsuariosNuevoController.clickEvents(response);
				break;
			case 'newProjectLeader':
				ProyectosNewController.clickEvents(response);
				break;
			case 'editProjectLeader':
				ProyectosEditController.clickEvents(response);
				break;
			case 'newNotification':
				NotificacionesNuevaController.clickUser(response);
				break;
			case 'editNotification':
				NotificacionesEditarController.clickUser(response);
				break;
			case 'configuration':
				ConfiguracionController.selectUser(response);
				break;
			case 'configurationMissions':
				ConfiguracionController.selectUserMissions(response);
				break;
			case 'pagosAutomatizadosNew':
				PagosAutomatizadosNewController.clickUser(response);
				break;
			case 'pagosAutomatizadosEdit':
				PagosAutomatizadosEditController.clickUser(response);
				break;
			case 'editCountry':
				PaisesEditController.clickUser(response);
				break;
			case 'newAdministradorAppUser':
				AdministradoresNuevoController.clickEvents(response);
				break;
			case 'editAdministradorAppUser':
				AdministradoresEditarController.clickEvents(response);
				break;
			case 'newProductProjectLeader':
				ProductoProyectoNewController.clickEvents(response);
				break;
			case 'editProductProjectLeader':
				ProductoProyectoEditController.clickEvents(response);
				break;
			case 'popUps':
				PopUpsController.clickEvents(response);
				break;
			case 'StepByStepProjectNewController':
				StepByStepProjectNewController.clickEvents(response);
				break;
			case 'StepByStepProjectEditController':
				StepByStepProjectEditController.clickEvents(response);
				break;
		}
	}
}