let NotificacionesColaController = {
	scheduledData: null,
	cyclicalIntervalsData: null,
	cyclicalData: [],
	removeLoader: {},
	dateFormat: '',

	resetData() {
		let self = this;

		self.scheduledData = null;
		self.cyclicalIntervalsData = null;
		self.cyclicalData = [];
		self.removeLoader = {
			scheduled: false,
			cyclical: false
		};
		self.dateFormat = '';
	},

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

		// Información de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let userA = JSON.parse(JSONuser);
		self.dateFormat = userA.formatoFecha;

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

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

		self.loadLanguage();

		// Notificaciones
		addLoader();
		ajaxComunCallWithCallback('getCMBPNotificationsServiceProgramadasTimer', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.scheduledData = ajaxReturn.result;

				self.renderScheduledCola();

				self.removeLoader.scheduled = true;
				if(self.removeLoader.scheduled && self.removeLoader.cyclical) {
					removeLoader();
				}
			}
		}, false);
		ajaxComunCallWithCallback('getCMBPNotificationsServiceCiclicas', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.cyclicalIntervalsData = ajaxReturn.result;

				if(self.cyclicalIntervalsData.length > 0) {
					self.getCMBPNotificationsServiceCiclicasTimer(0);
				} else {
					removeLoader();
					self.renderCyclicalCola();
				}
			}
		}, false);

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	renderScheduledCola() {
		let self = this;

		let table = `
			<table id="tableScheduledCola" class="table table-hover tRegs tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC431}">${pf.const.language.RSC431}</th>
						<th scope="col" title="${pf.const.language.RSC369}">${pf.const.language.RSC369}</th>
						<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
					</tr>
				</thead>

				<thead class="filtersScheduled">
					<tr>
						<td>pais</td>
						<td>descripcion</td>
						<td>ejecución</td>
						<td>observaciones</td>
						<td>activa</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.scheduledData.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.scheduledData[i].country != '' && allowedCountries.indexOf(self.scheduledData[i].country) == -1) {
				continue;
			}

			// Para ordenación en columna
			let fechaUltimaEjecucionOrderArray = self.scheduledData[i].Aux01.split(' ');
			let fechaUltimaEjecucionOrder = modifyDateFormat(fechaUltimaEjecucionOrderArray[0]).replace(/\//g, '-') + fechaUltimaEjecucionOrderArray[1];

			// Formato de fecha, el servicio devuelve DD/MM/AAAA HH:MM:SS
			let dateTime = '';
			let dateTimeArray = self.scheduledData[i].Aux01.split(' ');
			let date = dateTimeArray[0].replace(/-/g, '/');
			if(self.dateFormat === 'AAAAMMDD') {
				dateTime = modifyDateFormat(date) + ' ' + dateTimeArray[1];
			} else {
				dateTime = date + ' ' + dateTimeArray[1];
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.scheduledData[i].country}">${(self.scheduledData[i].country != '' ? self.scheduledData[i].country : '-')}</td>
					<td class="text-truncate" title="${self.scheduledData[i].Descripcion}">${(self.scheduledData[i].Descripcion != '' ? self.scheduledData[i].Descripcion : '-')}</td>
					<td class="text-truncate" title="${dateTime}">
						<span class="d-none">${fechaUltimaEjecucionOrder}</span>
						${dateTime}
					</td>
					<td class="text-truncate" title="${self.scheduledData[i].Observaciones1}">${(self.scheduledData[i].Observaciones1 != '' ? self.scheduledData[i].Observaciones1 : '-')}</td>
					<td class="text-truncate">
						<div class="custom-control custom-switch" data-index="${i}">
							<span class="d-none">${(self.scheduledData[i].Activa == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input id="scheduled_${i}" type="checkbox" class="custom-control-input scheduled" ${(self.scheduledData[i].Activa == 1 ? 'checked' : '')}>
							<label for="scheduled_${i}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

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

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

			if(title === 'activa') {
				value = optionsSelectAllYesNo();
			}

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

		let tableScheduledCola = $('#tableScheduledCola').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			columnDefs: [
				{width: '60px', targets: 0},
				{width: '140px', targets: 2},
				{width: '60px', targets: 4}
			],
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1836,
				className: 'd-none',
				title: pf.const.language.RSC1836,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 2) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Apply the search
		applyTheSearch(tableScheduledCola, 'filtersScheduled');

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

		self.tableScheduledEvents();

		$('#tableScheduledCola').on('draw.dt', function() {
			self.tableScheduledEvents();
		});
	},

	tableScheduledEvents() {
		let self = this;

		$('.scheduled').off().on('change', function() {
			let value = $(this).prop('checked');
			if(!value) {
				let index = $(this).parent().data('index');

				self.updateCMBPNotifications(self.scheduledData[index]);
			}
		});
	},

	getCMBPNotificationsServiceCiclicasTimer(position) {
		let self = this;

		let parameters = {
			TiempoEntreEjecuciones: self.cyclicalIntervalsData[position].TiempoEntreEjecuciones,
			UnidadDeTiempo: self.cyclicalIntervalsData[position].UnidadDeTiempo
		};
		ajaxComunCallWithCallback('getCMBPNotificationsServiceCiclicasTimer', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.cyclicalData = self.cyclicalData.concat(ajaxReturn.result);

				position++;
				if(position < self.cyclicalIntervalsData.length) {
					self.getCMBPNotificationsServiceCiclicasTimer(position);
				} else {
					self.removeLoader.cyclical = true;
					self.renderCyclicalCola();
					if(self.removeLoader.scheduled && self.removeLoader.cyclical) {
						removeLoader();
					}
				}
			}
		}, false);
	},

	renderCyclicalCola() {
		let self = this;

		let table = `
			<table id="tableCyclicalCola" class="table table-hover tRegs tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC368}">${pf.const.language.RSC368}</th>
						<th scope="col" title="${pf.const.language.RSC369}">${pf.const.language.RSC369}</th>
						<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
					</tr>
				</thead>

				<thead class="filtersCyclical">
					<tr>
						<td>pais</td>
						<td>descripcion</td>
						<td>ejecución</td>
						<td>observaciones</td>
						<td>activa</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.cyclicalData.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.cyclicalData[i].country != '' && allowedCountries.indexOf(self.cyclicalData[i].country) == -1) {
				continue;
			}

			// Para ordenación en columna
			let fechaUltimaEjecucionOrderArray = self.cyclicalData[i].FechaUltimaEjecucion.split(' ');
			let fechaUltimaEjecucionOrder = modifyDateFormat(fechaUltimaEjecucionOrderArray[0]).replace(/\//g, '-') + fechaUltimaEjecucionOrderArray[1];

			// Formato de fecha, el servicio devuelve DD/MM/AAAA HH:MM:SS
			let dateTime = '';
			let dateTimeArray = self.cyclicalData[i].FechaUltimaEjecucion.split(' ');
			let date = dateTimeArray[0].replace(/-/g, '/');
			if(self.dateFormat === 'AAAAMMDD') {
				dateTime = modifyDateFormat(date) + ' ' + dateTimeArray[1];
			} else {
				dateTime = date + ' ' + dateTimeArray[1];
			}

			table += `
				<tr>
					<td class="text-truncate" title="${self.cyclicalData[i].country}">${(self.cyclicalData[i].country != '' ? self.cyclicalData[i].country : '-')}</td>
					<td class="text-truncate" title="${self.cyclicalData[i].Descripcion}">${(self.cyclicalData[i].Descripcion != '' ? self.cyclicalData[i].Descripcion : '-')}</td>
					<td class="text-truncate" title="${dateTime}">
						<span class="d-none">${fechaUltimaEjecucionOrder}</span>
						${dateTime}
					</td>
					<td class="text-truncate" title="${self.cyclicalData[i].Observaciones1}">${(self.cyclicalData[i].Observaciones1 != '' ? self.cyclicalData[i].Observaciones1 : '-')}</td>
					<td class="text-truncate">
						<div class="custom-control custom-switch" data-index="${i}">
							<span class="d-none">${(self.cyclicalData[i].Activa == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input id="cyclical_${i}" type="checkbox" class="custom-control-input cyclical" ${(self.cyclicalData[i].Activa == 1 ? 'checked' : '')}>
							<label for="cyclical_${i}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

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

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

			if(title === 'activa') {
				value = optionsSelectAllYesNo();
			}

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

		let tableCyclicalCola = $('#tableCyclicalCola').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			columnDefs: [
				{width: '60px', targets: 0},
				{width: '140px', targets: 2},
				{width: '60px', targets: 4}
			],
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1837,
				className: 'd-none',
				title: pf.const.language.RSC1837,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 2) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Apply the search
		applyTheSearch(tableCyclicalCola, 'filtersCyclical');

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

		self.tableCyclicalEvents();

		$('#tableCyclicalCola').on('draw.dt', function() {
			self.tableCyclicalEvents();
		});
	},

	tableCyclicalEvents() {
		let self = this;

		$('.cyclical').off().on('change', function() {
			let value = $(this).prop('checked');
			if(!value) {
				let index = $(this).parent().data('index');

				self.updateCMBPNotifications(self.cyclicalData[index]);
			}
		});
	},

	updateCMBPNotifications(notification) {
		let user = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let userMod = user.email;

		let parameters = {
			fileSend: false,
			id: notification.id,
			Descripcion: notification.Descripcion,
			TipoNotificacion: notification.TipoNotificacion,
			TiempoEntreEjecuciones: notification.TiempoEntreEjecuciones,
			UnidadDeTiempo: notification.UnidadDeTiempo,
			FechaHoraEjecucionUnica: notification.FechaHoraEjecucionUnica,
			Activa: '0',
			EstiloNotificacion: notification.EstiloNotificacion,
			UsuarioQueNotifica: notification.UsuarioQueNotifica,
			DescUsuarioQueNotifica: notification.DescUsuarioQueNotifica,
			UsuarioANotificar: notification.UsuarioANotificar,
			DescUsuarioANotificar: notification.DescUsuarioANotificar,
			GrupoANotificar: notification.GrupoANotificar,
			DescGrupoANotificar: notification.DescGrupoANotificar,
			ListaANotificar: notification.ListaANotificar,
			DescListaANotificar: notification.DescListaANotificar,
			MotivoNotificacion: notification.MotivoNotificacion,
			ArchivoANotificar: notification.ArchivoANotificar,
			TipoArchivoANotificar: notification.TipoArchivoANotificar,
			MensajeANotificar: notification.MensajeANotificar,
			EncuestaANotificar: notification.EncuestaANotificar,
			DescEncuestaANotificar: notification.DescEncuestaANotificar,
			UsuarioUltimaModificacion: userMod,
			FechaUltimaModificacion: notification.FechaUltimaModificacion,
			FechaUltimaEjecucion: notification.FechaUltimaEjecucion,
			Observaciones1: notification.Observaciones1,
			Observaciones2: notification.Observaciones2,
			Aux01: notification.Aux01,
			Aux02: notification.Aux02,
			Aux03: notification.Aux03,
			Aux04: notification.Aux04,
			Aux05: notification.Aux05,
			NumVecesCiclica: notification.NumVecesCiclica,
			country: notification.country
		};
		ajaxComunCallWithCallbackOne('updateCMBPNotifications', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				if(resp.status === 'OK') {
					location.reload();
				} else {
					let errorTitle = pf.const.language.RSC61;
					let errorContent = resp.result;
					if(resp.resp == 'image') {
						errorContent = pf.const.language.RSC477;
					}
					pf.utils.showInfoDialog(errorTitle, errorContent);
					if(resp.result == 'Not authorized') {
						pf.ajax.setWindowLocationIndex();
					}
				}
			}
		});
	}
};