Untitled
unknown
javascript
2 years ago
6.0 kB
7
Indexable
document.addEventListener('DOMContentLoaded', function() { // Get a reference to the 'estacionamento' element const estacionamento = document.getElementById('estacionamento'); // Configuration for parking rates const configTarifas = { tarifaPorHora: 10, tarifaPorFracao: 2 }; // Initialize the state of parking spots let estadoVagas = inicializarEstadoVagas(10); // Add event listeners for filter buttons document.getElementById('filterAll').addEventListener('click', () => filterSpots('all')); document.getElementById('filterOccupied').addEventListener('click', () => filterSpots('ocupada')); document.getElementById('filterFree').addEventListener('click', () => filterSpots('livre')); // Add a click event listener to the 'estacionamento' element estacionamento.addEventListener('click', function(event) { if (event.target.classList.contains('vaga')) { // Manage the clicked parking spot gerenciarVaga(event.target, estadoVagas, configTarifas); } }); // Function to filter parking spots based on 'filter' parameter function filterSpots(filter) { const spots = document.querySelectorAll('.vaga'); spots.forEach(spot => { if (filter === 'all') { spot.style.display = 'flex'; } else if (spot.classList.contains(filter)) { spot.style.display = 'flex'; } else { spot.style.display = 'none'; } }); } // Function to initialize the state of parking spots function inicializarEstadoVagas(numeroVagas) { let estado = { horarioEntrada: {}, placaPorVaga: {} }; for (let i = 0; i < numeroVagas; i++) { let vaga = document.createElement('div'); vaga.classList.add('vaga', 'livre'); vaga.id = `vaga-${i + 1}`; vaga.textContent = i + 1; estacionamento.appendChild(vaga); } return estado; } // Function to manage a parking spot (either park or process exit) function gerenciarVaga(vaga, estadoVagas, configTarifas) { let vagaId = vaga.id; if (vaga.classList.contains('livre')) { // Prompt for the car's license plate and perform entry registration let placa = prompt("Digite a placa do carro (formato: AAA1A11):").toUpperCase(); if (!validarPlaca(placa)) { alert("Placa inválida. Por favor, insira a placa no formato: AAA1A11."); return; } let estadoIdentificado = identificarEstado(placa); if (!estadoIdentificado) { alert("Estado da placa não identificado. Estados aceitos: SP, RJ, ES."); return; } estadoVagas.placaPorVaga[vagaId] = placa; alert(`Placa de origem: ${estadoIdentificado}`); registrarEntrada(vaga, vagaId, estadoVagas); } else { // Process exit from the parking spot processarSaida(vaga, vagaId, estadoVagas, configTarifas); } } // Function to validate a license plate function validarPlaca(placa) { const regexPlaca = /^[A-Z]{3}[0-9][A-Z][0-9]{2}$/; return regexPlaca.test(placa); } // Function to register entry for a parking spot function registrarEntrada(vaga, vagaId, estadoVagas) { estadoVagas.horarioEntrada[vagaId] = new Date(); vaga.classList.replace('livre', 'ocupada'); alert(`Entrada registrada para a ${vagaId} às ${estadoVagas.horarioEntrada[vagaId].toLocaleTimeString()}`); } // Function to process exit from a parking spot function processarSaida(vaga, vagaId, estadoVagas, configTarifas) { let horaSaidaValida = false; let dataSaida; while (!horaSaidaValida) { let horaSaida = prompt(`Insira a hora de saída para a ${vagaId} (formato HH:MM):`, new Date().toLocaleTimeString().slice(0, 5)); dataSaida = new Date(); if (validarHoraSaida(horaSaida)) { let [hora, minuto] = horaSaida.split(':').map(Number); dataSaida.setHours(hora, minuto); horaSaidaValida = true; } else { alert("Hora inválida. Por favor, insira a hora no formato HH:MM."); } } let tarifa = calcularTarifa(estadoVagas.horarioEntrada[vagaId], dataSaida, configTarifas); alert(`Tarifa para a ${vagaId}: R$ ${tarifa}`); vaga.classList.replace('ocupada', 'livre'); delete estadoVagas.placaPorVaga[vagaId]; } // Function to validate the exit time format function validarHoraSaida(horaSaida) { const regexHora = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/; return regexHora.test(horaSaida); } // Function to identify the state based on the license plate function identificarEstado(placa) { const estados = { 'BFA': { fim: 'GKI', nome: 'São Paulo' }, 'KMF': { fim: 'LVE', nome: 'Rio de Janeiro' }, 'MOX': { fim: 'MTZ', nome: 'Espírito Santo' } }; let letras = placa.substring(0, 3).toUpperCase(); let estadoEncontrado = Object.keys(estados).find(inicio => letras >= inicio && letras <= estados[inicio].fim); return estadoEncontrado ? estados[estadoEncontrado].nome : null; } // Function to calculate the parking fee function calcularTarifa(horaEntrada, horaSaida, configTarifas) { let diferenca = horaSaida - horaEntrada; let horas = diferenca / 3600000; let tarifa = configTarifas.tarifaPorHora * Math.floor(horas); if (horas % 1 !== 0) { tarifa += configTarifas.tarifaPorFracao; } return tarifa.toFixed(2); } });
Editor is loading...
Leave a Comment