let CubosNewController = {
	name: '',
	description: '',
	schemaTableArray: [],
	schemes: '',
	schemesFlag: false,
	tables: '',
	tablesFlag: false,
	relationsArray: [],
	tablesSelectedFlag: false,
	columnsFlag: false,
	fieldsArray: [],
	filtersArray: [],

	reset() {
		let self = this;

		self.name = '';
		self.description = '';
		self.schemaTableArray = [];
		self.schemes = '';
		self.schemesFlag = false;
		self.tables = '';
		self.tablesFlag = false;
		self.relationsArray = [];
		self.tablesSelectedFlag = false;
		self.columnsFlag = false;
		self.fieldsArray = [];
		self.filtersArray = [];
	},

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

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

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

		// Opciones de header
		let jsonsubopt = {
			back: 'backLists',
			save: 'btn-send'
		};

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${createSubOptionBack(jsonsubopt.back)}
		`;

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

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

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

		self.loadLanguage();
		self.applyEvents();

		self.tablesSelection();
		self.relationsSelection();
		self.fieldsSelection();
		self.filtersSelection();

		// Collapse
		addEventArrowTableHeader();

		// Pintar texto de label
		changeLabelsColor();
	},

	loadLanguage() {
		pf.rsc.translateByTag('text');
	},

	applyEvents() {
		let self = this;

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

		// Ocultar cubo de basura
		$('#countryDelete').hide();

		// País
		let countryModal = new TableCountries(0, 'newCubosCountry');
		$('#searchCountry').off().on('click', function() {
			self.requestType = 'country';
			countryModal.setEvents();
		});

		// Limpiar País
		$('#countryDelete').on('click', function() {
			$('#pais').val('');
			$('#countryDelete').hide();
		});

		// Añadir esquema / tabla
		$('#newTable').off().on('click', function() {
			let obj = {
				schema: '',
				table: '',
				principal: 0
			};
			self.schemaTableArray.push(obj);
			self.tablesSelection();
		});

		// Añadir relación
		$('#newRelation').off().on('click', function() {
			let obj = {
				table1: '',
				field1: '',
				relation: 'INNER',
				table2: '',
				field2: '',
				schema1: '',
				schema2: ''
			};
			self.relationsArray.push(obj);
			self.relationsSelection();
		});

		// Añadir campo
		$('#newField').off().on('click', function() {
			let obj = {
				table0: '',
				field0: '',
				type: 'text',
				schema: ''
			};
			self.fieldsArray.push(obj);
			self.fieldsSelection();
		});

		// Añadir filtro
		$('#newFilter').off().on('click', function() {
			let obj = {
				parenthesisOpen: '',
				table4: '',
				field4: '',
				operator: '=',
				value: '',
				parenthesisClose: '',
				conjunction: '',
				ask: '0',
				question: '',
				schema: ''
			};

			let sizeOld = self.filtersArray.length;
			if(self.filtersArray[(sizeOld - 1)].conjunction === '') {
				self.filtersArray[(sizeOld - 1)].conjunction = 'AND';
			}

			self.filtersArray.push(obj);
			self.filtersSelection();
		});

		// Guardar cubo nuevo
		$('#btn-send').click(function() {
			self.name = $('#cubeName').val().trim();
			self.description = $('#cubeDesc').val().trim();

			let checked = true;
			if(self.name == '') {
				$('#cubeName').addClass('is-invalid');
				$('[for="cubeName"]').addClass('is-invalid');
				checked = false;
			} else {
				$('#cubeName').removeClass('is-invalid');
				$('[for="cubeName"]').removeClass('is-invalid');
			}

			if(self.description == '') {
				$('#cubeDesc').addClass('is-invalid');
				$('[for="cubeDesc"]').addClass('is-invalid');
				checked = false;
			} else {
				$('#cubeDesc').removeClass('is-invalid');
				$('[for="cubeDesc"]').removeClass('is-invalid');
			}

			if(checked) {
				self.setBI();
			} else {
				pf.utils.alerts.showCompleteAllFields();
			}
		});

		// Texto de Store procedure
		$('#storeProcedure').blur(function() {
			if($('#storeProcedure').val().trim() != '') {
				$('#storeProcedureText').text(pf.const.language.RSC1269);
			} else {
				$('#storeProcedureText').text('');
			}
		});
	},

	tablesSelection() {
		let self = this;

		let table = `
			<table id="tableSchemaTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1067}">${pf.const.language.RSC1067}</th>
						<th scope="col" title="${pf.const.language.RSC965}">${pf.const.language.RSC965}</th>
						<th scope="col" title="${pf.const.language.RSC1071}">${pf.const.language.RSC1071}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.schemaTableArray.length;
		if(size < 1) {
			let obj = {
				schema: '',
				table: '',
				principal: 0
			};
			self.schemaTableArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let schema = self.schemaTableArray[i].schema;
			let schemaTable = self.schemaTableArray[i].table;
			let disabled = self.schemaTableArray[i].schema == '' ? 'disabled' : '';

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${schema}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="schemaSelect_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1067}" value="${schema}" title="${schema}" disabled>
								<div class="input-group-append">
									<button id="btn-schema_${i}" type="button" class="btn btn-outline-secondary btn-schema" data-toggle="modal" data-target="#modalSchemes">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate tableName p-1">
						<span class="d-none">${schemaTable}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="tableSelect_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC965}" value="${schemaTable}" title="${schemaTable}" disabled>
								<div class="input-group-append">
									<button id="btn-table_${i}" type="button" class="btn btn-outline-secondary btn-table" data-toggle="modal" data-target="#modalTables" ${disabled}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="pl-2">
						<span class="d-none">${(self.schemaTableArray[i].principal == 1 ? '1' : '0')}</span>
						<div class="custom-control custom-switch">
							<input id="def_${i}" type="checkbox" class="custom-control-input uSwitch principalTable" ${(self.schemaTableArray[i].principal == 1 ? 'checked' : '')}>
							<label id="label_${i}" for="def_${i}" class="custom-control-label c-pointer"></label>
						</div>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteSchemaTables">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableSchemaTables = $('#tableSchemaTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '55px', targets: 2},
				{width: '30px', targets: 3}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1067 + '_' + pf.const.language.RSC965,
				className: 'd-none',
				title: pf.const.language.RSC1067 + '_' + pf.const.language.RSC965,
				exportOptions: {
					columns: [0, 1]
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportSchemaTables').off().on('click', function() {
			self.tablesSelection();
			$('#schemaTables .buttons-excel').trigger('click');
		});

		self.tablesSelectionEvents();
	},

	tablesSelectionEvents() {
		let self = this;

		// Modal de esquemas
		$('.btn-schema').off().on('click', function() {
			let index = $(this).attr('id').replace('btn-schema_', '');
			if(self.schemesFlag) {
				$('#tableSchemes').dataTable().fnDestroy();
			} else {
				self.schemesFlag = true;
			}
			self.getBISchemas(index);
		});

		// Modal de tablas
		$('.btn-table').off().on('click', function() {
			let index = $(this).attr('id').replace('btn-table_', '');
			let schema = $('#schemaSelect_' + index).val();
			if(self.tablesFlag) {
				$('#tableTables').dataTable().fnDestroy();
			} else {
				self.tablesFlag = true;
			}
			self.getAllSchemaTables(schema, index);
		});

		// Eliminar registro
		$('.deleteSchemaTables').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.schemaTableArray.splice(index, 1);
			self.tablesSelection();
		});

		// Seleccionar principal
		$('.principalTable').off().on('click', function() {
			let index = $(this).attr('id').replace('def_', '');
			$('.principalTable').prop('checked', false);
			$('#def_' + index).prop('checked', true);
			let size = self.schemaTableArray.length;
			for(let i = 0; i < size; i++) {
				self.schemaTableArray[i].principal = 0;
			}
			self.schemaTableArray[index].principal = 1;
		});
	},

	getBISchemas(index) {
		let self = this;

		ajaxComunCallWithCallback('getBISchemas', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.schemes = ajaxReturn.result;

				// Modal de esquemas
				self.renderSchemes(index);
			}
		});
	},

	renderSchemes(index) {
		let self = this;

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

			<thead class="filtersSchemes">
				<tr>
					<td>connection</td>
					<td>database</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.schemes.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-connection="${self.schemes[i].conection}" data-database="${self.schemes[i].database}">
					<td class="text-truncate" title="${self.schemes[i].conection}">${self.schemes[i].conection}</td>
					<td class="text-truncate" title="${self.schemes[i].database}">${self.schemes[i].database}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableSchemes, 'filtersSchemes');

		$('#tableSchemes tbody').off().on('click', 'tr', function() {
			let schema = $(this).attr('data-database');
			self.schemaTableArray[index].schema = schema;
			self.schemaTableArray[index].table = '';
			self.schemaTableArray[index].principal = 0;
			$('#schemaSelect_' + index).val(schema);
			$('#tableSelect_' + index).val('');
			$('#btn-table_' + index).prop('disabled', false);
			$('#closeSchemes').trigger('click');
		});
	},

	getAllSchemaTables(schema, index) {
		let self = this;

		let parameters = {
			schema: schema
		};
		ajaxComunCallWithCallback('getAllSchemaTables', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.tables = ajaxReturn.result;

				// Modal de tablas
				self.renderTables(index);
			}
		});
	},

	renderTables(index) {
		let self = this;

		let table = `
			<thead>
				<tr>
					<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.RSC1070}">${pf.const.language.RSC1070}</th>
				</tr>
			</thead>

			<thead class="filtersTables">
				<tr>
					<td>name</td>
					<td>description</td>
					<td>rows</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.tables.length;
		for(let i = 0; i < size; i++) {
			let descNumber = self.tables[i].description;
			let description = '';
			if(descNumber != '0') {
				description = pf.const.language['RSC' + descNumber];
			}

			let table_name = '';
			if(self.tables[i].table_name != undefined) {
				table_name = self.tables[i].table_name;
			} else if(self.tables[i].TABLE_NAME != undefined) {
				table_name = self.tables[i].TABLE_NAME;
			}

			let table_rows = '-';
			if(self.tables[i].table_rows != undefined) {
				table_rows = self.tables[i].table_rows;
			} else if(self.tables[i].TABLE_ROWS != undefined) {
				table_rows = self.tables[i].TABLE_ROWS;
			}

			table += `
				<tr id="${table_name}" class="c-pointer" data-table="${table_name}">
					<td class="text-truncate" title="${table_name}">${table_name}</td>
					<td class="text-truncate" title="${description}">${description}</td>
					<td class="text-truncate" title="${table_rows}">${table_rows}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

		let tableTables = $('#tableTables').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: [],
			columnDefs: [
				{width: '60px', targets: 2}
			]
		});

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

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

		// Apply the search
		applyTheSearch(tableTables, 'filtersTables');

		$('#tableTables tbody').off().on('click', 'tr', function() {
			let table = $(this).attr('data-table');

			self.schemaTableArray[index].table = table;
			self.schemaTableArray[index].principal = 0;
			$('#tableSelect_' + index).val(table);
			$('#closeTables').trigger('click');
		});
	},

	relationsSelection() {
		let self = this;

		let table = `
			<table id="tableRelationsTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1073} 1">${pf.const.language.RSC1073} 1</th>
						<th scope="col" title="${pf.const.language.RSC1077}">${pf.const.language.RSC1077}</th>
						<th scope="col" title="${pf.const.language.RSC1078}">${pf.const.language.RSC1078}</th>
						<th scope="col" title="${pf.const.language.RSC1073} 2">${pf.const.language.RSC1073} 2</th>
						<th scope="col" title="${pf.const.language.RSC1077}">${pf.const.language.RSC1077}</th>
						<th scope="col" title="${pf.const.language.RSC1083}">${pf.const.language.RSC1083}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.relationsArray.length;
		if(size < 1) {
			let obj = {
				table1: '',
				field1: '',
				relation: 'INNER',
				table2: '',
				field2: '',
				schema1: '',
				schema2: ''
			};
			self.relationsArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let table1 = self.relationsArray[i].table1;
			let field1 = self.relationsArray[i].field1;
			let table2 = self.relationsArray[i].table2;
			let field2 = self.relationsArray[i].field2;
			let disabled1 = table1 == '' ? 'disabled' : '';
			let disabled2 = table2 == '' ? 'disabled' : '';
			let relation = self.relationsArray[i].relation;
			let schema1 = self.relationsArray[i].schema1;
			let schema2 = self.relationsArray[i].schema2;

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${table1}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="table1_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1073} 1" value="${table1}" data-schema="${schema1}" title="${table1}" disabled>
								<div class="input-group-append">
									<button id="btn-table1_${i}" type="button" class="btn btn-outline-secondary btn-table-selected-rel" data-toggle="modal" data-target="#modalSelectedTables">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${field1}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="field1_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1077}" value="${field1}" title="${field1}" disabled>
								<div class="input-group-append">
									<button id="btn-field1_${i}" type="button" class="btn btn-outline-secondary btn-field-rel" data-toggle="modal" data-target="#modalFields" ${disabled1}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<select id="relations_${i}" class="custom-select relationsSelect">
							<option value="INNER" ${(relation == 'INNER' ? 'selected' : '')}>INNER</option>
							<option value="LEFT" ${(relation == 'LEFT' ? 'selected' : '')}>LEFT</option>
							<option value="RIGTH" ${(relation == 'RIGTH' ? 'selected' : '')}>RIGTH</option>
						</select>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${table2}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="table2_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1073} 2" value="${table2}" data-schema="${schema2}" title="${table2}" disabled>
								<div class="input-group-append">
									<button id="btn-table2_${i}" type="button" class="btn btn-outline-secondary btn-table-selected-rel" data-toggle="modal" data-target="#modalSelectedTables">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${field2}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="field2_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1077}" value="${field2}" title="${field2}" disabled>
								<div class="input-group-append">
									<button id="btn-field2_${i}" type="button" class="btn btn-outline-secondary btn-field-rel" data-toggle="modal" data-target="#modalFields" ${disabled2}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate text-center">
						<span class="c-pointer rowDownRel">
							${stcmbackend.svg.arrowDownShort}
						</span>
						<span class="c-pointer rowUpRel">
							${stcmbackend.svg.arrowUpShort}
						</span>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteRelationsTables">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableRelationsTables = $('#tableRelationsTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '75px', targets: 2},
				{width: '55px', targets: 5},
				{width: '30px', targets: 6}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1072,
				className: 'd-none',
				title: pf.const.language.RSC1072,
				exportOptions: {
					columns: [0, 1, 2, 3, 4],
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 2) {
								dev = $('#relations_' + row).val();
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '').trim();
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportRelationsTables').off().on('click', function() {
			self.relationsSelection();
			$('#relationsTables .buttons-excel').trigger('click');
		});

		self.relationsSelectionEvents();
	},

	relationsSelectionEvents() {
		let self = this;

		// Modal tablas seleccionadas
		$('.btn-table-selected-rel').off().on('click', function() {
			let indexTable = $(this).attr('id');
			let index = '';
			let table = '';
			if(indexTable.indexOf('btn-table1_') !== -1) {
				index = indexTable.replace('btn-table1_', '');
				table = 1;
			} else {
				index = indexTable.replace('btn-table2_', '');
				table = 2;
			}

			if(self.tablesSelectedFlag) {
				$('#tableSelectedTables').dataTable().fnDestroy();
			} else {
				self.tablesSelectedFlag = true;
			}
			self.viewSelectedTables(index, table);
		});

		// Modal columnas
		$('.btn-field-rel').off().on('click', function() {
			let indexField = $(this).attr('id');
			let index = '';
			let field = '';
			let schema = '';
			let table = '';
			if(indexField.indexOf('btn-field1_') !== -1) {
				index = indexField.replace('btn-field1_', '');
				field = 1;
				table = $('#table' + field + '_' + index).val();
				schema = $('#table' + field + '_' + index).attr('data-schema');
			} else {
				index = indexField.replace('btn-field2_', '');
				field = 2;
				table = $('#table' + field + '_' + index).val();
				schema = $('#table' + field + '_' + index).attr('data-schema');
			}

			if(self.columnsFlag) {
				$('#tableFields').dataTable().fnDestroy();
			} else {
				self.columnsFlag = true;
			}
			self.getAllSchemaTablesFields(index, field, schema, table);
		});

		// Select de relaciones
		$('.relationsSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('relations_', '');
			let value = $(this).val();
			self.relationsArray[index].relation = value;
		});

		// Bajar registro
		$('.rowDownRel').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			if(index < (self.relationsArray.length - 1)) {
				let element = self.relationsArray.splice(index, 1);
				let newIndex = parseInt(index) + 1;
				self.relationsArray.splice(newIndex, 0, element[0]);
				self.relationsSelection();
			}
		});

		// Subir registro
		$('.rowUpRel').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			if(index > 0) {
				let element = self.relationsArray.splice(index, 1);
				let newIndex = parseInt(index) -1;
				self.relationsArray.splice(newIndex, 0, element[0]);
				self.relationsSelection();
			}
		});

		// Eliminar relación
		$('.deleteRelationsTables').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.relationsArray.splice(index, 1);
			self.relationsSelection();
		});
	},

	viewSelectedTables(index, tableNum) {
		let self = this;

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

			<thead class="filtersTablesSelected">
				<tr>
					<td>schema</td>
					<td>table</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.schemaTableArray.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="${self.schemaTableArray[i].table}" class="c-pointer" data-schema="${self.schemaTableArray[i].schema}">
					<td class="text-truncate" title="${self.schemaTableArray[i].schema}">
						${self.schemaTableArray[i].schema}
					</td>
					<td class="text-truncate" title="${self.schemaTableArray[i].table}">${self.schemaTableArray[i].table}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableSelectedTables, 'filtersTablesSelected');

		$('#tableSelectedTables tbody').off().on('click', 'tr', function() {
			let table = $(this).attr('id');
			let schema = $(this).attr('data-schema');
			$('#table' + tableNum + '_' + index).val(table);
			$('#table' + tableNum + '_' + index).attr('data-schema', schema);
			$('#field' + tableNum + '_' + index).val('');
			$('#btn-field' + tableNum + '_' + index).prop('disabled', false);

			if(tableNum == 1) {
				self.relationsArray[index].table1 = table;
				self.relationsArray[index].field1 = '';
				self.relationsArray[index].schema1 = schema;
			} else if(tableNum == 2) {
				self.relationsArray[index].table2 = table;
				self.relationsArray[index].field2 = '';
				self.relationsArray[index].schema2 = schema;
			} else if(tableNum == 0) {
				self.fieldsArray[index].table0 = table;
				self.fieldsArray[index].field0 = '';
				self.fieldsArray[index].schema = schema;
			} else {
				self.filtersArray[index].table4 = table;
				self.filtersArray[index].field4 = '';
				self.filtersArray[index].schema = schema;
			}

			$('#closeSelectedTables').trigger('click');
		});
	},

	getAllSchemaTablesFields(index, fieldNum, schema, table) {
		let self = this;

		let parameters = {
			schema: schema,
			table_name: table
		};
		ajaxComunCallWithCallback('getAllSchemaTablesFields', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let fields = ajaxReturn.result;

				// Modal de campos
				self.renderFields(index, fieldNum, fields, schema, table);
			}
		});
	},

	renderFields(index, fieldNum, fields, schema, tableField) {
		let self = this;

		let multipleButton = '';
		if(fieldNum == '0') {
			multipleButton = `
				<button id="selectFields" type="button" class="btn btn-outline-secondary">${pf.const.language.RSC141}</button>
				<button id="checkFiltersRows" type="button" class="btn btn-outline-secondary">${pf.const.language.RSC379}</button>
				<button id="uncheckRows" type="button" class="btn btn-outline-secondary">${pf.const.language.RSC378}</button>
			`;
		}
		$('#buttonsFieldsContainer').html(multipleButton);

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

			<thead class="filtersFields">
				<tr>
					<td>name</td>
					<td>type</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = fields.length;
		for(let i = 0; i < size; i++) {
			let column_name = '';
			if(fields[i].column_name != undefined) {
				column_name = fields[i].column_name;
			} else if(fields[i].COLUMN_NAME != undefined) {
				column_name = fields[i].COLUMN_NAME;
			}

			let data_type = '';
			if(fields[i].data_type != undefined) {
				data_type = fields[i].data_type;
			} else if(fields[i].DATA_TYPE != undefined) {
				data_type = fields[i].DATA_TYPE;
			}

			let checked = '';
			let cursor = 'c-pointer';
			if(fieldNum == '0') {
				cursor = '';
				for(let j = 0; j < self.fieldsArray.length; j++) {
					if(self.fieldsArray[j].field0 === column_name && self.fieldsArray[j].table0 === tableField && self.fieldsArray[j].schema === schema) {
						checked = 'checked';
					}
				}
			}

			table += `
				<tr class="${cursor}" data-name="${column_name}">
					<td class="text-truncate" title="${column_name}">
						${(fieldNum == '0' ? `<input type="checkbox" class="selection" ${checked}>` : '')}
						${column_name}
					</td>
					<td class="text-truncate" title="${data_type}">${data_type}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableFields, 'filtersFields');

		if(fieldNum == '0') {
			// Selección de múltiples campos
			$('#selectFields').off().on('click', function() {
				addLoader();
				$('#closeFields').trigger('click');
				setTimeout(function() {
					tableFields.destroy();
					let fieldsSelected = [];

					$('#tableFields tr').each(function() {
						let cheked = $(this).find('.selection');
						if(cheked.prop('checked')) {
							fieldsSelected.push($(this).data('name'));
						}
					});

					// Control de campos
					let fieldsArrayNew = [];
					for(let i = 0; i < self.fieldsArray.length; i++) {
						if(self.fieldsArray[i].schema !== schema || self.fieldsArray[i].table0 !== tableField) {
							fieldsArrayNew.push(self.fieldsArray[i]);
						} else if(fieldsSelected.indexOf(self.fieldsArray[i].field0) !== -1) {
							fieldsArrayNew.push(self.fieldsArray[i]);
							let index = fieldsSelected.indexOf(self.fieldsArray[i].field0);
							fieldsSelected.splice(index, 1);
						}
					}

					for(let n = 0; n < fieldsSelected.length; n++) {
						let obj = {
							table0: tableField,
							field0: fieldsSelected[n],
							type: 'text',
							schema: schema
						};
						fieldsArrayNew.push(obj);
					}

					self.fieldsArray = fieldsArrayNew;
					removeLoader();
					self.fieldsSelection();
				}, 500);
			});

			// Marcar todo
			$('#checkFiltersRows').off().on('click', function() {
				tableFields.rows({filter: 'applied'}).every(function(rowIdx, tableLoop, rowLoop) {
					let value = tableFields.cell(rowIdx, 0).data();
					value = value.replace('<input type="checkbox" class="selection">', '<input type="checkbox" class="selection" checked>');
					tableFields.cell(rowIdx, 0).data(value);
				}).draw();
			});

			// Desmarcar todo
			$('#uncheckRows').off().on('click', function() {
				tableFields.rows().every(function(rowIdx, tableLoop, rowLoop) {
					let value = tableFields.cell(rowIdx, 0).data();
					value = value.replace(/ checked=""| checked/g, '');
					tableFields.cell(rowIdx, 0).data(value);
				}).draw();
			});
		} else {
			$('#tableFields tbody').off().on('click', 'tr', function() {
				let field = $(this).attr('data-name');

				$('#field' + fieldNum + '_' + index).val(field);

				if(fieldNum == 1) {
					self.relationsArray[index].field1 = field;
				} else if(fieldNum == 2) {
					self.relationsArray[index].field2 = field;
				} else if(fieldNum == 0) {
					self.fieldsArray[index].field0 = field;
				} else {
					self.filtersArray[index].field4 = field;
				}

				$('#closeFields').trigger('click');
			});
		}
	},

	fieldsSelection() {
		let self = this;

		let table = `
			<table id="tableFieldsTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1073} 1">${pf.const.language.RSC1073} 1</th>
						<th scope="col" title="${pf.const.language.RSC1077}">${pf.const.language.RSC1077}</th>
						<th scope="col" title="${pf.const.language.RSC438}">${pf.const.language.RSC438}</th>
						<th scope="col" title="${pf.const.language.RSC1083}">${pf.const.language.RSC1083}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.fieldsArray.length;
		if(size < 1) {
			let obj = {
				table0: '',
				field0: '',
				type: 'text',
				schema: ''
			};
			self.fieldsArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let table0 = self.fieldsArray[i].table0;
			let field0 = self.fieldsArray[i].field0;
			let type = self.fieldsArray[i].type;
			let disabled0 = table0 == '' ? 'disabled' : '';
			let schema = self.fieldsArray[i].schema;

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${table0}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="table0_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1073}" value="${table0}" data-schema="${schema}" title="${table0}" disabled>
								<div class="input-group-append">
									<button id="btn-table0_${i}" type="button" class="btn btn-outline-secondary btn-table-selected-fie" data-toggle="modal" data-target="#modalSelectedTables">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${field0}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="field0_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1077}" value="${field0}" title="${field0}" disabled>
								<div class="input-group-append">
									<button id="btn-field0_${i}" type="button" class="btn btn-outline-secondary btn-field-fie" data-toggle="modal" data-target="#modalFields" ${disabled0}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<select id="fieldType${i}" class="custom-select fieldTypeSelect">
							<option value="text" ${(type == 'text' ? 'selected' : '')}>text</option>
							<option value="boolean" ${(type == 'boolean' ? 'selected' : '')}>boolean</option>
						</select>
					</td>
					<td class="text-truncate text-center">
						<span class="c-pointer rowDownFie">
							${stcmbackend.svg.arrowDownShort}
						</span>
						<span class="c-pointer rowUpFie">
							${stcmbackend.svg.arrowUpShort}
						</span>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteFieldsTables">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableFieldsTables = $('#tableFieldsTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '85px', targets: 2},
				{width: '55px', targets: 3},
				{width: '30px', targets: 4}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1072,
				className: 'd-none',
				title: pf.const.language.RSC1075,
				exportOptions: {
					columns: [0, 1, 2],
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 2) {
								dev = $('#fieldType' + row).val();
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '').trim();
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportFieldsTables').off().on('click', function() {
			self.fieldsSelection();
			$('#fieldsTables .buttons-excel').trigger('click');
		});

		self.fieldsSelectionEvents();
	},

	fieldsSelectionEvents() {
		let self = this;

		// Modal tablas seleccionadas
		$('.btn-table-selected-fie').off().on('click', function() {
			let indexTable = $(this).attr('id');
			let index = indexTable.replace('btn-table0_', '');
			let table = 0;

			if(self.tablesSelectedFlag) {
				$('#tableSelectedTables').dataTable().fnDestroy();
			} else {
				self.tablesSelectedFlag = true;
			}
			self.viewSelectedTables(index, table);
		});

		// Modal columnas
		$('.btn-field-fie').off().on('click', function() {
			let indexField = $(this).attr('id');
			let index = indexField.replace('btn-field0_', '');
			let field = 0;
			let schema = $('#table' + field + '_' + index).attr('data-schema');
			let table = $('#table' + field + '_' + index).val();

			if(self.columnsFlag) {
				$('#tableFields').dataTable().fnDestroy();
			} else {
				self.columnsFlag = true;
			}
			self.getAllSchemaTablesFields(index, field, schema, table);
		});

		// Select de tipo de campo
		$('.fieldTypeSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('fieldType', '');
			let value = $(this).val();
			self.fieldsArray[index].type = value;
		});

		// Bajar registro
		$('.rowDownFie').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			if(index < (self.fieldsArray.length - 1)) {
				let element = self.fieldsArray.splice(index, 1);
				let newIndex = parseInt(index) + 1;
				self.fieldsArray.splice(newIndex, 0, element[0]);
				self.fieldsSelection();
			}
		});

		// Subir registro
		$('.rowUpFie').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			if(index > 0) {
				let element = self.fieldsArray.splice(index, 1);
				let newIndex = parseInt(index) -1;
				self.fieldsArray.splice(newIndex, 0, element[0]);
				self.fieldsSelection();
			}
		});

		// Eliminar campo
		$('.deleteFieldsTables').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.fieldsArray.splice(index, 1);
			self.fieldsSelection();
		});
	},

	filtersSelection() {
		let self = this;

		let table = `
			<table id="tableFiltersTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1079}">${pf.const.language.RSC1079}</th>
						<th scope="col" title="${pf.const.language.RSC1073}">${pf.const.language.RSC1073}</th>
						<th scope="col" title="${pf.const.language.RSC1077}">${pf.const.language.RSC1077}</th>
						<th scope="col" title="${pf.const.language.RSC1080}">${pf.const.language.RSC1080}</th>
						<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
						<th scope="col" title="${pf.const.language.RSC1079}">${pf.const.language.RSC1079}</th>
						<th scope="col" title="${pf.const.language.RSC1081}">${pf.const.language.RSC1081}</th>
						<th scope="col" title="${pf.const.language.RSC1082}">${pf.const.language.RSC1082}</th>
						<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
						<th scope="col" title="${pf.const.language.RSC1083}">${pf.const.language.RSC1083}</th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.filtersArray.length;
		if(size < 1) {
			let obj = {
				parenthesisOpen: '',
				table4: '',
				field4: '',
				operator: '=',
				value: '',
				parenthesisClose: '',
				conjunction: '',
				ask: '0',
				question: '',
				schema: ''
			};
			self.filtersArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let parenthesisOpen = self.filtersArray[i].parenthesisOpen;
			let table4 = self.filtersArray[i].table4;
			let field4 = self.filtersArray[i].field4;
			let disabled4 = table4 == '' ? 'disabled' : '';
			let operator = self.filtersArray[i].operator;
			let value = self.filtersArray[i].value;
			let parenthesisClose = self.filtersArray[i].parenthesisClose;
			let conjunction = self.filtersArray[i].conjunction;
			let ask = self.filtersArray[i].ask;
			let question = self.filtersArray[i].question;
			let schema = self.filtersArray[i].schema;

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<select id="parenthesisOpen${i}" class="custom-select parenthesisOpenSelect">
							<option value="" ${(parenthesisOpen == '' ? 'selected' : '')}></option>
							<option value="(" ${(parenthesisOpen == '(' ? 'selected' : '')}>(</option>
						</select>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${table4}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="table4_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1073}" value="${table4}" data-schema="${schema}" title="${table4}" disabled>
								<div class="input-group-append">
									<button id="btn-table4_${i}" type="button" class="btn btn-outline-secondary btn-table-selected-fil" data-toggle="modal" data-target="#modalSelectedTables">
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${field4}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="field4_${i}" type="text" class="form-control" placeholder="${pf.const.language.RSC1077}" value="${field4}" title="${field4}" disabled>
								<div class="input-group-append">
									<button id="btn-field4_${i}" type="button" class="btn btn-outline-secondary btn-field-fil" data-toggle="modal" data-target="#modalFields" ${disabled4}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate p-1">
						<select id="operator${i}" class="custom-select operatorSelect">
							<option value="=" ${(operator == '=' ? 'selected' : '')}>=</option>
							<option value=">" ${(operator == '>' ? 'selected' : '')}>></option>
							<option value="<" ${(operator == '<' ? 'selected' : '')}><</option>
							<option value=">=" ${(operator == '>=' ? 'selected' : '')}>>=</option>
							<option value="<=" ${(operator == '<=' ? 'selected' : '')}><=</option>
							<option value="<>" ${(operator == '<>' ? 'selected' : '')}><></option>
							<option value="LIKE" ${(operator == 'LIKE' ? 'selected' : '')}>LIKE</option>
						</select>
					</td>
					<td class="text-truncate p-1">
						<span id="value${i}" class="d-none">${value}</span>
						<input id="valueInput${i}" type="text" class="form-control valueInput" value="${value}" title="${value}">
					</td>
					<td class="text-truncate p-1">
						<select id="parenthesisClose${i}" class="custom-select parenthesisCloseSelect">
							<option value="" ${(parenthesisClose == '' ? 'selected' : '')}></option>
							<option value=")" ${(parenthesisClose == ')' ? 'selected' : '')}>)</option>
						</select>
					</td>
					<td class="text-truncate p-1">
						<select id="conjunction${i}" class="custom-select conjunctionSelect">
							<option value="" ${(conjunction == '' ? 'selected' : '')}></option>
							<option value="AND" ${(conjunction == 'AND' ? 'selected' : '')}>AND</option>
							<option value="OR" ${(conjunction == 'OR' ? 'selected' : '')}>OR</option>
						</select>
					</td>
					<td class="text-truncate p-1">
						<select id="ask${i}" class="custom-select askSelect">
							<option value="0" ${(ask == '0' ? 'selected' : '')}>${pf.const.language.RSC121}</option>
							<option value="1" ${(ask == '1' ? 'selected' : '')}>${pf.const.language.RSC120}</option>
						</select>
					</td>
					<td class="text-truncate p-1">
						<span id="question${i}" class="d-none">${question}</span>
						<input id="questionInput${i}" type="text" class="form-control questionInput" value="${question}" title="${question}" disabled>
					</td>
					<td class="text-truncate text-center">
						<span class="c-pointer rowDownFil">
							${stcmbackend.svg.arrowDownShort}
						</span>
						<span class="c-pointer rowUpFil">
							${stcmbackend.svg.arrowUpShort}
						</span>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteFiltersTables">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

		let tableFiltersTables = $('#tableFiltersTables').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '70px', targets: 0},
				{width: '65px', targets: 3},
				{width: '70px', targets: 5},
				{width: '70px', targets: 6},
				{width: '65px', targets: 7},
				{width: '55px', targets: 9},
				{width: '30px', targets: 10}
			],
			ordering: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1072,
				className: 'd-none',
				title: pf.const.language.RSC1076,
				exportOptions: {
					columns: [0, 1, 2, 3, 4, 5, 6, 7, 8],
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 0) {
								dev = $('#parenthesisOpen' + row).val();
							} else if(column === 3) {
								dev = $('#operator' + row).val();
							} else if(column === 5) {
								dev = $('#parenthesisClose' + row).val();
							} else if(column === 6) {
								dev = $('#conjunction' + row).val();
							} else if(column === 7) {
								dev = $('#ask' + row).val();
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '').trim();
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Exportar tabla
		$('#exportFiltersTables').off().on('click', function() {
			self.filtersSelection();
			$('#filtersTables .buttons-excel').trigger('click');
		});

		self.filtersSelectionEvents();
	},

	filtersSelectionEvents() {
		let self = this;

		// Select de apertura de paréntesis
		$('.parenthesisOpenSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('parenthesisOpen', '');
			let value = $(this).val();
			self.filtersArray[index].parenthesisOpen = value;
		});

		// Modal tablas seleccionadas
		$('.btn-table-selected-fil').off().on('click', function() {
			let indexTable = $(this).attr('id');
			let index = indexTable.replace('btn-table4_', '');
			let table = 4;

			if(self.tablesSelectedFlag) {
				$('#tableSelectedTables').dataTable().fnDestroy();
			} else {
				self.tablesSelectedFlag = true;
			}
			self.viewSelectedTables(index, table);
		});

		// Modal columnas
		$('.btn-field-fil').off().on('click', function() {
			let indexField = $(this).attr('id');
			let index = indexField.replace('btn-field4_', '');
			let field = 4;
			let schema = $('#table' + field + '_' + index).attr('data-schema');
			let table = $('#table' + field + '_' + index).val();

			if(self.columnsFlag) {
				$('#tableFields').dataTable().fnDestroy();
			} else {
				self.columnsFlag = true;
			}
			self.getAllSchemaTablesFields(index, field, schema, table);
		});

		// Select de operador
		$('.operatorSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('operator', '');
			let value = $(this).val();
			self.filtersArray[index].operator = value;
		});

		// Input de valor
		$('.valueInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('valueInput', '');
			let value = $(this).val();
			self.filtersArray[index].value = value;
		});

		// Select de cierre de paréntesis
		$('.parenthesisCloseSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('parenthesisClose', '');
			let value = $(this).val();
			self.filtersArray[index].parenthesisClose = value;
		});

		// Select de conjunción
		$('.conjunctionSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('conjunction', '');
			let value = $(this).val();
			self.filtersArray[index].conjunction = value;
		});

		// Select de preguntar
		$('.askSelect').off().on('change', function() {
			let index = $(this).attr('id').replace('ask', '');
			let value = $(this).val();
			self.filtersArray[index].ask = value;
			if(value == 0) {
				$('#questionInput' + index).val('');
				$('#questionInput' + index).prop('disabled', true);
			} else {
				$('#questionInput' + index).prop('disabled', false);
			}
		});

		// Input de pregunta
		$('.questionInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('questionInput', '');
			let value = $(this).val();
			self.filtersArray[index].question = value;
		});

		// Bajar registro
		$('.rowDownFil').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			if(index < (self.filtersArray.length - 1)) {
				let element = self.filtersArray.splice(index, 1);
				let newIndex = parseInt(index) + 1;
				self.filtersArray.splice(newIndex, 0, element[0]);
				self.filtersSelection();
			}
		});

		// Subir registro
		$('.rowUpFil').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			if(index > 0) {
				let element = self.filtersArray.splice(index, 1);
				let newIndex = parseInt(index) -1;
				self.filtersArray.splice(newIndex, 0, element[0]);
				self.filtersSelection();
			}
		});

		// Eliminar filtro
		$('.deleteFiltersTables').off().on('click', function() {
			let index = $(this).parent().parent().attr('data-id').replace('id', '');
			self.filtersArray.splice(index, 1);
			let sizeNew = self.filtersArray.length;
			if(sizeNew > 0) {
				self.filtersArray[(sizeNew - 1)].conjunction = '';
			}
			self.filtersSelection();
		});
	},

	setBI() {
		let self = this;

		// "nombreEsquema.nombreTabla#principal"
		let table_name = [];
		let tabSize = self.schemaTableArray.length;
		for(let i = 0; i < tabSize; i++) {
			if(self.schemaTableArray[i].schema == '' && self.schemaTableArray[i].table == '') {
				continue;
			}
			let stringTable = self.schemaTableArray[i].schema + '.' + self.schemaTableArray[i].table + '#' + self.schemaTableArray[i].principal;
			table_name.push(stringTable);
		}

		// "esquema1.nombreTabla1#nombreCampo1#relacion#esquema2.nombreTabla2#nombreCampo2"
		let bi_relations = [];
		let relSize = self.relationsArray.length;
		for(let i = 0; i < relSize; i++) {
			if(self.relationsArray[i].table1 == '' && self.relationsArray[i].field1 == '' && self.relationsArray[i].table2 == '' && self.relationsArray[i].field2 == '') {
				continue;
			}
			let stringRelation = self.relationsArray[i].schema1 + '.' + self.relationsArray[i].table1 + '#' + self.relationsArray[i].field1 + '#' + self.relationsArray[i].relation + '#' + self.relationsArray[i].schema2 + '.' + self.relationsArray[i].table2 + '#' + self.relationsArray[i].field2;
			bi_relations.push(stringRelation);
		}

		// "nombreTabla.nombreCampo#orden##[text|boolean]"
		let field_name = [];
		let fieSize = self.fieldsArray.length;
		for(let i = 0; i < fieSize; i++) {
			if(self.fieldsArray[i].table0 == '' && self.fieldsArray[i].field0 == '') {
				continue;
			}
			let stringField = self.fieldsArray[i].table0 + '.' + self.fieldsArray[i].field0 + '#' + (i + 1) + '##' + self.fieldsArray[i].type;
			field_name.push(stringField);
		}

		//"orden#(#nombreTabla#nombreCampo#operador#valor#)#conjuncion#preguntar#pregunta"
		let bi_filters = [];
		let filSize = self.filtersArray.length;
		for(let i = 0; i < filSize; i++) {
			if(self.filtersArray[i].table4 == '' && self.filtersArray[i].field4 == '' && self.filtersArray[i].value == '') {
				continue;
			}
			let stringFilter = (i + 1) + '#' + self.filtersArray[i].parenthesisOpen + '#' + self.filtersArray[i].table4 + '#' + self.filtersArray[i].field4 + '#' + self.filtersArray[i].operator + '#' + self.filtersArray[i].value + '#' + self.filtersArray[i].parenthesisClose + '#' + self.filtersArray[i].conjunction + '#' + self.filtersArray[i].ask + '#' + self.filtersArray[i].question;
			bi_filters.push(stringFilter);
		}

		// Límite de registros
		let recordLimit = $('#recordLimit').val();
		if(recordLimit === '') {
			recordLimit = 0;
		}

		let parameters = {
			name: self.name,
			description: self.description,
			sp_initial: $('#storeProcedure').val().trim(),
			table_name: JSON.stringify(table_name),
			field_name: JSON.stringify(field_name),
			bi_relations: JSON.stringify(bi_relations),
			bi_filters: JSON.stringify(bi_filters),
			country: $('#pais').val(),
			limitRows: recordLimit
		};
		ajaxComunCallWithCallback('setBI', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let alertTitle = pf.const.language.RSC1065;
				let alertText = pf.const.language.RSC106;
				let alertBtn = pf.const.language.RSC132;
				pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
					window.location.href = '#!cubos';
				});
			}
		});
	},

	clickEvents(data) {
		$('#pais').val(data.isocode);
		$('#countryDelete').show();
	}
};