let StoresController = {
	data: '',
	arrayDelMult: [],
	storesType: {},
	dataExcelHead: [],
	dataExcelBody: [],

	reset() {
		let self = this;

		self.data = '';
		self.arrayDelMult = [];
		self.storesType = {};
		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.RSC2473);

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

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

				ajaxComunCallWithCallback('getAllComerciosType', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.storesType = {};

						for(let i = 0; i < ajaxReturn.result.length; i++) {
							self.storesType[ajaxReturn.result[i].id] = ajaxReturn.result[i].descripcion;
						}

						self.renderData();
						removeLoader();
					}
				}, false);
			}
		}, false);

		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);
		$('.deleteMultTitle').attr('title', pf.const.language.RSC95);
	},

	applyEvents() {
		let self = this;

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

	renderData() {
		let self = this;

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

		// Creación de cabeceras para el excel
		self.dataExcelHead = ['id', 'nombre', 'direccion', 'latitude', 'longitude', 'altitude', 'accuracy', 'idComercioType', 'fotosFolder', 'abiertaPublico', 'ventanilla', 'numCajas', 'numRefrigeradores', 'horarioApertura', 'horarioCierre', 'apertura24H', 'telefono', 'email', 'personaContacto'];

		// 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" title="ID">ID</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC1229}">${pf.const.language.RSC1229}</th>
					<th scope="col">latitude</th>
					<th scope="col">longitude</th>
					<th scope="col">altitude</th>
					<th scope="col">accuracy</th>
					<th scope="col" title="${pf.const.language.RSC2474}">${pf.const.language.RSC2474}</th>
					<th scope="col">${pf.const.language.RSC2474}</th>
					<th scope="col">fotosFolder</th>
					<th scope="col">abiertaPublico</th>
					<th scope="col">ventanilla</th>
					<th scope="col">numCajas</th>
					<th scope="col">numRefrigeradores</th>
					<th scope="col">horarioApertura</th>
					<th scope="col">horarioCierre</th>
					<th scope="col" title="${pf.const.language.RSC2488}">${pf.const.language.RSC2488}</th>
					<th scope="col">telefono</th>
					<th scope="col">email</th>
					<th scope="col">personaContacto</th>
					<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>selector</td>
					<td>id</td>
					<td>nombre</td>
					<td>direccion</td>
					<td class="d-none">latitude</td>
					<td class="d-none">longitude</td>
					<td class="d-none">altitude</td>
					<td class="d-none">accuracy</td>
					<td>idComercioType</td>
					<td class="d-none">idComercio</td>
					<td class="d-none">fotosFolder</td>
					<td class="d-none">abiertaPublico</td>
					<td class="d-none">ventanilla</td>
					<td class="d-none">numCajas</td>
					<td class="d-none">numRefrigeradores</td>
					<td class="d-none">horarioApertura</td>
					<td class="d-none">horarioCierre</td>
					<td>apertura24H</td>
					<td class="d-none">telefono</td>
					<td class="d-none">email</td>
					<td class="d-none">personaContacto</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].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-center c-pointer editRow" title="${self.data[i].id}">${self.data[i].id}</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].direccion || '-'}">${self.data[i].direccion || '-'}</td>
					<td class="">${self.data[i].latitude}</td>
					<td class="">${self.data[i].longitude}</td>
					<td class="">${self.data[i].altitude}</td>
					<td class="">${self.data[i].accuracy}</td>
					<td class="text-truncate c-pointer editRow" title="${self.storesType[self.data[i].idComercioType]}">${self.storesType[self.data[i].idComercioType]}</td>
					<td class="">${self.data[i].idComercioType}</td>
					<td class="">${self.data[i].fotosFolder}</td>
					<td class="">${self.data[i].abiertaPublico}</td>
					<td class="">${self.data[i].ventanilla}</td>
					<td class="">${self.data[i].numCajas}</td>
					<td class="">${self.data[i].numRefrigeradores}</td>
					<td class="">${self.data[i].horarioApertura}</td>
					<td class="">${self.data[i].horarioCierre}</td>
					<td class="text-center c-pointer editRow">
						<span class="d-none">${(self.data[i].apertura24H == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(self.data[i].apertura24H == '1' ? 'checked' : '')}>
					</td>
					<td class="">${self.data[i].telefono}</td>
					<td class="">${self.data[i].email}</td>
					<td class="">${self.data[i].personaContacto}</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 === 'apertura24H') {
				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},
				{width: '30px', targets: 1},
				{visible: false, targets: 4},
				{visible: false, targets: 5},
				{visible: false, targets: 6},
				{visible: false, targets: 7},
				{visible: false, targets: 9},
				{visible: false, targets: 10},
				{visible: false, targets: 11},
				{visible: false, targets: 12},
				{visible: false, targets: 13},
				{visible: false, targets: 14},
				{visible: false, targets: 15},
				{visible: false, targets: 16},
				{width: '90px', targets: 17},
				{visible: false, targets: 18},
				{visible: false, targets: 19},
				{visible: false, targets: 20},
				{width: '60px', orderable: false, targets: 21}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC2473,
				className: 'd-none',
				title: '',
				filename: function () {
					return pf.const.language.RSC2473;
				 },
				exportOptions: {
					columns: [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
				},
				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 tienda
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

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

		// Borrar tienda
		$('.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.RSC2473;
			let alertText = pf.const.language.RSC2490;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteComercios(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.RSC2473;
			let alertText = pf.const.language.RSC2489;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteComercios();
			}, function() {});
		});
	},

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

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

		let parameters = {
			stores: JSON.stringify(stores)
		};
		ajaxComunCallWithCallback('deleteComercios', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC2473;
				let successContent = pf.const.language.RSC2491;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/items/stores.html', 'wrapper', StoresController);
			}
		});
	},

	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('sendExcelDataToServerStores', 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 = {
						id: element.id || '',
						nombre: element[pf.const.language.RSC123] === undefined ? '' : element[pf.const.language.RSC123],
						direccion: element[pf.const.language.RSC1229] === undefined ? '' : element[pf.const.language.RSC1229],
						latitude: element.latitude === undefined ? '' : element.latitude,
						longitude: element.longitude === undefined ? '' : element.longitude,
						altitude: element.altitude === undefined ? '' : element.altitude,
						accuracy: element.accuracy === undefined ? '' : element.accuracy,
						idComercioType: element[pf.const.language.RSC2474] === undefined ? '' : element[pf.const.language.RSC2474],
						fotosFolder: element.fotosFolder === undefined ? '' : element.fotosFolder,
						abiertaPublico: element.abiertaPublico === undefined ? '' : element.abiertaPublico,
						ventanilla: element.ventanilla === undefined ? '' : element.ventanilla,
						numCajas: element.numCajas === undefined ? '' : element.numCajas,
						numRefrigeradores: element.numRefrigeradores === undefined ? '' : element.numRefrigeradores,
						horarioApertura: element.horarioApertura === undefined ? '' : element.horarioApertura,
						horarioCierre: element.horarioCierre === undefined ? '' : element.horarioCierre,
						apertura24H: element[pf.const.language.RSC2488] === undefined ? '' : element[pf.const.language.RSC2488],
						telefono: element.telefono === undefined ? '' : element.telefono,
						email: element.email === undefined ? '' : element.email,
						personaContacto: element.personaContacto === undefined ? '' : element.personaContacto
					};

					itemsArray.push(obj);
				});

				if(!validate) {
					let alertTitle = pf.const.language.RSC2473;
					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('updateNewStoresFromFile', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							let successTitle = pf.const.language.RSC2473;
							let successContent = pf.const.language.RSC2404;
							pf.utils.showInfoDialog(successTitle, successContent);
							loadHTML('inc/items/stores.html', 'wrapper', StoresController);
						}
					});
				}

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

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

		reader.readAsBinaryString(selectedFile);
	}
};