let AdministradoresEditarController = {
	userAPI: null,
	userType: null,
	countries: [],
	userCountries: [],
	allowedCountries: '',
	idTenant: null,
	enabledOld: '',
	userAdmin: '',
	loaders: {},

	reset() {
		let self = this;

		self.userAPI = JSON.parse(atob(sessionStorage['STCMBackEnd:editUser']));
		self.userType = null;
		self.countries = [];
		self.userCountries = [];
		self.allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		self.idTenant = sessionStorage['STCMBackEnd:idTenant'];
		self.enabledOld = '';
		self.userAdmin = '';
		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.RSC225);

		// 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 sessionUser = JSON.parse(JSONuser);
		let idCPG = sessionUser.idCPG;
		let empresa = sessionUser.empresa;
		self.userAdmin= sessionUser.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(idCPG !== '0' && idCPG !== 0) {
			$('#tenantInput').removeClass('d-flex');
			$('#tenantInput').hide();
			$('#idTenant').text(idCPG);
			$('#empresa').prop('disabled', true);
			$('#empresa').val(empresa);
		}

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

		let nav = `
			<div class="d-flex">
				${createSubOptionChangePass(jsonsubopt.pass)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>

			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

		// Botones secundarios
		$('#backLists').addClass('secondary-button');
		$('#btn-pass').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);
				$('#idioma').val(self.userAPI.lenguage);

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

		let parameters = {
			email: self.userAPI.email
		};
		ajaxComunCallWithCallback('getUserAPICountries', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let sizeB = ajaxReturn.result.length;
				for(let i = 0; i < sizeB; i++) {
					self.userCountries.push(ajaxReturn.result[i].country);
				}

				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);
			}
		}, false);

		stcmbackend.administradores.sharedEvents(self);

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

		self.getUserAPI();

		$('#btn-setUser').click(function() {
			self.setUsersAPI();
		});

		$('#btn-pass').click(function() {
			setTimeout(function() {
				self.revelPass();
			}, 500);

			let content = `
				<div class="form-group">
					<label for="pass1" class="fw-500">${pf.const.language.RSC288}</label>
					<div class="input-group new-input-pass-style">
						<input id="pass1" type="password" class="form-control" name="pass1" aria-describedby="btn-users">
						<div class="input-group-append">
							<button id="btn-pass1" type="button" class="btn btn-outline-secondary">
								${stcmbackend.svg.eyeWithoutColor}
							</button>
						</div>
					</div>
				</div>

				<div class="form-group">
					<label for="pass2" class="fw-500">${pf.const.language.RSC289}</label>
					<div class="input-group new-input-pass-style">
						<input id="pass2" type="password" class="form-control" name="pass2" aria-describedby="btn-users">
						<div class="input-group-append">
							<button id="btn-pass2" type="button" class="btn btn-outline-secondary">
								${stcmbackend.svg.eyeWithoutColor}
							</button>
						</div>
					</div>
				</div>

				<script>
					// Pintar texto de label
					changeLabelsColor();
				</script>
			`;

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

			let alertTitle = pf.const.language.RSC287;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, content, objInfo, function() {
				self.changePassword();
			}, function() {});
		});

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

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

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

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

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

	// Mostrar Contraseña
	revelPass() {
		$('#btn-pass1').mouseup(function() {
			$('#pass1').attr('type', 'password');
		});

		$('#btn-pass1').mousedown(function() {
			$('#pass1').attr('type', 'text');
		});

		$('#btn-pass2').mouseup(function() {
			$('#pass2').attr('type', 'password');
		});

		$('#btn-pass2').mousedown(function() {
			$('#pass2').attr('type', 'text');
		});
	},

	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 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 paises permitidos
			if(self.allowedCountries.indexOf(self.countries[i].isocode) == -1 && userRol != 'FullAdmin') {
				continue;
			}

			let countryChecked = false;
			if(self.userCountries.indexOf(self.countries[i].isocode) != -1) {
				countryChecked = true;
			}

			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>
						<span class="d-none">${(countryChecked ? '1' : '0')}</span>
						<div class="custom-control custom-switch">
							<input id="${self.countries[i].isocode}" type="checkbox" class="custom-control-input uSwitch" ${(countryChecked ? 'checked' : '')}>
							<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);
	},

	changePassword() {
		let self = AdministradoresEditarController;

		let pass1 = $('#pass1').val();
		let pass2 = $('#pass2').val();

		if(pass1 == pass2 && pass1 != '') {
			let parameters = {
				email: self.userAPI.email,
				passwordAPI: pass1
			};
			ajaxComunCallWithCallback('resetPasswordAPIUser', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let resetTitle = pf.const.language.RSC71;
					let resetContent = pf.const.language.RSC359;
					pf.utils.showInfoDialog(resetTitle, resetContent);
				}
			});
		} else {
			let alertTitle = pf.const.language.RSC287;
			let alertText = pf.const.language.RSC290;
			pf.utils.showInfoDialog(alertTitle, alertText, pf.const.language.RSC78);
		}
	},

	getUserAPI() {
		let self = this;

		if(self.userAPI.enabled == '1') {
			$('#enabledUser').prop('checked', true);
		}
		self.enabledOld = self.userAPI.enabled;

		// Usuario de App
		if(self.userAPI.appUser != '') {
			$('#appUser').val(self.userAPI.appUser);
			$('#appUser').attr('title', self.userAPI.appUser);
			$('#appUserDelete').show();
		}

		$('#email').val(self.userAPI.email);
		if(self.userAPI.mustResetPass == '1') {
			$('#resetPassword').prop('checked', true);
		}
		$('#name').val(self.userAPI.name);
		$('#pais').val(self.userAPI.country);
		$('#apellido1').val(self.userAPI.apellido1);
		$('#apellido2').val(self.userAPI.apellido2);
		$('#empresa').val(self.userAPI.empresa);
		$('#departamento').val(self.userAPI.departamento);
		$('#role').val(self.userAPI.role);
		if(self.userAPI.idTenant == '0') {
			$('#tenantReq').hide();
			$('#searchTenant').prop('disabled', true);
			$('#tenantPrincipal').prop('checked', true);
		} else {
			$('#tenant').val(self.userAPI.razonSocial);
			$('#idTenant').text(self.userAPI.idTenant);
		}
		$('#customers').val(self.userAPI.razonSocialCliente);
		$('#customers').data('id', self.userAPI.idCliente);
	},

	setUsersAPI() {
		let self = this;

		let formIncomplete = false;
		let activo = ($('#enabledUser').prop('checked') ? '1' : '0');
		let email = self.userAPI.email;
		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 country = $('#pais').val();
		if(country == '') {
			formIncomplete = true;
			$('#pais').addClass('is-invalid');
			$('[for="pais"]').addClass('is-invalid');
		} else {
			$('#pais').removeClass('is-invalid');
			$('[for="pais"]').removeClass('is-invalid');
		}
		let lenguage = $('#idioma').val();
		let role = $('#role').val();
		if(role == '') {
			formIncomplete = true;
			$('#role').addClass('is-invalid');
			$('[for="role"]').addClass('is-invalid');
		} else {
			$('#role').removeClass('is-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,
			enabledOld: self.enabledOld,
			email: email,
			username: name,
			userapellidos: userapellidos,
			userapellidos2: userapellidos2,
			empresa: empresa,
			departamento: departamento,
			lenguage: lenguage,
			role: role,
			countries: countries,
			idTenant: tenant,
			country: $('#pais').val(),
			appUser: $('#appUser').val(),
			userAdmin: self.userAdmin,
			idCliente: $('#customers').data('id')
		};
		ajaxComunCallWithCallback('updateAPIUser', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let updateTitle = pf.const.language.RSC78;
				let updateContent = pf.const.language.RSC106;
				pf.utils.showInfoDialog(updateTitle, updateContent);
				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;
		}
	}
};