let RolesBackendController = {
	data: '',
	arrayDelMult: [],
	userAdmin: '',

	reset() {
		let self = this;

		self.data = '';
		self.arrayDelMult = [];
		self.userAdmin = '';
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.userAdmin = user.email;

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

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

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

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

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

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

		let parameters = {
			cpgUser: ''
		};
		ajaxComunCallWithCallback('getAllAdminRolesMenu', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				// Tabla de resultados
				self.renderData();
			}
		});

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!roles_backend_new';
		});
	},

	renderData() {
		let self = this;

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

		let table = `
			<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.RSC277}">${pf.const.language.RSC277}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>selector</td>
						<td>rol</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="${self.data[i].role}">
					<td class="text-truncate text-center">
						<div class="div-single-selection" data-id="${self.data[i].role}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].role}">${self.data[i].role}</td>
					<td class="text-truncate 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="${self.data[i].role}">
							<p class="dropdown-item editRow">
								${stcmbackend.svg.pencilWithoutColor}
								<span>${pf.const.language.RSC225}</span>
							</p>
							<p class="dropdown-item deleteRow">
								${stcmbackend.svg.trashWithoutColor}
								<span>${pf.const.language.RSC95}</span>
							</p>
						</div>
					</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" disabled>`;

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

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '60px', orderable: false, targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1278,
				className: 'd-none',
				title: pf.const.language.RSC1278,
				exportOptions: {
					columns: [1]
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

		self.tableEvents(dataTable);

		// Eventos con cambio de página de tabla
		$('#registers').on('draw.dt', function() {
			self.tableEvents(dataTable);
		});
	},

	tableEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

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

			sessionStorage.setItem('rol_backend', btoa(id));
			window.location.href = '#!roles_backend_edit';
		});

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

			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC1278;
			let alertText = pf.const.language.RSC268;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteAdminRoleMenu(id);
			}, function() {});
		});

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

			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.RSC1278;
			let alertText = pf.const.language.RSC1687;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteAdminRoleMenu();
			}, function() {});
		});
	},

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

		let admins = null;
		let adminRoles = [];
		let controlAdminRoles = [];
		if(id !== false) {
			let obj = {
				id: id
			}
			adminRoles.push(obj);
			controlAdminRoles.push(id.toString());
		} else {
			let delSize = self.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				let obj = {
					id: self.arrayDelMult[i]
				}
				adminRoles.push(obj);
				controlAdminRoles.push(self.arrayDelMult[i].toString());
			}
			self.arrayDelMult = [];
		}

		ajaxComunCallWithCallback('getAllUsersAPI', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				admins = ajaxReturn.result;
				countAdminRoles = 0;

				let size = admins.length;
				for(let i = 0; i < size; i++) {
					if(controlAdminRoles.includes(admins[i].role)) {
						countAdminRoles++;
					}
				}

				if(countAdminRoles > 0) {
					let objInfo = {
						accept: {
							text: pf.const.language.RSC95
						},
						cancel: {
							text: pf.const.language.RSC57
						}
					};

					let alertTitle = pf.const.language.RSC1278;
					let alertText = pf.const.language.RSC2152;
					pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
						let parameters = {
							adminRoles: JSON.stringify(adminRoles),
							userAdmin: self.userAdmin
						};
						ajaxComunCallWithCallback('deleteAdminRoleMenu', parameters, function(ajaxReturn) {
							if(ajaxReturn) {
								let successTitle = pf.const.language.RSC1278;
								let successContent = pf.const.language.RSC267;
								pf.utils.showInfoDialog(successTitle, successContent);
								loadHTML('inc/administradores/roles_backend.html', 'wrapper', RolesBackendController);
							}
						});
					}, function() {});
				} else {
					let parameters = {
						adminRoles: JSON.stringify(adminRoles)
					};
					ajaxComunCallWithCallback('deleteAdminRoleMenu', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							let successTitle = pf.const.language.RSC1278;
							let successContent = pf.const.language.RSC267;
							pf.utils.showInfoDialog(successTitle, successContent);
							loadHTML('inc/administradores/roles_backend.html', 'wrapper', RolesBackendController);
						}
					});
				}
			}
		});
	}
};