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

	// Guardar datos por segmentación
	countriesNumber: 0,
	segmentationsCountryArray: [],
	segmentationsTables: [],

	reset() {
		let self = this;

		self.surveysTable = null;
		self.segmentationsTable= null;
		self.index = '';
		self.data = [];

		// Guardar datos por segmentación
		self.countriesNumber = 0;
		self.segmentationsCountryArray = [];
		self.segmentationsTables = [];
	},

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

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

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

		// 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: '',
						segmentationArray: [],
						segmentationNameArray: []
					};
					self.segmentationsCountryArray.push(ajaxReturn.result[i].isocode);
					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, 'muestreoDetalladoMAZSeg');

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

	renderPaisesEnabled() {
		let self = this;

		$('#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>
						<th scope="col" title="${pf.const.language.RSC1741}">${pf.const.language.RSC1741}</th>
					</tr>
				</thead>

				<thead class="filtersCountry">
					<tr>
						<td>iso</td>
						<td>pais</td>
						<td>mision</td>
						<td>segmentaciones</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 paises-encuesta-segmentaciones seleccionadas
			if(self.data[i].active === '1' && self.data[i].segmentationNameArray != '' && self.data[i].survey_sid != '') {
				$('#load').prop('disabled', false);
			}

			table += `
				<tr data-index="${i}">
					<td title="${self.data[i].iso}">
						<input type="checkbox" class="select_country" 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>
					<td class="p-1">
						<span class="d-none">${self.data[i].segmentationNameArray}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="segmentations_${i}" type="text" class="form-control" value="${self.data[i].segmentationNameArray}" title="${self.data[i].segmentationNameArray}" disabled>
								<div class="input-group-append" id ="${self.data[i].iso}">
									<button id="btn_segmentations_${i}" type="button" class="btn btn-outline-secondary btn_segmentations" data-toggle="modal" data-target="#modalContainer" data-index="${i}" ${disabled}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
				</tr>
			`;
		}

		// Control paises-encuesta-segmentaciones seleccionadas
		for(let j = 0; j < size; j++) {
			if(self.data[j].active === '1' && (self.data[j].segmentationNameArray == '' || self.data[j].survey_sid == '')) {
				$('#load').prop('disabled', true);
				break;
			}
		}

		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: '120px', targets: 0}
			],
			scrollCollapse: true,
			scroller: false,
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1875,
				className: 'd-none',
				title: pf.const.language.RSC1875,
				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
		$('.select_country').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);
				$('#btn_segmentations_' + index).prop('disabled', false);
				$('#load').prop('disabled', true);
			} else {
				self.data[index].active = '0';
				self.data[index].survey_sid = '';
				self.data[index].survey_title = '';
				self.data[index].segmentationArray = [],
				self.data[index].segmentationNameArray = []
				self.renderPaisesEnabled();
			}
		});

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

		// Abrir modal segmentaciones
		$('.btn_segmentations').click(function() {
			self.index = $(this).data('index');
			let countryCode = $(this).parent().attr('id');

			// Recoge las segmentaciones previamente seleccionadas para cargarlas con la checkbox marcada
			let segmentacionesACargar = $(this).parent().siblings().val();
			let segmentacionesPrevias = segmentacionesACargar.split(',');

			self.segmentationsTable = new TableSegmentations(1, 'muestreoDetalladoMAZSeg', countryCode, segmentacionesPrevias);
			self.segmentationsTable.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();
	},

	clickSegmentation(segmentation) {
		let self = this;

		segmentacionesSeleccionadas = [];
		segmentacionesSeleccionadasDesc = '';

		let size = segmentation.length;
		for(let i = 0; i < size; i++) {
			segmentacionesSeleccionadas.push(segmentation[i].idSegmentacion);
			segmentacionesSeleccionadasDesc += segmentation[i].Descripcion + ',';
		}
		segmentacionesSeleccionadasDesc = segmentacionesSeleccionadasDesc.substring(0, segmentacionesSeleccionadasDesc.length - 1);

		self.data[self.index].segmentacionIdCountry = segmentacionesSeleccionadas;
		self.data[self.index].segmentationNameArray = segmentacionesSeleccionadasDesc;
		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:muesDetMAZSeg'] = btoa(JSON.stringify(self.data));
				window.location.href = '#!muestreodetallado_maz_seg_tabla';
			}
		});
	}
};