let MisionesUrlsController = {
	defaultStyles: null,
	typeColors: null,
	fontSize: null,
	fontName: null,
	isPerf: null,
	colorsHex: [],
	poll: '',
	idPoll: '',
	primaryColor: '',
	secundaryColor: '',
	data: '',
	user: null,
	loadIMG: '',
	numPregPerf: '',
	splitCharacter: '',
	idTenant: '',
	idMission: '',
	project: '',
	stampMision: '',
	dateFormat: '',
	startDate: '',
	endDate: '',
	suffix: '',
	participants: '',
	selectedParticipants: [],
	participantLinks: [],
	tokensArray: [],

	reset() {
		let self = this;
		self.defaultStyles = null;
		self.typeColors = null;
		self.fontSize = null;
		self.fontName = null;
		self.isPerf = null;
		self.colorsHex = [];
		self.poll = '';
		self.idPoll = '';
		self.primaryColor = '';
		self.secundaryColor = '';
		self.data = '';
		self.user = '';
		self.loadIMG = '';
		self.numPregPerf = '';
		self.splitCharacter = '';
		self.idTenant = sessionStorage['STCMBackEnd:idTenant'];
		self.idMission = '';
		self.project = '';
		self.stampMision = '';
		self.dateFormat = '';
		self.suffix = '';
		participants = '';
		selectedParticipants = [];
		tokensArray = [];
	},

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

		// Información de administrador
		self.user = sessionStorage['STCMBackEnd:user'];
		let userA = JSON.parse(self.user);
		let user = userA.email;
		let user_split = user.split('@');
		self.user = user_split[0].replace('.', '_');
		self.dateFormat = userA.formatoFecha;

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

		let jsonsubopt = {};
		let nav = '';
		if (self.suffix === '') {
			$('#page-title').text(pf.const.language.RSC2746);
			jsonsubopt = {
				survey: 'poll',
				user: 'user',
				link: 'generateURLs',
			};
			nav = `
				<div class="d-flex justify-content-end align-items-end row m-0">
					${createSubOptionSurvey(jsonsubopt.survey)}
					${createSubOptionUser(jsonsubopt.user)}
					${createSubOptionGetLinks(jsonsubopt.link)}
				</div>
			`;
		} else if (self.suffix === '-me-sam') {
			// Opciones de header
			jsonsubopt = {
				user: 'user',
				link: 'generateURLs',
			};
			nav = `
				<div class="d-flex justify-content-end align-items-end row m-0">
					${createSubOptionUser(jsonsubopt.user)}
					${createSubOptionGetLinks(jsonsubopt.link)}
				</div>
			`;
		}

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

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

		// Secciones ocultas al cargar
		$('#deleteAll').hide();
		$('#poll').parent().parent().removeClass('col-2');
		$('#poll').parent().parent().removeClass('col-sm-3');

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.primaryColor = config.tenant[0].colorPrimario.replace('#', '');
		self.secundaryColor = config.tenant[0].colorSecundario.replace('#', '');
		self.loadIMG = config.URLEncuestas;
		self.numPregPerf = config.numPregPerfEnMostreo;
		self.splitCharacter = config.splitCharacter;

		// Plantilla por defecto
		ajaxComunCallWithCallback('getPlantillaReportesByDefault', {}, function (ajaxReturn) {
			if (ajaxReturn) {
				self.defaultStyles = ajaxReturn.result[0];

				self.typeColors = self.defaultStyles.rangoColores;

				if (self.typeColors == "1") {
					self.colorsHex[0] = self.defaultStyles.colorInicio;
					self.colorsHex[1] = self.defaultStyles.colorFinal;
				} else {
					self.colorsHex = self.defaultStyles.coloresComponenRango;
				}

				self.fontSize = 16;
				self.fontName = 'Arial';
			}
		});

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

		addEventArrowTableHeader();
	},

	loadLang() {
		pf.rsc.translateByTag('text');
		$('#poll').attr('placeholder', pf.const.language.RSC177);

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

	applyEvents() {
		let self = this;

		// Encuestas
		$('#searchPoll').on('click', function () {
			// Objeto poll
			if (self.poll === '') {
				let JSONuser = sessionStorage['STCMBackEnd:user'];
				let user = JSON.parse(JSONuser);
				let idCliente = user.idCliente;

				// Parámetro de cliente
				let parameters = {
					idCliente: idCliente
				}
				ajaxComunCallWithCallback('getAllSurveysWithMissions', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						self.poll = ajaxReturn.result;
						self.renderPoll(self.poll);
					}
				});
			}
		});

		// Users
		$('#searchUser').off().on('click', function () {
			if (self.participants == '') {
				let parameters = {
					country: '',
					consejero: 1,
					enabled: 1,
					staff: 1
				};
				ajaxComunCallWithCallback('getAllUsers', parameters, function (ajaxReturn) {
					if (ajaxReturn) {
						self.participants = ajaxReturn.result;
						self.renderPool();
					}
				});
			} else {
				if ($.fn.DataTable.isDataTable('#tableUser')) {
					var table = $('#tableUser').DataTable();
					table.destroy();
				}
				self.renderPool();
			}
		});

		// Selección de reportes a generar
		$('#generateURLs').click(function () {
			let parameters = {
				participants: JSON.stringify(self.selectedParticipants),
				idMission: self.idMission
			};
			ajaxComunCallWithCallback('getMissionSurveyLinks', parameters, function (ajaxReturn) {
				if (ajaxReturn) {
					self.participantLinks = ajaxReturn.result;
					if ($.fn.DataTable.isDataTable('#registers')) {
						var table = $('#registers').DataTable();
						table.destroy();
					}
					self.renderParticipants();
				}
			});
		});

		// Fecha de inicio
		$('#startDate' + self.suffix).on('change', function () {
			self.startDate = $('#startDate' + self.suffix).val();
			if (self.startDate > self.endDate) {
				$('#startDate' + self.suffix).val(self.endDate);
				self.startDate = $('#startDate' + self.suffix).val();
			}
		});

		// Fecha de fin
		$('#endDate' + self.suffix).on('change', function () {
			self.endDate = $('#endDate' + self.suffix).val();
			if (self.endDate < self.startDate) {
				$('#endDate' + self.suffix).val(self.startDate);
				self.endDate = $('#endDate' + self.suffix).val();
			}
		});
	},

	renderPoll(poll) {
		let self = this;
		let table = `
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC177}">${pf.const.language.RSC177}</th>
						<th scope="col" title="${pf.const.language.RSC176}">${pf.const.language.RSC176}</th>
						<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
						<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
						<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
						<th scope="col" title="${pf.const.language.RSC549}">${pf.const.language.RSC549}</th>
					</tr>
				</thead>

				<thead class="filtersPoll">
					<tr>
						<td>mision</td>
						<td>proyecto</td>
						<td>active</td>
						<td>startdate</td>
						<td>expires</td>
						<td>country</td>
					</tr>
				</thead>
			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let size = poll.length;
		for (let i = 0; i < size; i++) {
			// Control de países permitidos
			if (poll[i].countries != '' && allowedCountries.indexOf(poll[i].countries) == -1) {
				continue;
			}

			if (poll[i].idmision == '') {
				continue;
			}

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let startDate = '-';
			let startDateOrder = '';
			if (poll[i].startdate != '') {
				// Para ordenación en columna
				startDateOrder = poll[i].startdate.replace(' ', '');

				let dateTimeArrayStart = poll[i].startdate.split(' ');
				let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
				if (self.dateFormat === 'DDMMAAAA') {
					startDate = modifyDateFormat(dateStart);
				} else {
					startDate = dateStart;
				}
			}

			let endDate = '-';
			let endDateOrder = '';
			if (poll[i].expires != '') {
				// Para ordenación en columna
				endDateOrder = poll[i].expires.replace(' ', '');

				let dateTimeArrayEnd = poll[i].expires.split(' ');
				let dateEnd = dateTimeArrayEnd[0].replace(/-/g, '/');
				if (self.dateFormat === 'DDMMAAAA') {
					endDate = modifyDateFormat(dateEnd);
				} else {
					endDate = dateEnd;
				}
			}

			table += `
						<tr id="sid${poll[i].sid}" class="c-pointer" data-perf="${poll[i].perfilacion}" data-mission="${poll[i].idmision}" data-stamp="${poll[i].stampMision}" data-project="${poll[i].idProject}" data-surveyname="${poll[i].surveyls_title}" data-continuing="${poll[i].continuingMission}">
							<td class="text-truncate" title="${poll[i].idmision}">${poll[i].idmision}</td>
							<td class="text-truncate" title="${poll[i].NombreProyecto}">${poll[i].NombreProyecto}</td>
							<td class="text-center">
								<span class="d-none">${(poll[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
								<input type="checkbox" disabled ${(poll[i].active == '1' ? 'checked' : '')}>
							</td>
							<td class="text-truncate" title="${startDate}">
								<span class="d-none">${startDateOrder}</span>
								${startDate}
							</td>
							<td class="text-truncate" title="${endDate}">
								<span class="d-none">${endDateOrder}</span>
								${endDate}
							</td>
							<td class="country text-truncate" title="${poll[i].countries}">${poll[i].countries}</td>
						</tr>
					`;
		}

		table += `
					</tbody>
				`;

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

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

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

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

		let tablePoll = $('#tablePoll').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{ width: '60px', targets: 2 }
			],
			autoWidth: false,
			aaSorting: []
		});

		// Prueba de reparación para Beb
		setTimeout(function () {
			tablePoll.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tablePoll, 'filtersPoll');

		self.pollEvents();

		$('#tablePoll').on('draw.dt', function () {
			self.pollEvents();
		});
	},

	pollEvents() {
		let self = this;
		$('#tablePoll tbody').off().on('click', 'tr', function () {
			self.idPoll = $(this).prop('id').replace('sid', '');
			self.isPerf = $(this).data('perf');
			self.idMission = $(this).data('mission');
			self.stampMision = $(this).data('stamp');
			self.project = $(this).data('project');
			$('#poll').val(self.idMission);
			$('#searchUser').prop('disabled', false);
			$('#closePoll').trigger('click');
		});
	},

	renderPool() {
		let self = this;
		let table = `
			<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="Nombre">Nombre</th>
					<th scope="col" title="E-mail">E-mail</th>
					<th scope="col" title="Rol">Rol</th>
					<th scope="col" title="Perfil">Perfil</th>
				</tr>
			</thead>

			<thead class="filtersPool">
				<tr>
					<td>selector</td>
					<td>name</td>
					<td>email</td>
					<td>role</td>
					<td>profile</td>
				</tr>
			</thead>

			<tbody>
		`;

		let empty = true;
		let size = self.participants.length;
		for (let i = 0; i < size; i++) {
			let participant = self.participants[i];
			if (participant.enabled == 1) {
				empty = false;
				let name = `${participant.nameUser} ${participant.userApellidos} ${participant.userApellidos2}`;
				let checked = self.selectedParticipants.some(p => p === participant.email) ? 'checked' : '';
				table += `
					<tr id="${participant.email}" class="c-pointer check-select">
						<td class="text-center">
							<div class="div-single-selection">
								<input type="checkbox" class="selection" ${checked} data-id="${participant.email}">
							</div>
						</td>
						<td class="text-truncate" title="${name}">${name}</td>
						<td class="text-truncate" title="${participant.email}">${participant.email}</td>
						<td class="text-truncate" title="${participant.role}">${participant.role}</td>
						<td class="text-truncate" title="${participant.profile}">${participant.profile}</td>
					</tr>
				`;
			}
		}

		if (empty) {
			$('#tableUser').removeClass('tRegs');
		} else {
			$('#tableUser').addClass('tRegs')
		}

		table += `
			</tbody>
		`;

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

		// Inject search input
		$('#tableUser .filtersPool td').each(function () {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;
			if (title == 'selector') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}
			$(this).html(value);
		});

		let tableUser = $('#tableUser').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 50,
			columnDefs: [
				{ width: '25px', orderable: false, targets: 0 },
				{ width: '80px', targets: 4 }
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function () {
			tableUser.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableUser, 'filtersPool');

		self.multiSelectTableEvents();

		$('#tableUser').on('draw.dt', function () {
			self.multiSelectTableEvents();
		});
	},

	multiSelectTableEvents() {
		const self = this;

		inputControl();

		// Add selected useers
		$('#addUsers').off().on('click', function () {
			self.selectedParticipants = self.participants
				.filter(participant => self.selectedParticipants.includes(participant.email))
				.map(participant => participant.email);
			$('#generateURLs').prop('disabled', self.selectedParticipants.length === 0);
			$('#userTable').modal('hide');
		});

		// Select via tr
		$('#tableUser tbody').off().on('click', 'tr', function (event) {
			if (!$(event.target).is('input.selection') && !$(event.target).closest('.div-single-selection').length) {
				let checkbox = $(this).find('.selection');
				checkbox.prop('checked', !checkbox.prop('checked')).change();
			}
		});

		// Refresh table model
		$('#tableUser input.selection').off().on('change', function () {
			let checkedComp = $(this).prop('checked');
			let email = $(this).data('id');
			if (checkedComp) {
				self.selectedParticipants.push(email);
			} else {
				self.selectedParticipants = self.selectedParticipants.filter(e => e !== email);
			}
			inputControl();
		});

		// Global check
		$('.globalSelection').off().on('change', function () {
			if ($('.globalSelection').prop('checked')) {
				$('.selection').prop('checked', true).change();;
			} else {
				$('.selection').prop('checked', false).change();;
			}
		});

		// Refresh global check on single check
		function inputControl() {
			if ($('.selection').length == $('.selection:checked').length && $('.selection').length > 0) {
				$('.globalSelection').prop('checked', true);
			} else {
				$('.globalSelection').prop('checked', false);
			}
		}
	},

	renderParticipants() {
		let self = this;

		let excelTitle = pf.const.language.RSC523;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="E-mail">E-mail</th>
					<th scope="col" title="Link">Link</th>
					<th scope="col" title=""></th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>email</td>
					<td>link</td>
					<td>delete</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.participantLinks.length;
		for (let i = 0; i < size; i++) {
			table += `
				<tr id="${self.participantLinks[i].email}">
					<td class="text-truncate" title="${self.participantLinks[i].email}">${self.participantLinks[i].email}</td>
					<td class="text-truncate" title="${self.participantLinks[i].link}">${self.participantLinks[i].link}</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer circle-container deleteParticipant">
							${stcmbackend.svg.trash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		if (size > 0) {
			$('#tableUser').addClass('tRegs')
			$('#deleteAll').show();
			$('#export').prop('disabled', false);
		} else {
			$('#tableUser').removeClass('tRegs');
			$('#deleteAll').hide();
			$('#export').prop('disabled', true);
		}

		$('#registers').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">`;
			if (title === 'delete') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}
			$(this).html(value);
		});

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{ width: '70px', targets: 2 },
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				filename: excelTitle,
				title: null,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

		self.tableEvents();

		$('#registers').on('draw.dt', function () {
			self.tableEvents();
		});
	},

	tableEvents() {
		let self = this;

		// Eliminar objetivo
		$('.deleteParticipant').off().on('click', function () {
			let email = $(this).parent().parent().attr('id');
			self.removeObjectives(email);
		});

		// Eliminar todos los objetivos
		$('#deleteAll').off().on('click', function () {
			self.selectedParticipants = [];
			self.participantLinks = [];
			$('#registers').dataTable().fnDestroy();
			self.renderParticipants();
		});
	},

	removeObjectives(email) {
		let self = this;
		let size = self.selectedParticipants.length;
		for (let i = 0; i < size; i++) {
			if (self.selectedParticipants[i] == email) {
				self.selectedParticipants.splice(i, 1);
				break;
			}
		}

		size = self.participantLinks.length;
		for (let i = 0; i < size; i++) {
			if (self.participantLinks[i].email == email) {
				self.participantLinks.splice(i, 1);
				break;
			}
		}
		$('#registers').dataTable().fnDestroy();
		self.renderParticipants();
	},

};