let MuestreoDetalladoComparativoController = {
	index: '',
	data: [],
	selectedSurveys: [],
	surveys: '',
	dateFormat: '',

	reset() {
		let self = this;

		self.index = '';
		self.data = [];
		self.selectedSurveys = [];
		self.surveys = '';
		self.dateFormat = '';
	},

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

		// 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.RSC2361);

		// Opciones de header
		let jsonsubopt = {
			refresh: {
				id: 'load',
				disabled: true
			}
		};

		let nav = `
			${createSubOptionRefresh(jsonsubopt.refresh.id, jsonsubopt.refresh.disabled)}
		`;

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

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

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

		ajaxComunCallWithCallback('getPaisesEnabled', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let size = ajaxReturn.result.length;
				for(let i = 0; i < size; i++) {
					let obj = {
						iso: ajaxReturn.result[i].isocode,
						country: ajaxReturn.result[i].descripcion,
						active: '0',
						survey_sid: '',
						survey_title: ''
					};

					self.data.push(obj);
				}

				self.renderPaisesEnabled();
			}
		});

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Cargar muestreo
		$('#load').off().on('click', function() {
			// Comprobación de la integridad de las encuestas
			self.getIfSurveysAreEquals();
		});
	},

	renderPaisesEnabled() {
		let self = this;

		// El botón de cargar inicialmente está desactivado
		$('#load').prop('disabled', true);

		let table = `
			<table id="tableCountries" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC177}">${pf.const.language.RSC177}</th>
					</tr>
				</thead>

				<thead class="filtersCountry">
					<tr>
						<td>iso</td>
						<td>pais</td>
						<td>mision</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let checked = '';
			let disabled = 'disabled';
			if(self.data[i].active === '1') {
				checked = 'checked';
				disabled = '';

				// Control de si hay alguna selección país-encuesta para activar el botón de carga
				$('#load').prop('disabled', false);
			}

			table += `
				<tr data-index="${i}">
					<td title="${self.data[i].iso}">
						<input type="checkbox" class="selection" data-index="${i}" ${checked}>
						${self.data[i].iso}
					</td>
					<td class="text-truncate desc" title="${self.data[i].country}">
						${self.data[i].country}
					</td>
					<td class="p-1">
						<span class="d-none">${self.data[i].survey_title}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="survey_${i}" type="text" class="form-control" value="${self.data[i].survey_title}" title="${self.data[i].survey_title}" disabled>
								<div class="input-group-append">
									<button id="btn_survey_${i}" type="button" class="btn btn-outline-secondary btn_survey" data-toggle="modal" data-target="#surveyTable" data-index="${i}" ${disabled}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
				</tr>
			`;
		}

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

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

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

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

		let tableCountries = $('#tableCountries').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			columnDefs: [
				{width: '60px', targets: 0}
			],
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1797,
				className: 'd-none',
				title: pf.const.language.RSC1797,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
		});

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

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

		// Apply the search
		applyTheSearch(tableCountries, 'filtersCountry');

		// Eventos
		self.applyEventsTable();
		$('#tableCountries').on('draw.dt', function() {
			self.applyEventsTable();
		});
	},

	applyEventsTable() {
		let self = this;

		// Activar país por checbox
		$('.selection').off().on('change', function() {
			let checked = $(this).prop('checked');
			let index = $(this).data('index');

			if(checked) {
				self.selectedSurveys = [];
				self.index = '';
				for(let i = 0; i < self.data.length; i++) {
					self.data[i].active = '0';
					self.data[i].survey_sid = '';
					self.data[i].survey_title = '';
				}

				$('.selectionSurvey').prop('checked', false)
				$('.selection').prop('checked', false);
				$('.btn_survey').prop('disabled', true);
				$('[id*="survey_"]').val('');
				$('.selection[data-index=' + index + ']').prop('checked', true);

				self.data[index].active = '1';
				$('#btn_survey_' + index).prop('disabled', false);
			} else {
				self.data[index].active = '0';
				self.data[index].survey_sid = '';
				self.data[index].survey_title = '';
				self.renderPaisesEnabled();
			}
		});

		// Abrir modal encuestas
		$('.btn_survey').click(function() {
			self.index = $(this).data('index');

			if(self.surveys === '') {
				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.surveys = ajaxReturn.result;

						self.renderSurveys();
					}
				});
			} else {
				$('#surveyTable').modal('show', true);
			}
		});
	},

	renderSurveys() {
		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="filters">
				<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 = self.surveys.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.surveys[i].countries != '' && allowedCountries.indexOf(self.surveys[i].countries) == -1) {
				continue;
			}

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

			let checked = '';
			for(let j = 0; j < self.selectedSurveys.length; j++) {
				if(self.selectedSurveys[j].sid == self.surveys[i].sid) {
					checked = 'checked';
				}
			}

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

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

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

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

			table += `
				<tr id="sid-${self.surveys[i].sid}" class="c-pointer" data-id="${i}" data-sid="${self.surveys[i].sid}">
					<td class="text-truncate" title="${self.surveys[i].idmision}">
						<input type="checkbox" class="selectionSurvey" ${checked}>
						${self.surveys[i].idmision}
					</td>
					<td class="text-truncate" title="${self.surveys[i].NombreProyecto}">${self.surveys[i].NombreProyecto}</td>
					<td class="text-center">
						<span class="d-none">${(self.surveys[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveys[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="${self.surveys[i].countries}">${self.surveys[i].countries}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filters');

		self.eventsSurveys();

		$('#tableSurvey').on('draw.dt', function() {
			self.eventsSurveys();
		});
	},

	eventsSurveys() {
		let self = this;

		// Seleccionar encuesta por tr
		$('#tableSurvey tbody tr').off().on('click', function() {
			let index = $(this).data('id');
			let id = $(this).data('sid');
			let selSurSize = self.selectedSurveys.length;
			let checked = $(this).find('.selectionSurvey').prop('checked');

			if(!checked) {
				$(this).find('.selectionSurvey').prop('checked', true);

				if(self.surveys[index].active != '1') {
					let alertTitle = pf.const.language.RSC398;
					let alertText = pf.const.language.RSC1365;
					pf.utils.showInfoDialog(alertTitle, alertText);
					$(this).find('.selectionSurvey').prop('checked', false);
					return false;
				}

				self.selectedSurveys.push(self.surveys[index]);
			} else {
				$(this).find('.selectionSurvey').prop('checked', false);
				for(let i = 0; i < selSurSize; i++) {
					if(self.selectedSurveys[i].sid == id) {
						self.selectedSurveys.splice(i, 1);
						break;
					}
				}
			}
		});

		// Seleccionar encuesta por checbox
		$('.selectionSurvey').off().on('click', function() {
			let checked = $(this).prop('checked');

			if(checked) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}
		});

		// Aceptar encuestas
		$('#selectSurveys').on('click', function() {
			$('#surveyClose').trigger('click');

			if(self.selectedSurveys.length > 0) {
				var surveys_name = '';
				var surveys_id = '';
				for(var i = 0; i < self.selectedSurveys.length; ++i) {
					if(i > 0) {
						surveys_name += ',';
						surveys_id += ',';
					}
					surveys_name += self.selectedSurveys[i].surveyls_title;
					surveys_id += self.selectedSurveys[i].sid;
				}
				self.data[self.index].survey_sid = surveys_id;
				self.data[self.index].survey_title = surveys_name;
				self.renderPaisesEnabled();
			} else {
				$('#inclusiveContainer').hide();
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');
				$('#surveyProfiling').val('');
			}
		});
	},

	getIfSurveysAreEquals() {
		let self = this;

		let surveys = '';
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(self.data[i].active === '1') {
				if(surveys === '') {
					surveys = self.data[i].survey_sid;
				} else if(self.data[i].survey_sid !== '') {
					surveys += ',' + self.data[i].survey_sid;
				}
			}
		}

		let parameters = {
			survey: surveys
		};
		ajaxComunCallWithCallback('getIfSurveysAreEquals', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				sessionStorage['STCMBackEnd:muesDetComparativo'] = btoa(JSON.stringify(self.data[self.index]));
				window.location.href = '#!muestreodetalladocomparativo_tabla';
			}
		});
	}
};