let MissionesColaController = {
	data: null,
	token: null,
	dateFormat: '',

	resetData() {
		let self = MissionesColaController;

		self.data = null;
		self.token = sessionStorage['STCMBackEnd:token'];
		self.dateFormat = '';
	},

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

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

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

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

		self.loadLanguage();

		// Obtener cola de misiones
		ajaxComunCallWithCallback('getColaMisionesPendientes', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				self.renderCola();
			}
		});

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	renderCola() {
		let self = this;

		let table = `
			<table id="tableCola" class="table table-hover tRegs tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC176}">${pf.const.language.RSC176}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC326}">${pf.const.language.RSC326}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC171}">${pf.const.language.RSC171}</th>
						<th scope="col" title="${pf.const.language.RSC172}">${pf.const.language.RSC172}</th>
						<th scope="col" title="${pf.const.language.RSC145}">${pf.const.language.RSC145}</th>
						<th scope="col" title="${pf.const.language.RSC961}">${pf.const.language.RSC961}</th>
						<th scope="col" title="${pf.const.language.RSC962}">${pf.const.language.RSC962}</th>
					</tr>
				</thead>

				<thead class="filtersUser">
					<tr>
						<td>NombreProyecto</td>
						<td>pais</td>
						<td>idmision</td>
						<td>descripcion</td>
						<td>fechahorainicio</td>
						<td>fechahorafin</td>
						<td>importe</td>
						<td>inicionotificado</td>
						<td>finnotificado</td>
					</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) {
				continue;
			}

			// Formato de fecha, el servicio devuelve DD/MM/AAAA HH:MM:SS
			let startDate = '';
			let endDate = '';
			let dateTimeArrayStart = self.data[i].fechahorainicio.split(' ');
			let dateTimeArrayEnd = self.data[i].fechahorafin.split(' ');
			let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
			let dateEnd = dateTimeArrayEnd[0].replace(/-/g, '/');
			if(self.dateFormat === 'AAAAMMDD') {
				startDate = modifyDateFormat(dateStart) + ' ' + dateTimeArrayStart[1];
				endDate = modifyDateFormat(dateEnd) + ' ' + dateTimeArrayEnd[1];
			} else {
				startDate = dateStart + ' ' + dateTimeArrayStart[1];
				endDate = dateEnd + ' ' + dateTimeArrayEnd[1];
			}

			table += `
				<tr data-id="${i}">
					<td class="text-truncate projectName c-pointer" data-id="${self.data[i].idProject}" title="${self.data[i].NombreProyecto}">${(self.data[i].NombreProyecto != null ? self.data[i].NombreProyecto : '-')}</td>
					<td class="text-truncate" title="${self.data[i].country}">${(self.data[i].country != null ? self.data[i].country : '-')}</td>
					<td class="text-truncate missionName c-pointer" data-id="${self.data[i].idmision}" title="${self.data[i].idmision}">${(self.data[i].idmision != '' ? self.data[i].idmision : '-')}</td>
					<td class="text-truncate" title="${self.data[i].descripcion}">${(self.data[i].descripcion != '' ? self.data[i].descripcion : '-')}</td>
					<td class="text-truncate" title="${startDate}">${startDate}</td>
					<td class="text-truncate" title="${endDate}">${endDate}</td>
					<td class="text-truncate" title="${self.data[i].importe}">${(self.data[i].importe != '' ? self.data[i].importe : '-')}</td>
					<td class="text-truncate edit-inicionotificado" title="${self.data[i].inicionotificado}" data-id="${i}">
						<div class="custom-control custom-switch">
							<span class="d-none">${(self.data[i].inicionotificado == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input id="inicionotificado" type="checkbox" class="custom-control-input uSwitch" disabled ${(self.data[i].inicionotificado == 1 ? 'checked' : '')}>
							<label for="inicionotificado" class="custom-control-label c-pointer iniNotificadoinput" data-id="${i}"></label>
						</div>
					</td>
					<td class="text-truncate edit-finnotificado" title="${self.data[i].finnotificado}" data-id="${i}">
						<div class="custom-control custom-switch">
							<span class="d-none">${(self.data[i].finnotificado == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input id="finnotificado" type="checkbox" class="custom-control-input uSwitch" disabled ${(self.data[i].finnotificado == 1 ? 'checked' : '')}>
							<label for="finnotificado" class="custom-control-label c-pointer finNotificadoinput" data-id="${i}"></label>
						</div>
					</td>
				</tr>
			`;
		}

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

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

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

			if(title === 'inicionotificado' || title === 'finnotificado') {
				value = optionsSelectAllYesNo();
			}

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

		let tableCola = $('#tableCola').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			columnDefs: [
				{width: '40px', targets: 1},
				{width: '90px', targets: 4},
				{width: '90px', targets: 5},
				{width: '60px', targets: 6},
				{width: '105px', targets: 7},
				{width: '105px', targets: 8}
			],
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC960,
				className: 'btn secondary-button ma-le-5',
				title: pf.const.language.RSC960,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
		});

		$('.dataTables_filter').hide();

		$('#btn-actions').html(tableCola.buttons().container());

		// Dar estilo al boton de excel
		$('.buttons-excel').removeClass('btn-secondary')

		$('.buttons-excel').html(
			stcmbackend.svg.download +
			`<span>${pf.const.language.RSC47}</span>`
		);

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

		$('.iniNotificadoinput').off().on('click', function() {
			let id = $(this).attr('data-id');
			let mision = self.data[id];

			self.updateMisionInicioNotificado(mision);
		});

		$('.finNotificadoinput').off().on('click', function() {
			let id = $(this).attr('data-id');
			let mision = self.data[id];
			self.updateMisionFinNotificado(mision);
		});

		$('.projectName').off().on('click', function() {
			let id = $(this).attr('data-id');
			sessionStorage.setItem('idProject', id);
			window.location.href = '#!proyectos_edit';
		});

		$('.missionName').off().on('click', function() {
			let id = $(this).attr('data-id');
			sessionStorage.setItem('idMission', btoa(id));
			window.location.href = '#!misiones_edit';
		});
	},

	updateMisionInicioNotificado(mision) {
		let self = MissionesColaController;

		let Value = 0;
		(mision.inicionotificado == 0) ? (Value = 1) : (Value = 0);
		let idCPG = getidCPG();

		addLoader();

		let parameters = {
			idProject: mision.idProject,
			mision: mision.idmision,
			Value: Value,
			idTenant: sessionStorage['STCMBackEnd:idTenant'],
			idCPG: idCPG
		};
		ajaxComunCallWithCallback('updateMisionInicioNotificado', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Obtener cola de misiones
				ajaxComunCallWithCallback('getColaMisionesPendientes', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.data = ajaxReturn.result;

						self.renderCola();

						removeLoader();
					}
				}, false);
			}
		}, false);
	},

	updateMisionFinNotificado(mision) {
		let self = MissionesColaController;

		let Value = 0;
		(mision.finnotificado == 0) ? (Value = 1) : (Value = 0);
		let idCPG = getidCPG();

		addLoader();

		let parameters = {
			idProject: mision.idProject,
			mision: mision.idmision,
			Value: Value,
			idTenant: sessionStorage['STCMBackEnd:idTenant'],
			idCPG: idCPG
		};
		ajaxComunCallWithCallback('updateMisionFinNotificado', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Obtener cola de misiones
				ajaxComunCallWithCallback('getColaMisionesPendientes', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.data = ajaxReturn.result;

						self.renderCola();

						removeLoader();
					}
				}, false);
			}
		}, false);
	}
};