let PlantillasReportesController = {
	user: null,
	language: '',
	data: '',
	arrayDelMult: [],
	defaultTemplate: '',

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = '';
		self.arrayDelMult = [];
		self.defaultTemplate = '';
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');

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

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

		// Opciones de header
		let jsonsubopt = {
			new: 'new'
		};

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

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

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!plantillas_reportes_new';
		});
	},

	getPlantillasReportes() {
		let self = this;

		ajaxComunCallWithCallback('getPlantillasReportes', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				// Tabla de resultados
				self.renderData();
			}
		});
	},

	renderData() {
		let self = this;

		let table = `
			<table id="registers" class="table table-hover">
				<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="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC2352}">${pf.const.language.RSC2352}</th>
						<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						<td>selector</td>
						<td>nombre</td>
						<td>descripcion</td>
						<td>default</td>
						<td>acciones</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(self.data[i].default == 1) {
				self.defaultTemplate = self.data[i].id;
			}

			table += `
				<tr data-id="${self.data[i].id}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${self.data[i].id}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].nombre}">${self.data[i].nombre}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].descripcion}">${self.data[i].descripcion}</td>
					<td class="pl-0">
						<span class="d-none">${(self.data[i].default == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="def_${i}" type="checkbox" class="custom-control-input uSwitch"${(self.data[i].default == 1 ? ' checked' : '')} data-id="${self.data[i].id}">
							<label for="def_${i}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
					<td class="text-truncate text-center">
						<div id="dropdownActions${i}" class="div-dd-actions c-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							${stcmbackend.svg.threeDotsVertical18}
						</div>

						<div class="dropdown-menu dropdown-menu-right shadow menu-actions" aria-labelledby="dropdownActions${i}" data-id="${self.data[i].id}">
							<p class="dropdown-item editRow">
								${stcmbackend.svg.pencilWithoutColor}
								<span>${pf.const.language.RSC225}</span>
							</p>
							<p class="dropdown-item deleteRow">
								${stcmbackend.svg.trashWithoutColor}
								<span>${pf.const.language.RSC95}</span>
							</p>
						</div>
					</td>
				</tr>
			`;
		}

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

		$('#resultTable').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 == 'selector' || title == 'acciones') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			} else if(title == 'default') {
				value = optionsSelectAllYesNo();
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '95px', targets: 3},
				{width: '60px', orderable: false, targets: 4}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2347,
				className: 'd-none',
				title: pf.const.language.RSC2347,
				exportOptions: {
					columns: [1, 2, 3]
				},
				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(dataTable);

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

	tableEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

		// Editar plantilla
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			sessionStorage.setItem('idPlantillaReporte', btoa(id));
			window.location.href = '#!plantillas_reportes_edit';
		});

		// Cambiar plantilla por defecto
		$('.uSwitch').off().on('change', function() {
			$('.uSwitch').prop('checked', false);
			$(this).prop('checked', true);

			let id = $(this).data('id');
			if(id != self.defaultTemplate) {
				let parameters = {
					id: id
				};
				ajaxComunCallWithCallback('setPlantillaReportesDefault', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.getPlantillasReportes();
					}
				}, false);
			}
		});

		// Borrar plantilla
		$('.deleteRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2347;
			let alertText = pf.const.language.RSC2083;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deletePlantillaReportes(id);
			}, function() {});
		});

		// Array de eliminado múltiple
		$('.deleteSelection').off().on('change', function() {
			let value = $(this).prop('checked');
			let id = $(this).parent().data('id');

			if(value) {
				self.arrayDelMult.push(id.toString());
			} else {
				let index = self.arrayDelMult.indexOf(id.toString());
				self.arrayDelMult.splice(index, 1);
			}

			// Eventos de los inputs individuales
			deleteSelectionInputActions(self.arrayDelMult);
		});

		// Función de borrado múltiple
		$('#multSelecDelete').off().on('click', function() {
			// Aviso de borrado múltiple
			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2347;
			let alertText = pf.const.language.RSC2082;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deletePlantillaReportes();
			}, function() {});
		});
	},

	deletePlantillaReportes(id = false) {
		let self = this;

		let defaultTemplateControl = false;

		let plantillas = [];
		if(id !== false) {
			if(id == self.defaultTemplate || id == '00000000000000') {
				defaultTemplateControl = true;
			} else {
				let obj = {
					id: id
				}
				plantillas.push(obj);
			}
		} else {
			if(self.arrayDelMult.includes(self.defaultTemplate) || self.arrayDelMult.includes('00000000000000')) {
				defaultTemplateControl = true;
			} else {
				let delSize = self.arrayDelMult.length;
				for(let i = 0; i < delSize; i++) {
					let obj = {
						id: self.arrayDelMult[i]
					}
					plantillas.push(obj);
				}
				self.arrayDelMult = [];
			}
		}

		if(defaultTemplateControl) {
			let successTitle = pf.const.language.RSC2347;
			let successContent = pf.const.language.RSC2425;
			pf.utils.showInfoDialog(successTitle, successContent);

			return false;
		}

		let parameters = {
			plantillas: JSON.stringify(plantillas)
		};
		ajaxComunCallWithCallbackOne('deletePlantillaReportes', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2347;
				let successContent = pf.const.language.RSC2084;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/analytics/plantillas_reportes.html', 'wrapper', PlantillasReportesController);
			}
		});
	}
};