let CubosExecuteController = {
	idCube: '',
	name: '',
	fields: [],
	fieldsType: [],
	fieldsBoolean: [],
	data: '',
	preguntas: [],
	general: '',
	cabeceras: [],
	parametros: [],
	toExport: false,

	reset() {
		let self = this;

		self.idCube = '';
		self.name = '';
		self.fields = [];
		self.fieldsType = [];
		self.fieldsBoolean = [];
		self.data = '';
		self.preguntas = [];
		self.general = '';
		self.cabeceras = [];
		self.parametros = [];
		self.toExport = false;
	},

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

		self.idCube = atob(sessionStorage.getItem('idCube'));
		self.name = atob(sessionStorage.getItem('nameCube'));

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

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC1065 + ' - ' + self.name);

		// Añadir titulo de tarjeta
		$('.cubeName').html(pf.const.language.RSC1065 + ' - ' + self.name);

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

		let nav = `
			<div></div>
			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

		addLoader();

		let parameters = {
			id: self.idCube
		};
		ajaxComunCallWithCallback('getBI', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// GENERAL
				self.general = ajaxReturn.result;
				let filtros = ajaxReturn.filters;
				self.preguntas = [];
				let size = filtros.length;
				for(let i = 0; i < size; i++) {
					if(filtros[i].preguntar == '1') {
						self.preguntas.push(filtros[i]);
					}
				}

				if(self.preguntas.length > 0 && !self.toExport) {
					self.setBIFiltrosModal();
					$('#modalPreguntas').modal('toggle');
					$('#modalPreguntas').modal({
						backdrop: 'static',
						keyboard: false
					});
					removeLoader();
				} else {
					if(self.general[0].sp_initial == '') {
						self.getBIExecution();
					} else {
						self.getBI_SP_Execution();
					}
				}
			}
		}, false);

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

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Vover a Cubos
		$('#backLists').on('click', function() {
			window.location.href = '#!cubos';
		});

		$('#closePreguntas').off().on('click', (e) =>{
			e.preventDefault();
			$('#modalPreguntas').on('hidden.bs.modal', ()=> {
				window.location.href = '#!cubos?nocache=' + (new Date()).getTime();
			});
			$('#modalPreguntas').modal('hide');
		});

		// Botón de aceptar
		$('#questions').off().on('click', function() {
			$('#modalPreguntas').modal('toggle');
			self.setBIFiltros();
			removeLoader();
		});

		// Detectar cierre de modal
		$('#modalPreguntas').on('click', function() {
			setTimeout(function() {
				let status = $('#modalPreguntas').css('display');

				if(status == 'none') {
					if(self.general[0].sp_initial == '') {
						self.getBIExecution();
					} else {
						self.getBI_SP_Execution();
					}
				}
			}, 400);
		});
	},

	setBIFiltrosModal() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
					<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
				</tr>
			</thead>

			<thead class="filtersPreguntas">
				<tr>
					<td>pregunta</td>
					<td>valor</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.preguntas.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${self.preguntas[i].pregunta}">${self.preguntas[i].pregunta}</td>
					<td class="text-truncate">
						<input type="text" class="form-control respuesta" value="" data-index="${i}">
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let tablePreguntas = $('#tablePreguntas').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(tablePreguntas, 'filtersPreguntas');

		self.filtrosModalEvents();

		$('#tablePreguntas').on('draw.dt', function() {
			self.filtrosModalEvents();
		});
	},

	filtrosModalEvents() {
		let self = this;

		$('.respuesta').off().on('blur', function() {
			let index = $(this).data('index');
			let value = $(this).val();

			self.preguntas[index].value = value;
		});
	},

	setBIFiltros() {
		let self = this;

		let valuesArray = [];
		let size = self.preguntas.length;
		for(let i = 0; i < size; i++) {
			let values = {
				order: self.preguntas[i].orden,
				table_name: self.preguntas[i].table_name,
				field_name: self.preguntas[i].field_name,
				value: self.preguntas[i].value
			};
			valuesArray.push(values);
		}

		let parameters = {
			id: self.idCube,
			values: JSON.stringify(valuesArray)
		};
		ajaxComunCallWithCallbackOne('setBIFiltros', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(self.general[0].sp_initial == '') {
					console.log('getbiexecution');
					self.getBIExecution();
				} else {
					console.log('getBI_SP_Execution');
					self.getBI_SP_Execution();
				}
			}
		});
	},

	getBI_SP_Execution() {
		let self = this;

		let parameters = {
			id: self.idCube
		};
		ajaxComunCallWithCallbackOne('getBI_SP_Execution', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.getBIExecution();
			}
		}, false);
	},

	getBIExecution() {
		let self = this;

		let token = sessionStorage['STCMBackEnd:token'];
		let reqName = 'getBIExecution';

		// Generador de documento en excel
		if(self.toExport) {values = {
				action: reqName,
				token: token,
				id: self.idCube,
				nameExcel: self.name,
				cabeceras: self.cabeceras,
				parametros: self.parametros
			};

			let generator = new DocumentsGenerator(values);
			generator.start();
			return;
		}

		let parameters = {
			id: self.idCube,
			toExport: self.toExport
		};
		ajaxComunCallWithCallback('getBIExecution', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let fieSize = ajaxReturn.fields.length;
				if(fieSize < 1) {
					self.fields = [];
					self.fieldsType = [];
				} else {
					for(let i = 0; i < fieSize; i++) {
						let fieldsArray = ajaxReturn.fields[i].field_name.split('.');
						self.fields.push(fieldsArray[1]);
						self.cabeceras.push(fieldsArray[1]);
						self.parametros.push(fieldsArray[1]);
						self.fieldsType.push(ajaxReturn.fields[i].field_visualization);

						if(ajaxReturn.fields[i].field_visualization == 'boolean') {
							self.fieldsBoolean.push(fieldsArray[1]);
						}
					}
				}

				if(ajaxReturn.result.length < 1) {
					self.data = [];
				} else {
					self.data = ajaxReturn.result;
				}

				// Tabla de resultados
				self.renderData();

				removeLoader();
			}
		}, false);
	},

	renderData() {
		let self = this;

		let fieSize = self.fields.length;
		let table = `
			<thead>
				<tr>
		`;

		for(let i = 0; i < fieSize; i++) {
			table += `<th scope="col" title="${self.fields[i]}">${self.fields[i]}</th>`;
		}

		table += `
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
		`;

		for(let i = 0; i < fieSize; i++) {
			table += `<td>${self.fields[i]}</td>`;
		}

		table += `
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			table += `<tr id="id${i}">`;

			for(let j = 0; j < fieSize; j++) {
				let value = self.data[i][self.fields[j]];
				if(value == null || value == 'null' || value == undefined || value == 'undefined' || value == '') {
					value = '-';
				}
				if(self.fieldsType[j] == 'boolean') {
					table += `
						<td class="text-center">
							<span class="d-none">${(value == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<input type="checkbox" disabled ${(value == '1' ? 'checked' : '')}>
						</td>
					`;
				} else {
					table += `
						<td class="text-truncate" title="${value}">
							${value}
						</td>
					`;
				}
			}

			table += `
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#registers').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 refresh">`;

			if(self.fieldsBoolean.indexOf(title) != -1) {
				value = `
					<select class="form-control form-control-sm refreshSel">
						<option value="">${pf.const.language.RSC119}</option>
						<option value="${pf.const.language.RSC121}">${pf.const.language.RSC121}</option>
						<option value="${pf.const.language.RSC120}">${pf.const.language.RSC120}</option>
					</select>
				`;
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1065 + ' - ' + self.name,
				className: 'd-none',
				title: pf.const.language.RSC1065 + ' - ' + self.name,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		// Exportar tabla
		$('#export').off().on('click', function() {
			self.toExport = true;

			let parameters = {
				id: self.idCube
			};
			ajaxComunCallWithCallback('getBI', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					// GENERAL
					self.general = ajaxReturn.result;
					let filtros = ajaxReturn.filters;
					self.preguntas = [];
					let size = filtros.length;
					for(let i = 0; i < size; i++) {
						if(filtros[i].preguntar == '1') {
							self.preguntas.push(filtros[i]);
						}
					}

					if(self.preguntas.length > 0 && !self.toExport) {
						self.setBIFiltrosModal();
						$('#modalPreguntas').modal('toggle');
						$('#modalPreguntas').modal({
							backdrop: 'static',
							keyboard: false
						});
					} else {
						if(self.general[0].sp_initial == '') {
							self.getBIExecution();
						} else {
							self.getBI_SP_Execution();
						}
					}
				}
			});
		});
	}
};