let CumplimientoController = {
	user: null,
	language: '',
	data: '',

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = '';
	},

	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('.', '_');

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

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

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

		let nav = `
			<div class="row mx-0">
				${createSubOptionNew(jsonsubopt.new)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>
		`;

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

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

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

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

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

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Guardar cumplimientos
		$('#save').on('click', function() {
			self.saveWarningsCompliance();
		});

		// Nuevo registro
		$('#new').on('click', function() {
			let obj = {
				disableuserslastwarning: ($('#disableUser').prop('cheked') == true ? 1 : 0),
				id: '',
				numAviso: '',
				textAviso: ''
			};
			self.data.push(obj);
			$('#registers').dataTable().fnDestroy();
			self.renderData();
		});

		ajaxComunCallWithCallback('getAllAvisosDisableUserAuto', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;
				if(self.data.length > 0) {
					$('#disableUser').prop('checked', (self.data[0].disableuserslastwarning == 1 ? true : false));
				}

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

	renderData() {
		let self = this;

		let excelTitle = pf.const.language.RSC28;

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

			<tbody>
		`;

		let size = self.data.length;
		// En caso de que no haya registros
		if(size < 1) {
			let obj = {
				disableuserslastwarning: ($('#disableUser').prop('cheked') == true ? 1 : 0),
				id: '',
				numAviso: '',
				textAviso: ''
			};
			self.data.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${self.data[i].numAviso}">
						<span class="d-none">${self.data[i].numAviso}</span>
						<input type="number" class="form-control warningInput" value="${self.data[i].numAviso}">
					</td>
					<td class="text-truncate notice" title="${self.data[i].textAviso}">
						<span class="d-none">${self.data[i].textAviso}</span>
						<input type="text" class="form-control noticeInput" value="${self.data[i].textAviso}">
					</td>
					<td class="text-truncate text-center align-middle" title="${pf.const.language.RSC226}">
						<span class="c-pointer delete">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			aaSorting: [],
			paging: false,
			autoWidth: false,
			ordering: false,
			columnDefs: [
				{width: '60px', targets: 0},
				{width: '30px', orderable: false, targets: 2}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Exportar tabla
		$('#export').off().on('click', function() {
			$('#resultTable .buttons-excel').trigger('click');
		});

		// Modificar deshabilitación de usuario
		$('#disableUser').off().on('change', function() {
			let disable = ($('#disableUser').prop('checked') == true ? 1 : 0);
			let size = self.data.length;
			for(let i = 0; i < size; i++) {
				self.data[i].disableuserslastwarning = disable;
			}
		});

		// Modificar Nº Aviso
		$('.warningInput').off().on('change', function() {
			let index = $('.warningInput').index(this);
			let value = $(this).val();
			self.data[index].numAviso = value;
		});

		// Restricciones de carácteres por tecla
		$('.noticeInput').off().on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1762);

			return result;
		});

		// Restricciones de carácteres por pegado
		$('.noticeInput').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1762);
		});

		// Modificar Texto Aviso
		$('.noticeInput').on('change', function() {
			let index = $('.noticeInput').index(this);
			let value = $(this).val();
			self.data[index].textAviso = value;
		});

		// Borrar registro
		$('.delete').off().off().on('click', function() {
			let index = $('.delete').index(this);
			self.data.splice(index, 1);
			$('#registers').dataTable().fnDestroy();
			self.renderData();
		});
	},

	saveWarningsCompliance(id) {
		let self = this;

		let avisos = {};
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			avisos[self.data[i].numAviso] = self.data[i].numAviso + '#:#' + self.data[i].textAviso;
		}

		let parameters = {
			avisos: JSON.stringify(avisos),
			disableuserslastwarning: ($('#disableUser').prop('checked') == true ? 1 : 0)
		};
		ajaxComunCallWithCallbackOne('deleteAllAvisosDisableUserAuto', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC28;
				let successContent = pf.const.language.RSC380;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/misiones/cumplimiento.html', 'wrapper', CumplimientoController);
			}
		});
	}
};