let RSCController = {
	user: null,
	language: '',
	data: '',
	languagesList: [],

	reset() {
		let self = this;

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

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

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

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

		// Opciones de header
		let jsonsubopt = {
			new: 'new',
			importLayout: 'import',
			sync: 'synchronize'
		};

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

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

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

		if(ADDRSC) {
			// Nuevo
			$('#new').on('click', function() {
				window.location.href = '#!rsc_new';
			});
		} else {
			$('#new').hide();
		}

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

				// Tablas de resultados
				self.renderData();
				self.renderDataExport();
			}
		});

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

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Importar excel
		$('#import').click(function() {
			$('#inputFile').trigger('click');
		})

		// Detectar fichero subido
		$('#inputFile').change(function(evt) {
			self.uploadFile(evt);
		});

		//
		$('#synchronize').click(function() {
			self.synchronizeRSC();
		});
	},

	renderData() {
		let self = this;

		let language = sessionStorage['STCMBackEnd:lenguage'];

		// Comprobación de array
		if(!Array.isArray(self.data)) {
			self.data = [];
		}

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${language}">${language}</th>
					<th scope="col" title="${pf.const.language.RSC2409}">${pf.const.language.RSC2409}</th>
					<th scope="col" title="${pf.const.language.RSC620}">${pf.const.language.RSC620}</th>
					<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>id</td>
					<td>${language}</td>
					<td>RSCSistema</td>
					<td>RSCAplicacion</td>
					<td>acciones</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let languageRSC = self.data[i][language].replace(/.&lt;\w*&gt;/gi, '\n').replace(/.&lt;\/\w*&gt/gi, '');

			table += `
				<tr id="id-${self.data[i].idRSC}" data-id="${self.data[i].idRSC}" data-app="${self.data[i].app}" data-system="${self.data[i].system}">
					<td class="text-center c-pointer editRow" title="${self.data[i].idRSC}">${self.data[i].idRSC}</td>
					<td class="text-truncate c-pointer editRow" title="${languageRSC}">${languageRSC}</td>
					<td class="pl-0 c-pointer editRow">
						<span class="d-none">${(self.data[i].system == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="sys_${i}" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].system == 1 ? 'checked' : '')} disabled>
							<label for="sys_${i}" class="custom-control-label c-pointer defaultCountry"></label>
						</div>
					</td>
					<td class="pl-0 c-pointer editRow">
						<span class="d-none">${(self.data[i].app == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<div class="custom-control custom-switch">
							<input id="app_${i}" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].app == 1 ? 'checked' : '')} disabled>
							<label for="app_${i}" class="custom-control-label c-pointer defaultCountry"></label>
						</div>
					</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].idRSC}" data-app="${self.data[i].app}" data-system="${self.data[i].system}">
							<p class="dropdown-item editRow">
								${stcmbackend.svg.pencilWithoutColor}
								<span>${pf.const.language.RSC225}</span>
							</p>
						</div>
					</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let dataTable = $('#registersByLanguage').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '40px', targets: 0},
				{width: '100px', targets: 2},
				{width: '100px', targets: 3},
				{width: '60px', orderable: false, targets: 4}
			],
			aaSorting: []
		});

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

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

		self.dataEvents();

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

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

			sessionStorage.setItem('idRSC', btoa(id));
			sessionStorage.setItem('appRSC', btoa(app));
			sessionStorage.setItem('systemRSC', btoa(system));
			window.location.href = '#!rsc_edit';
		});
	},

	renderDataExport() {
		let self = this;

		let excelTitle = pf.const.language.RSC466;

		for(const key in self.data[0]) {
			if(key != 'idRSC' && key != 'app') {
				self.languagesList.push(key);
			}
		}
		sessionStorage.setItem('languagesList', btoa(self.languagesList.join()));

		let table = `
			<thead>
				<tr>
					<th scope="col">ID</th>
					<th scope="col">APP</th>
		`;

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

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

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(self.data[i].system == 0) {
				continue;
			}
			table += `
				<tr id="id-${self.data[i].idRSC}">
					<td class="text-truncate">${self.data[i].idRSC}</td>
					<td class="text-truncate">${self.data[i].app}</td>
			`;

			for(let j = 0; j < self.languagesList.length; j++) {
				table += `<td class="text-truncate">${self.data[i][self.languagesList[j]]}</td>`;
			}

			table += `
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

	uploadFile(evt) {
		let self = this;

		let newRSC = [];
		//let updateRSC = [];

		let selectedFile = evt.target.files[0];
		let reader = new FileReader();
		reader.onload = function(event) {
			let data = event.target.result;
			let workbook = XLSX.read(data, {
				type: 'binary'
			});

			workbook.SheetNames.forEach(function(sheetName) {
				let arrayRSC = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

				let sizeNew = arrayRSC.length;
				for(let i = 0; i < sizeNew; i++) {
					let defaultRSC = 'RSC' + arrayRSC[i].ID;
					let objNew = {};

					if(arrayRSC[i].ID) {
						objNew['rsc'] = arrayRSC[i].ID;
					}

					if(arrayRSC[i].APP || arrayRSC[i].APP == 0) {
						objNew['app'] = arrayRSC[i].APP;
					}

					if(arrayRSC[i].COUNTRY || arrayRSC[i].COUNTRY == 0) {
						objNew['country'] = arrayRSC[i].COUNTRY;
					}

					for(let j = 0; j < self.languagesList.length; j++) {
						if(self.languagesList[j] == 'country') {
							objNew[self.languagesList[j].toLowerCase()] = arrayRSC[i][self.languagesList[j]];
						} else {
							if(arrayRSC[i][self.languagesList[j]]) {
								objNew[self.languagesList[j].toLowerCase()] = arrayRSC[i][self.languagesList[j]];
							} else {
								objNew[self.languagesList[j].toLowerCase()] = defaultRSC;
							}
						}
					}

					newRSC.push(objNew);
				}
			});

			self.importRSC(newRSC);
		};

		/* reader.onerror = function(event) {
			console.error('File could not be read! Code ' + event.target.error.code);
		}; */

		reader.readAsBinaryString(selectedFile);
	},

	importRSC(newRSC) {
		let self = this;

		let parameters = {
			newRSC: JSON.stringify(newRSC),
			list: JSON.stringify(self.languagesList)
		};
		ajaxComunCallWithCallback('importRSC', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC466;
				let successContent = pf.const.language.RSC469;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.reload();
			}
		});
	},

	synchronizeRSC() {
		let idTenant = sessionStorage['STCMBackEnd:idTenant'];

		let parameters = {
			idTenant: idTenant
		};
		ajaxComunCallWithCallback('synchronizeRSC', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC466;
				let successContent = '';
				if(ajaxReturn.result == 'No RSC defined') {
					// No hay nuevos RSC
					successContent = pf.const.language.RSC1267;
					pf.utils.showInfoDialog(successTitle, successContent);
				} else {
					// RSC guardado con éxito
					successContent = pf.const.language.RSC469;
					pf.utils.showInfoDialog(successTitle, successContent);
					window.location.reload();
				}
			}
		});
	}
};