let AdministradoresNuevoController = {
	userType: null,
	countries: [],
	idTenant: null,
	userAdmin: '',
	idCPG: '',
	loaders: {},

	reset() {
		let self = this;

		self.userType = null;
		self.countries = [];
		self.idTenant = sessionStorage['STCMBackEnd:idTenant'];
		self.userAdmin = '';
		self.idCPG = '';
		self.loaders = {
			getIdiomas: false,
			getPaises: false
		};
	},

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

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

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

		// Obtener uso de Tenant
		let showTenant = sessionStorage['STCMBackEnd:multiTenant'];

		// Ocultar inputs de tenant
		if((self.idTenant !== 0 && self.idTenant !== '0') || showTenant == '0') {
			$('#tenantInput').removeClass('d-flex');
			$('#tenantInput').hide();

			// Tenant a 0
			if(showTenant == '0') {
				$('#idTenant').text('0');
			}
		}

		// Obtener idCPG y empresa
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.idCPG = user.idCPG;
		let empresa = user.empresa;
		self.userAdmin= user.email;

		// Ocultar elemento si no se trabaja con clientes
		if(sessionStorage['STCMBackEnd:globalWorkingwithClients'] == 'false') {
			$('#customersContainer').hide();
		}

		// Ocultar inputs de tenant para CPGs que no sean 0 y dejar el valor marcado al CPG del usuario
		if(self.idCPG !== '0' && self.idCPG !== 0) {
			$('#tenantInput').removeClass('d-flex');
			$('#tenantInput').hide();
			$('#idTenant').text(self.idTenant);
			$('#empresa').prop('disabled', true);
			$('#empresa').val(empresa);
		}

		// Opciones de header
		let jsonsubopt = {
			back: 'backLists',
			save: 'btn-setCatalog'
		};

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

		// Botones secundarios
		$('#backLists').addClass('secondary-button');

		stcmbackend.administradores.loadLanguage(self);

		// Iniciar spinner
		addLoader();
		ajaxComunCallWithCallback('getIdiomas', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let idiomas = ajaxReturn.result;

				// Búsqueda de idiomas activos y creación de select
				let options = '';
				let sizeA = idiomas.length;
				for(let i = 0; i < sizeA; i++) {
					if(idiomas[i].enabled == 1) {
						options += `<option value="${idiomas[i].isocode}">${idiomas[i].descripcion}</option>`;
					}
				}

				$('#idioma').html(options);

				// Control de spinner
				self.loaders.getIdiomas = true;
				spinnerControl(self.loaders);
			}
		}, false);

		ajaxComunCallWithCallback('getPaises', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let sizeC = ajaxReturn.result.length;
				for(let i = 0; i < sizeC; i++) {
					if(ajaxReturn.result[i].enabled == '1') {
						self.countries.push(ajaxReturn.result[i]);
					}
				}

				self.renderCountriesEnabled();

				// Control de spinner
				self.loaders.getPaises = true;
				spinnerControl(self.loaders);
			}
		}, false);

		stcmbackend.administradores.sharedEvents(self);
		self.applyEvents();

		setTimeout(function() {
			$('#passwordAPI').attr('type', 'password');
		}, 500);

		// Control de países permitidos por el administrador si solo hay uno
		let countries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		if(countries.length === 1) {
			$('#pais').val(countries[0]);
		}

		// Pintar texto de label
		changeLabelsColor();
	},

	applyEvents() {
		let self = this;

		//Mostrar contraseña
		$('#btn-passwordAPI').mousedown(function() {
			$('#passwordAPI').attr('type', 'text');
		});
		$('#btn-passwordAPI').mouseup(function() {
			$('#passwordAPI').attr('type', 'password');
		});

		// Guardar usuario administrador
		$('#btn-setCatalog').click(function() {
			if($('#appUser').val() === '') {
				// Comprobación de licencias
				ajaxComunCallWithCallback('getFreeLicences', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						if(ajaxReturn.result > 0) {
							self.setUserAPI();
						} else {
							let warningTitle = pf.const.language.RSC21;
							let WarningContent = pf.const.language.RSC1254;
							pf.utils.showInfoDialog(warningTitle, WarningContent);
						}
					}
				});
			} else {
				self.setUserAPI();
			}
		});

		// Modal de usuarios
		let users = new TableUsers(0, 'newAdministradorAppUser', '', 1, 1, 1, 1);
		$('#btn-appUser').click(function() {
			users.surname = false;
			self.userType = 'appUser';
			users.setEvents('tableModal');
		});

		// País
		let countryModal = new TableCountries(0, 'newAdministradorCountry');
		$('#searchCountry').off().on('click', function() {
			self.userType = 'country';
			countryModal.setEvents();
		});

		// Modal de roles
		$('#btn-role').click(function() {
			self.userType = 'rol';
			tableBackendAdminRol.setEvents('newUser', self.idCPG);
		});

		// Modal de tenant
		let tenantModal = new TableTenant('newAdministradorTenant');
		$('#searchTenant').click(function() {
			self.userType = 'tenant';
			tenantModal.setEvents();
		});

		// Cliente
		let customerModal = new TableCustomers('newAdministradorCustomer');
		$('#searchCustomer').off().on('click', function() {
			self.userType = 'customer';
			customerModal.setEvents();
		});
	},

	renderCountriesEnabled() {
		let self = this;

		let table = `
			<table id="tableCountries" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="ISO">
							ISO
						</th>
						<th scope="col" title="${pf.const.language.RSC549}">
							${pf.const.language.RSC549}
							<span class="float-right">${pf.const.language.RSC278}:</span>
						</th>
						<th scope="col">
							<div class="custom-control custom-switch">
								<input id="allSwitchs" type="checkbox" class="custom-control-input">
								<label for="allSwitchs" class="custom-control-label c-pointer"></label>
							</div>
						</th>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		// Obtener rol de usuario
		let userData = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let userRol = userData.role;
		let size = self.countries.length;
		for(let i = 0; i < size; i ++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.countries[i].isocode) == -1 && userRol != 'FullAdmin') {
				continue;
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.countries[i].isocode}">${self.countries[i].isocode}</td>
					<td class="text-truncate" title="${self.countries[i].descripcion}">${self.countries[i].descripcion}</td>
					<td>
						<div class="custom-control custom-switch">
							<input id="${self.countries[i].isocode}" type="checkbox" class="custom-control-input uSwitch">
							<label for="${self.countries[i].isocode}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

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

		let tableCountries = $('#tableCountries').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			searching: false,
			ordering: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 0},
				{width: '30px', targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC549,
				className: 'd-none',
				title: pf.const.language.RSC549,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		stcmbackend.administradores.switchEvents(self);
	},

	setUserAPI() {
		let self = this;

		let formIncomplete = false;
		let activo = ($('#enabledUser').prop('checked') ? '1' : '0');
		let email = $('#email').val().trim();
		if(email == '' || !pf.utils.validateEmail(email)) {
			formIncomplete = true;
			$('#email').addClass('is-invalid');
			$('[for="email"]').addClass('is-invalid');
		} else {
			$('#email').removeClass('is-invalid');
			$('[for="email"]').removeClass('is-invalid');
		}
		let passwordAPI = $('#passwordAPI').val().trim();
		if(passwordAPI == '') {
			formIncomplete = true;
			$('#passwordAPI').addClass('is-invalid');
			$('#pass-group').addClass('group-invalid');
			$('[for="passwordAPI"]').addClass('is-invalid');
		} else {
			$('#passwordAPI').removeClass('is-invalid');
			$('#pass-group').removeClass('group-invalid');
			$('[for="passwordAPI"]').removeClass('is-invalid');
		}
		let country = $('#pais').val();
		if(country == '') {
			formIncomplete = true;
			$('#pais').addClass('is-invalid');
			$('#pais-group').addClass('group-invalid');
			$('[for="pais"]').addClass('is-invalid');
		} else {
			$('#pais').removeClass('is-invalid');
			$('#pais-group').removeClass('group-invalid');
			$('[for="pais"]').removeClass('is-invalid');
		}
		let lenguage = $('#idioma').val();
		let role = $('#role').val();
		if(role == '') {
			formIncomplete = true;
			$('#role').addClass('is-invalid');
			$('#role-group').addClass('group-invalid');
			$('[for="role"]').addClass('is-invalid');
		} else {
			$('#role').removeClass('is-invalid');
			$('#role-group').removeClass('group-invalid');
			$('[for="role"]').removeClass('is-invalid');
		}
		let name = $('#name').val().trim();
		if(name == '') {
			formIncomplete = true;
			$('#name').addClass('is-invalid');
			$('[for="name"]').addClass('is-invalid');
		} else {
			$('#name').removeClass('is-invalid');
			$('[for="name"]').removeClass('is-invalid');
		}
		let userapellidos = $('#apellido1').val().trim();
		if(userapellidos == '') {
			formIncomplete = true;
			$('#apellido1').addClass('is-invalid');
			$('[for="apellido1"]').addClass('is-invalid');
		} else {
			$('#apellido1').removeClass('is-invalid');
			$('[for="apellido1"]').removeClass('is-invalid');
		}
		let userapellidos2 = $('#apellido2').val().trim();
		let empresa = $('#empresa').val().trim();
		if(empresa == '') {
			formIncomplete = true;
			$('#empresa').addClass('is-invalid');
			$('[for="empresa"]').addClass('is-invalid');
		} else {
			$('#empresa').removeClass('is-invalid');
			$('[for="empresa"]').removeClass('is-invalid');
		}
		let departamento = $('#departamento').val().trim();

		// idTenant
		let tenant = '';
		if(self.idTenant !== 0 && self.idTenant !== '0') {
			tenant = self.idTenant;
		} else {
			if($('#tenantPrincipal').prop('checked')) {
				tenant = 0;
				$('#tenant').removeClass('is-invalid');
				$('#tenant-group').removeClass('group-invalid');
				$('[for="tenant"]').removeClass('is-invalid');
			} else {
				tenant = $('#idTenant').text();
				if(tenant == '') {
					formIncomplete = true;
					$('#tenant').addClass('is-invalid');
					$('#tenant-group').addClass('group-invalid');
					$('[for="tenant"]').addClass('is-invalid');
				} else {
					$('#tenant').removeClass('is-invalid');
					$('#tenant-group').removeClass('group-invalid');
					$('[for="tenant"]').removeClass('is-invalid');
				}
			}
		}

		let resetPassword = ($('#resetPassword').prop('checked') ? '1' : '0');

		// Comprobación
		if(formIncomplete) {
			let alertTitle = pf.const.language.RSC21;
			let alertText = pf.const.language.RSC101;
			pf.utils.showInfoDialog(alertTitle, alertText);
			return;
		}

		// Países permitidos
		let countries = [];
		$('.uSwitch').each(function() {
			if($(this).prop('checked') == true) {
				countries.push($(this).attr('id'));
			}
		});

		let parameters = {
			mustResetPass: resetPassword,
			enabled: activo,
			email: email,
			username: name,
			userapellidos: userapellidos,
			userapellidos2: userapellidos2,
			empresa: empresa,
			departamento: departamento,
			lenguage: lenguage,
			role: role,
			countries: countries,
			idTenant: tenant,
			idCPG: self.idCPG,
			country: country,
			appUser: $('#appUser').val(),
			userAdmin: self.userAdmin,
			passwordAPI: passwordAPI,
			idCliente: $('#customers').data('id')
		};
		ajaxComunCallWithCallback('registerAPIUser', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(ajaxReturn.exist) {
					let errorTitle = pf.const.language.RSC78;
					// Ya existe un usuario con ese email
					let errorContent = pf.const.language.RSC314;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				} else {
					let errorTitle = pf.const.language.RSC78;
					// Los cambios se han guardado correctamente
					let errorContent = pf.const.language.RSC106;
					pf.utils.showInfoDialog(errorTitle, errorContent);
					window.location.href = '#!administradores_backend';
				}
			}
		});
	},

	clickEvents(data) {
		let self = this;

		switch(self.userType) {
			case 'rol':
				$('#role').val(data.role);
				break;
			// Seleccionar país
			case 'country':
				$('#pais').val(data.isocode);
				break;
			// Seleccionar tenant
			case 'tenant':
				$('#tenant').val(data.razonSocial);
				$('#idTenant').text(data.idTenant);
				break;
			// Seleccionar Usuario de App
			case 'appUser':
				$('#appUser').val(data.email);
				$('#appUser').attr('title', data.email);
				$('#appUserDelete').show();
				break;
			// Seleccionar cliente
			case 'customer':
				$('#customers').val(data.nombreComercial);
				$('#customers').data('id', data.idCustomer);
				break;
		}
	}
};