Adicionar Instrumento
`; } else { html += `
+
`; } } grid.innerHTML = html;}function addFoto(e) { const file = e.target.files && e.target.files[0]; if (!file) return; if (fotosTmp.length >= MAX_FOTOS) { alert('Máximo de 5 fotos por instrumento.'); e.target.value = ''; return; } const reader = new FileReader(); reader.onload = ev => { const img = new Image(); img.onload = () => { const maxLado = 800; let { width: w, height: h } = img; if (w > h && w > maxLado) { h = h * maxLado / w; w = maxLado; } else if (h > maxLado) { w = w * maxLado / h; h = maxLado; } const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; canvas.getContext('2d').drawImage(img, 0, 0, w, h); fotosTmp.push(canvas.toDataURL('image/jpeg', 0.7)); renderFotos(); }; img.onerror = () => alert('Não foi possível carregar a imagem.'); img.src = ev.target.result; }; reader.readAsDataURL(file); e.target.value = '';}function removerFoto(k) { if (!confirm('Remover esta foto?')) return; fotosTmp.splice(k, 1); renderFotos();}function abrirLightbox(src) { if (!src) return; document.getElementById('lightboxImg').src = src; document.getElementById('lightbox').classList.add('aberto');}function fecharLightbox() { document.getElementById('lightbox').classList.remove('aberto'); document.getElementById('lightboxImg').src = '';}function salvar() { const nome = document.getElementById('fNome').value.trim(); if (!nome) { alert('Informe o nome do instrumento.'); document.getElementById('fNome').focus(); return; } const id = document.getElementById('editId').value; const antigo = id ? dados.find(d => d.id === id) : null; const obj = { id: id || Date.now().toString() + Math.random().toString(36).slice(2, 7), nome, categoria: document.getElementById('fCategoria').value, marca: document.getElementById('fMarca').value.trim(), inventario: document.getElementById('fInventario').value.trim(), estado: document.getElementById('fEstado').value, status: document.getElementById('fStatus').value, departamento: document.getElementById('fDepartamento').value.trim(), local: document.getElementById('fLocal').value.trim(), obs: document.getElementById('fObs').value.trim(), fotos: [...fotosTmp], historico: antigo?.historico || [], criadoEm: antigo?.criadoEm || new Date().toISOString() }; if (id) { dados = dados.map(d => d.id === id ? obj : d); } else { dados.push(obj); } if (!salvarStorage()) return; fecharModal(); render();}function excluir(id) { if (!confirm('Excluir este instrumento e todo o histórico?')) return; dados = dados.filter(d => d.id !== id); salvarStorage(); render();}function abrirHist(id) { const inst = dados.find(d => d.id === id); if (!inst) return; histAtualId = id; document.getElementById('tituloHist').textContent = 'Manutenção: ' + inst.nome; document.getElementById('hData').value = new Date().toISOString().slice(0, 10); document.getElementById('hTipo').value = 'Limpeza'; document.getElementById('hCusto').value = ''; document.getElementById('hObs').value = ''; renderHist(); document.getElementById('modalHist').classList.add('aberto');}function fecharHist() { document.getElementById('modalHist').classList.remove('aberto'); histAtualId = null;}function renderHist() { const inst = dados.find(d => d.id === histAtualId); const box = document.getElementById('listaHist'); if (!box) return; if (!inst || !inst.historico.length) { box.innerHTML = '
Nenhum registro ainda.
'; return; } const ordenado = [...inst.historico].sort((a, b) => (b.data || '').localeCompare(a.data || '')); box.innerHTML = ordenado.map(h => `
${formatarData(h.data)} — ${escapeHtml(h.tipo)}
Custo: R$ ${Number(h.custo || 0).toFixed(2).replace('.', ',')} ${h.obs ? '
' + escapeHtml(h.obs) + '' : ''}
`).join('');}function salvarHist() { const inst = dados.find(d => d.id === histAtualId); if (!inst) return; const data = document.getElementById('hData').value; if (!data) { alert('Informe a data.'); document.getElementById('hData').focus(); return; } inst.historico.push({ id: Date.now().toString() + Math.random().toString(36).slice(2, 6), data, tipo: document.getElementById('hTipo').value, custo: parseFloat(document.getElementById('hCusto').value) || 0, obs: document.getElementById('hObs').value.trim() }); if (!salvarStorage()) return; renderHist(); render(); document.getElementById('hCusto').value = ''; document.getElementById('hObs').value = '';}function excluirHist(hid) { const inst = dados.find(d => d.id === histAtualId); if (!inst) return; if (!confirm('Remover este registro?')) return; inst.historico = inst.historico.filter(h => h.id !== hid); salvarStorage(); renderHist(); render();}function classeStatus(s) { return { 'Disponível':'st-disponivel', 'Em uso':'st-uso', 'Em manutenção':'st-manutencao', 'Emprestado':'st-emprestado' }[s] || 'st-disponivel';}function formatarData(iso) { if (!iso) return ''; const partes = String(iso).split('-'); if (partes.length !== 3) return iso; return `${partes[2]}/${partes[1]}/${partes[0]}`;}function escapeHtml(t) { return String(t ?? '').replace(/[&<>"']/g, c => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[c]));}function render() { const busca = (document.getElementById('busca').value || '').toLowerCase(); const fs = document.getElementById('filtroStatus').value; const fc = document.getElementById('filtroCategoria').value; const lista = document.getElementById('lista'); const filtrados = dados.filter(d => { const alvo = (d.nome + ' ' + (d.marca || '') + ' ' + (d.inventario || '')).toLowerCase(); const okBusca = !busca || alvo.includes(busca); const okStatus = !fs || d.status === fs; const okCat = !fc || d.categoria === fc; return okBusca && okStatus && okCat; }); document.getElementById('contador').textContent = `${filtrados.length} de ${dados.length} instrumento(s)`; if (!filtrados.length) { lista.innerHTML = '
Nenhum instrumento encontrado.
Clique em "Adicionar Instrumento" para começar.
'; return; } lista.innerHTML = filtrados.map(d => { const totalManut = (d.historico || []).reduce((s, h) => s + Number(h.custo || 0), 0); const fotosHtml = (d.fotos && d.fotos.length) ? `
${d.fotos.map(f => `

`).join('')}
` : ''; return `
${escapeHtml(d.status)} ${escapeHtml(d.nome)}
${fotosHtml}
📂 ${escapeHtml(d.categoria)}${d.marca ? ' • ' + escapeHtml(d.marca) : ''}
${d.inventario ? `
🏷 Inventário: ${escapeHtml(d.inventario)}
` : ''}
⭐ Estado: ${escapeHtml(d.estado)}
${d.departamento ? `
🏛 Departamento: ${escapeHtml(d.departamento)}
` : ''} ${d.local ? `
📍 Local: ${escapeHtml(d.local)}
` : ''} ${d.obs ? `
📝 ${escapeHtml(d.obs)}
` : ''}
🔧 ${(d.historico || []).length} manutenção(ões) • Total: R$ ${totalManut.toFixed(2).replace('.', ',')}
`; }).join('');}function exportar() { try { const blob = new Blob([JSON.stringify(dados, null, 2)], { type: 'application/json' }); const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `fama-adoracao-backup-${new Date().toISOString().slice(0, 10)}.json`; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(a.href), 1000); } catch (e) { alert('Não foi possível exportar o backup.'); }}function importar(e) { const file = e.target.files && e.target.files[0]; if (!file) return; const reader = new FileReader(); reader.onload = ev => { try { const arr = JSON.parse(ev.target.result); if (!Array.isArray(arr)) throw new Error('Formato inválido'); if (!confirm(`Importar ${arr.length} instrumento(s)? Isso substituirá os dados atuais.`)) return; dados = arr; salvarStorage(); render(); alert('Backup importado com sucesso!'); } catch (err) { alert('Arquivo inválido ou corrompido.'); } }; reader.readAsText(file); e.target.value = '';}document.addEventListener('keydown', e => { if (e.key === 'Escape') { if (document.getElementById('lightbox').classList.contains('aberto')) fecharLightbox(); else if (document.getElementById('modalFundo').classList.contains('aberto')) fecharModal(); else if (document.getElementById('modalHist').classList.contains('aberto')) fecharHist(); }});render();