let ProyectosController = {
	user: null,
	language: '',
	data: '',
	arrayDelMult: [],
	dateFormat: '',

	reset() {
		let self = this;

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

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

		// Información de administrador
		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('.', '_');
		self.dateFormat = user.formatoFecha;

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

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

		// 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');

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));

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

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

		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 = '#!proyectos_new';
		});
	},

	renderData() {
		let self = this;

		let excelTitle = pf.const.language.RSC10;

		let table = `
			<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.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC143}">${pf.const.language.RSC143}</th>
					<th scope="col" title="${pf.const.language.RSC144}">${pf.const.language.RSC144}</th>
					<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
					<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>selector</td>
					<td>name</td>
					<td>pais</td>
					<td>leader</td>
					<td>client</td>
					<td>creationDate</td>
					<td>acciones</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].country != '' && allowedCountries.indexOf(self.data[i].country) == -1) {
				continue;
			}

			// Para ordenación en columna
			let fechaDeAltaOrder = self.data[i].FechaDeAlta.replace(' ', '');

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let dateTime = '';
			let dateTimeArray = self.data[i].FechaDeAlta.split(' ');
			let date = dateTimeArray[0].replace(/-/g, '/');
			if(self.dateFormat === 'DDMMAAAA') {
				dateTime = modifyDateFormat(date);
			} else {
				dateTime = date;
			}

			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].NombreProyecto}">${self.data[i].NombreProyecto}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].country}">${self.data[i].country}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].LiderProyecto}">${self.data[i].LiderProyecto}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].ClienteInterno}">${self.data[i].ClienteInterno}</td>
					<td class="text-truncate c-pointer editRow" title="${dateTime}">
						<span class="d-none">${fechaDeAltaOrder}</span>
						${dateTime}
					</td>
					<td class="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>
		`;

		$('#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">`;

			if(title === 'selector' || title === 'acciones') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '40px', targets: 2},
				{width: '140px', targets: 5},
				{width: '60px', orderable: false, targets: 6}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: excelTitle,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 5) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			order: [[5, 'desc']]
		});

		// 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.dataEvents(dataTable);

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

	dataEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

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

			sessionStorage.setItem('idProject', id);
			window.location.href = '#!proyectos_edit';
		});

		// Borrar proyecto
		$('.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.RSC10;
			let alertText = pf.const.language.RSC384;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteProject(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);
			} else {
				let index = self.arrayDelMult.indexOf(id);
				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.RSC10;
			let alertText = pf.const.language.RSC1693;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteProject();
			}, function() {});
		});
	},

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

		let projects = [];
		if(id !== false) {
			let obj = {
				id: id
			}
			projects.push(obj);
		} else {
			let delSize = self.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				let obj = {
					id: self.arrayDelMult[i]
				}
				projects.push(obj);
			}
			self.arrayDelMult = [];
		}

		let parameters = {
			projects: JSON.stringify(projects)
		};
		ajaxComunCallWithCallback('deleteCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC436;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/proyectos/proyectos.html', 'wrapper', ProyectosController);
			}
		});
	}
};