let MuestreoDetalladoMAZController = {
	surveysTable: null,
	index: '',
	data: [],

	reset() {
		let self = this;

		self.surveysTable = null;
		self.index = '';
		self.data = [];
	},

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

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

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

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

	applyEvents() {
		let self = this;

		self.surveysTable = new TableSurveysWithMission(0, 'muestreoDetalladoMAZ');

		// 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="#modalContainer" 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.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');
			self.surveysTable.setEvents('tableModal');
		});
	},

	clickSurvey(survey) {
		let self = this;

		self.data[self.index].survey_sid = survey.sid;
		self.data[self.index].survey_title = survey.surveyls_title;
		self.renderPaisesEnabled();
	},

	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:muesDetMAZ'] = btoa(JSON.stringify(self.data));
				window.location.href = '#!muestreodetallado_maz_tabla';
			}
		});
	}
};