class TableSurveysWithMission {
	constructor(type = 0, actions) {
		this.type = type;
		this.actionsTable = actions;
		this.data = null;
		this.modality = null;
	}

	setEvents(modality = 'tableModal', admin = null) {
		let self = this;

		clearGeneralModal();

		self.modality = modality;
		if(admin) {
			self.data = admin
			self.renderTable();
		} else if(self.data) {
			self.renderTable();
		} else {
			self.requestData();
		}
	}

	requestData() {
		let self = this;

		clearGeneralModal();

		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.data = ajaxReturn.result;
				self.renderTable();
			}
		});
	}

	renderTable() {
		let self = this;

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

		let table = `
			<table id="${this.modality}" class="table table-hover tr-pointer tRegs">
				<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="filtersUser">
					<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.data.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(self.data[i].countries != '' && allowedCountries.indexOf(self.data[i].countries) == -1) {
				continue;
			}

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

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

				let dateTimeArrayStart = self.data[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.data[i].expires != '') {
				// Para ordenación en columna
				endDateOrder = self.data[i].expires.replace(' ', '');

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

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

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

		if(this.modality == 'tableModal') {
			$('#headerModalTitle').text(pf.const.language.RSC14);
			$('#divTableModal').html(table);
		} else {
			$('#resultTable').html(table);
		}

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

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

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

		let tableUsers = '';
		if(self.modality != 'tableModal') {
			//
		} else {
			tableUsers = $('#' + this.modality).DataTable({
				language: pf.const.language_table,
				scrollY: 300,
				scroller: false,
				paging: true,
				pageLength: 25,
				columnDefs: [
					{width: '70px', targets: 2},
					{width: '70px', targets: 5}
				],
				autoWidth: false,
				aaSorting: []
			});
		}

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

		// Ocultar botones de tabla
		hideTableButtons(this.modality);

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

		if(self.modality != 'tableModal') {
			// Exportar tabla
			$('#exportUsers').off().on('click', function() {
				$('#resultTable .buttons-excel').trigger('click');
			});
		}

		if(self.type === 0) {
			// Detectar click
			$('#' + this.modality + ' tbody').off().on('click', 'tr', function() {
				self.eventsTable($(this).data('id'));
				$('#closeUser').trigger('click');
			});
		} else {
			// Si se necesitase el caso de selección múltiple
		}
	}

	eventsTable(id) {
		let self = this;

		let response = '';
		if(self.type === 0) {
			response = self.data[id];
		} else {
			response = self.members;
		}

		switch(self.actionsTable) {
			case 'muestreoDetalladoMAZ':
				MuestreoDetalladoMAZController.clickSurvey(response);
				break;
			case 'muestreoDetalladoMAZSeg':
				MuestreoDetalladoMAZSegController.clickSurvey(response);
				break;
		}
	}
}