let ItemsController = {
	data: '',
	arrayDelMult: [],
	dataExcelHead: [],
	dataExcelBody: [],

	reset() {
		let self = this;

		self.data = '';
		self.arrayDelMult = [];
		self.dataExcelHead = [];
		self.dataExcelBody = [];
	},

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

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

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

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

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

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

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

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

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

				self.renderData();
			}
		});

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

		// Collapse
		addEventArrowTableHeader();
	},

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

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('.importTitle').attr('title', pf.const.language.RSC316);
		$('#AutoFillIncompletes').attr('title', pf.const.language.RSC2593);
		$('.deleteMultTitle').attr('title', pf.const.language.RSC95);
	},

	applyEvents() {
		let self = this;

		// Rellenar incompletos
		$('#AutoFillIncompletes').on('click', function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC141
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2370;
			let alertText = pf.const.language.RSC2594;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				ajaxComunCallWithCallback('getItemUnknownInfoGS1Massive', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						let successTitle = pf.const.language.RSC2370;
						let successContent = pf.const.language.RSC2595;
						pf.utils.showInfoDialog(successTitle, successContent);
						loadHTML('inc/items/items.html', 'wrapper', ItemsController);
					}
				});
			}, function() {});
		});

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

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

		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!items_new';
		});
	},

	renderData() {
		let self = this;

		$('#resultTable').show();

		// Creación de cabeceras para el excel
		self.dataExcelHead = ['idItem', 'barcode', 'nombre', 'descripcion', 'categoria', 'subcategoria', 'segmento', 'subsegmento', 'ocasiones', 'fabricante', 'marca', 'submarca', 'sabor', 'empaque', 'contenido', 'unidadMedida', 'rangoContenido', 'imgFolder', 'fichaGS1Completa', 'pendienteRevision', 'comercios'];

		// Array de registros
		self.dataExcelBody = [];

		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">idItem</th>
					<th scope="col" title="${pf.const.language.RSC1674}">${pf.const.language.RSC1674}</th>
					<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.RSC1822}">${pf.const.language.RSC1822}</th>
					<th scope="col">${pf.const.language.RSC2371}</th>
					<th scope="col">${pf.const.language.RSC2133}</th>
					<th scope="col">${pf.const.language.RSC2372}</th>
					<th scope="col">${pf.const.language.RSC2373}</th>
					<th scope="col">${pf.const.language.RSC1422}</th>
					<th scope="col" title="${pf.const.language.RSC2374}">${pf.const.language.RSC2374}</th>
					<th scope="col">${pf.const.language.RSC2375}</th>
					<th scope="col">${pf.const.language.RSC2376}</th>
					<th scope="col">${pf.const.language.RSC2377}</th>
					<th scope="col" title="${pf.const.language.RSC2378}">${pf.const.language.RSC2378}</th>
					<th scope="col" title="${pf.const.language.RSC1048}">${pf.const.language.RSC1048}</th>
					<th scope="col">${pf.const.language.RSC2380}</th>
					<th scope="col">imgFolder</th>
					<th scope="col">${pf.const.language.RSC2414}</th>
					<th scope="col">${pf.const.language.RSC2415}</th>
					<th scope="col">${pf.const.language.RSC2473}</th>
					<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>selector</td>
					<td class="d-none">idItem</td>
					<td>barcode</td>
					<td>nombre</td>
					<td>descripcion</td>
					<td>categoria</td>
					<td class="d-none">subcategoria</td>
					<td class="d-none">segmento</td>
					<td class="d-none">subsegmento</td>
					<td class="d-none">ocasiones</td>
					<td class="d-none">fabricante</td>
					<td>marca</td>
					<td class="d-none">submarca</td>
					<td class="d-none">sabor</td>
					<td class="d-none">empaque</td>
					<td>contenido</td>
					<td>unidadMedida</td>
					<td class="d-none">rangoContenido</td>
					<td class="d-none">imgFolder</td>
					<td class="d-none">fichaGS1Completa</td>
					<td class="d-none">pendienteRevision</td>
					<td class="d-none">id_tiendas</td>
					<td>acciones</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Creación de registros para excel
			let dataExcelBodyRow = [];
			let headSize = self.dataExcelHead.length;
			for(let j = 0; j < headSize; j++) {
				dataExcelBodyRow.push(self.data[i][self.dataExcelHead[j]]);
			}
			self.dataExcelBody.push(dataExcelBodyRow);

			table += `
				<tr data-id="${self.data[i].idItem}">
					<td class="text-center">
						<div class="div-single-selection" data-id="${self.data[i].idItem}">
							<input type="checkbox" class="deleteSelection">
						</div>
					</td>
					<td class="">${self.data[i].idItem}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].barcode}">${'\0' + self.data[i].barcode}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].nombre}">${self.data[i].nombre}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].descripcion}">${self.data[i].descripcion}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].categoria}">${self.data[i].categoria}</td>
					<td class="">${self.data[i].subcategoria}</td>
					<td class="">${self.data[i].segmento}</td>
					<td class="">${self.data[i].subsegmento}</td>
					<td class="">${self.data[i].ocasiones}</td>
					<td class="">${self.data[i].fabricante}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].marca}">${self.data[i].marca}</td>
					<td class="">${self.data[i].submarca}</td>
					<td class="">${self.data[i].sabor}</td>
					<td class="">${self.data[i].empaque}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].contenido}">${self.data[i].contenido}</td>
					<td class="text-truncate c-pointer editRow" title="${self.data[i].unidadMedida == 'null' ? '-' : self.data[i].unidadMedida}">${self.data[i].unidadMedida == 'null' ? '-' : self.data[i].unidadMedida}</td>
					<td class="">${self.data[i].rangoContenido}</td>
					<td class="">${self.data[i].imgFolder}</td>
					<td class="">${self.data[i].fichaGS1Completa}</td>
					<td class="">${self.data[i].pendienteRevision}</td>
					<td class="">${self.data[i].comercios}</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].idItem}">
							<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 === 'fichacompleta' || title === 'pendienterevision') {
				value = optionsSelectAllYesNo();
			} else 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: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{visible: false, targets: 1},
				{visible: false, targets: 6},
				{visible: false, targets: 7},
				{visible: false, targets: 8},
				{visible: false, targets: 9},
				{visible: false, targets: 10},
				{visible: false, targets: 12},
				{visible: false, targets: 13},
				{visible: false, targets: 14},
				{width: '70px', targets: 15},
				{width: '70px', targets: 16},
				{visible: false, targets: 17},
				{visible: false, targets: 18},
				{visible: false, targets: 19},
				{visible: false, targets: 20},
				{visible: false, targets: 21},
				{width: '60px', orderable: false, targets: 22}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2370,
				className: 'd-none',
				title: '',
				filename: function () {
					return pf.const.language.RSC2370;
				 },
				exportOptions: {
					columns: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
					format: {
						body(data, row, column, node) {
                            //TODO: REVIEW THIS CODE
							//let dev = '\u200C' + data;
							let dev = data;

							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

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

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

		self.tableEvents(dataTable);

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

	tableEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

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

			sessionStorage.setItem('idItem', btoa(id));
			window.location.href = '#!items_edit';
		});

		// Eliminar item
		$('.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.RSC2370;
			let alertText = pf.const.language.RSC2382;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteItems(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.RSC2370;
			let alertText = pf.const.language.RSC2381;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteItems();
			}, function() {});
		});
	},

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

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

		let parameters = {
			items: JSON.stringify(items)
		};
		ajaxComunCallWithCallback('deleteItems', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2370;
				let successContent = pf.const.language.RSC2076;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/items/items.html', 'wrapper', ItemsController);
			}
		});
	},

	sendExcelDataToServer() {
		let self = this;

		let date = new Date();
		let stampName = date.getTime();
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;

		let parameters = {
			stampName: stampName,
			userMail: userMail,
			dataExcelHead: JSON.stringify(self.dataExcelHead),
			dataExcelBody: JSON.stringify(self.dataExcelBody)
		};
		ajaxComunCallWithCallback('sendExcelDataToServerItems', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Archivo guardado correctamente
				console.log('Data excel send.');
			}
		});
	},

	uploadFile(evt) {
		let self = this;

		let itemsArray = [];
		// Convertir excel a JSON
		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'
			});

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

				importItems.forEach(element => {
					let obj = {
						idItem: element.idItem === undefined ? '' : element.idItem.toString().replace('\u200C', ''),
						fichaGS1Completa: element[pf.const.language.RSC2414] === undefined ? '' : element[pf.const.language.RSC2414].toString().replace('\u200C', ''),
						pendienteRevision: element[pf.const.language.RSC2415] === undefined ? '' : element[pf.const.language.RSC2415].toString().replace('\u200C', ''),
						barcode: element[pf.const.language.RSC1674] === undefined ? '' : element[pf.const.language.RSC1674].toString().replace('\u200C', '').trim(),
						nombre: element[pf.const.language.RSC123] === undefined ? '' : element[pf.const.language.RSC123].toString().replace('\u200C', '').trim(),
						descripcion: element[pf.const.language.RSC178] === undefined ? '' : element[pf.const.language.RSC178].toString().replace('\u200C', '').trim(),
						categoria: element[pf.const.language.RSC1822] === undefined ? '' : element[pf.const.language.RSC1822].toString().replace('\u200C', '').trim(),
						subcategoria: element[pf.const.language.RSC2371] === undefined ? '' : element[pf.const.language.RSC2371].toString().replace('\u200C', '').trim(),
						segmento: element[pf.const.language.RSC2133] === undefined ? '' : element[pf.const.language.RSC2133].toString().replace('\u200C', '').trim(),
						subsegmento: element[pf.const.language.RSC2372] === undefined ? '' : element[pf.const.language.RSC2372].toString().replace('\u200C', '').trim(),
						ocasiones: element[pf.const.language.RSC2373] === undefined ? '' : element[pf.const.language.RSC2373].toString().replace('\u200C', '').trim(),
						fabricante: element[pf.const.language.RSC1422] === undefined ? '' : element[pf.const.language.RSC1422].toString().replace('\u200C', '').trim(),
						marca: element[pf.const.language.RSC2374] === undefined ? '' : element[pf.const.language.RSC2374].toString().replace('\u200C', '').trim(),
						submarca: element[pf.const.language.RSC2375] === undefined ? '' : element[pf.const.language.RSC2375].toString().replace('\u200C', '').trim(),
						sabor: element[pf.const.language.RSC2376] === undefined ? '' : element[pf.const.language.RSC2376].toString().replace('\u200C', '').trim(),
						empaque: element[pf.const.language.RSC2377] === undefined ? '' : element[pf.const.language.RSC2377].toString().replace('\u200C', '').trim(),
						contenido: element[pf.const.language.RSC2378] === undefined ? '' : element[pf.const.language.RSC2378].toString().replace('\u200C', '').trim(),
						unidadMedida: element[pf.const.language.RSC1048] === undefined ? '' : element[pf.const.language.RSC1048].toString().replace('\u200C', '').trim(),
						rangoContenido: element[pf.const.language.RSC2380] === undefined ? '' : element[pf.const.language.RSC2380].toString().replace('\u200C', '').trim(),
						comercios: element[pf.const.language.RSC2473] === undefined ? '' : element[pf.const.language.RSC2473].toString().replace('.', ',').replace('\u200C', '').trim(),
						imgFolder: element.imgFolder === undefined ? '' : element.imgFolder.toString().replace('\u200C', '')
					};

					itemsArray.push(obj);

					if(obj.barcode === '') {
						validate = false;
					}
				});

				if(!validate) {
					let alertTitle = pf.const.language.RSC2370;
					let alertText = pf.const.language.RSC322;
					pf.utils.showInfoDialog(alertTitle, alertText);
				} else {
					let JSONuser = sessionStorage['STCMBackEnd:user'];
					let user = JSON.parse(JSONuser);
					let userMail = user.email;

					let parameters = {
						userMail: userMail,
						itemsArray: JSON.stringify(itemsArray)
					};
					ajaxComunCallWithCallback('updateNewItemsFromFile', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							let successTitle = pf.const.language.RSC2370;
							let successContent = pf.const.language.RSC2404;
							pf.utils.showInfoDialog(successTitle, successContent);
							loadHTML('inc/items/items.html', 'wrapper', ItemsController);
						}
					});
				}

				$('#inputFile').val(null);
			})
		};

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

		reader.readAsBinaryString(selectedFile);
	}
};