console.log('Carregando script militantes.js...'); // Constantes para responsabilidades const Militante = { RESPONSAVEL_FINANCAS: 256, RESPONSAVEL_IMPRENSA: 512, QUADRO_ORIENTADOR: 64, SECRETARIO: 1, TESOUREIRO: 2, IMPRENSA: 4, MNS: 8, MPS: 16, JUVENTUDE: 32, ASPIRANTE: 128 }; // Função para obter o token CSRF da meta tag function getCsrfToken() { const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content'); if (!token) { console.error('CSRF token não encontrado!'); return ''; } return token; } // Variáveis globais para controle dos filtros e paginação let filtroAtual = 'todos'; let filtroResponsabilidade = null; let filtroCelula = null; let currentPage = 1; let rowsPerPage = 20; let totalRows = 0; // Mapa de responsabilidades para valores numéricos const RESPONSABILIDADES_MAP = { 'Secretário': 1, 'Tesoureiro': 2, 'Imprensa': 4, 'MNS': 8, 'MPS': 16, 'Juventude': 32, 'Quadro-Orientador': 64, 'Aspirante': 128, 'Responsável de Finanças': 256, 'Responsável de Imprensa': 512 }; // Mapa reverso para converter valores em nomes const RESPONSABILIDADES_REVERSE_MAP = { 1: 'Secretário', 2: 'Tesoureiro', 4: 'Imprensa', 8: 'MNS', 16: 'MPS', 32: 'Juventude', 64: 'Quadro-Orientador', 128: 'Aspirante', 256: 'Responsável de Finanças', 512: 'Responsável de Imprensa' }; // Função para validar data no formato DD/MM/YYYY function validarData(data) { if (!data) return true; // Campo vazio é válido // Verifica o formato if (!/^\d{2}\/\d{2}\/\d{4}$/.test(data)) return false; // Extrai dia, mês e ano const [dia, mes, ano] = data.split('/').map(Number); // Cria um objeto Date const dataObj = new Date(ano, mes - 1, dia); // Verifica se a data é válida return dataObj.getDate() === dia && dataObj.getMonth() === mes - 1 && dataObj.getFullYear() === ano && ano >= 1900 && ano <= 2100; } // Função para formatar data do formato ISO (YYYY-MM-DD) para DD/MM/YYYY function formatarData(data) { if (!data) return ''; const [ano, mes, dia] = data.split('-'); return `${dia}/${mes}/${ano}`; } // Função para converter data de DD/MM/YYYY para YYYY-MM-DD function converterDataParaISO(data) { if (!data) return ''; if (data.includes('-')) return data; const [dia, mes, ano] = data.split('/'); return `${ano}-${mes}-${dia}`; } // Função para calcular o total de páginas function calculateTotalPages() { const allRows = document.querySelectorAll('#militantesTable tbody tr'); const visibleRows = Array.from(allRows).filter(row => !row.hasAttribute('data-filtered-out') ); totalRows = visibleRows.length; return Math.ceil(totalRows / rowsPerPage); } // Função para atualizar o texto de contagem function updateCountText() { const allRows = document.querySelectorAll('#militantesTable tbody tr'); const visibleRows = Array.from(allRows).filter(row => !row.hasAttribute('data-filtered-out') ); totalRows = visibleRows.length; const startIndex = (currentPage - 1) * rowsPerPage + 1; const endIndex = Math.min(currentPage * rowsPerPage, totalRows); // Atualizar texto de contagem document.getElementById('countMilitantes').textContent = `${startIndex}-${endIndex} de ${totalRows}`; } // Função para atualizar a paginação function updatePagination() { const totalPages = calculateTotalPages(); const paginationUl = document.querySelector('.pagination'); const prevPage = document.getElementById('prevPage'); const nextPage = document.getElementById('nextPage'); // Limpar páginas existentes (exceto prev e next) const pageItems = paginationUl.querySelectorAll('li:not(#prevPage):not(#nextPage)'); pageItems.forEach(item => item.remove()); // Adicionar novas páginas for (let i = 1; i <= totalPages; i++) { const li = document.createElement('li'); li.className = `page-item${i === currentPage ? ' active' : ''}`; li.innerHTML = `${i}`; li.addEventListener('click', (e) => { e.preventDefault(); currentPage = i; updateVisibleRows(); updatePagination(); }); paginationUl.insertBefore(li, nextPage); } // Atualizar estado dos botões prev/next prevPage.classList.toggle('disabled', currentPage === 1); nextPage.classList.toggle('disabled', currentPage === totalPages || totalPages === 0); // Adicionar eventos aos botões prev/next prevPage.onclick = (e) => { e.preventDefault(); if (currentPage > 1) { currentPage--; updateVisibleRows(); updatePagination(); } }; nextPage.onclick = (e) => { e.preventDefault(); if (currentPage < totalPages) { currentPage++; updateVisibleRows(); updatePagination(); } }; // Atualizar texto de contagem updateCountText(); } // Função para atualizar as linhas visíveis function updateVisibleRows() { const allRows = document.querySelectorAll('#militantesTable tbody tr'); const visibleRows = Array.from(allRows).filter(row => !row.hasAttribute('data-filtered-out') ); const startIndex = (currentPage - 1) * rowsPerPage; const endIndex = startIndex + rowsPerPage; visibleRows.forEach((row, index) => { if (index >= startIndex && index < endIndex) { row.style.display = ''; } else { row.style.display = 'none'; } }); updateCountText(); } // Função para filtrar militantes function filtrarMilitantes() { const searchTerm = document.getElementById('searchInput').value.toLowerCase(); const rows = document.querySelectorAll('#militantesTable tbody tr'); rows.forEach(row => { let shouldShow = true; // Filtro de texto const textContent = row.textContent.toLowerCase(); if (!textContent.includes(searchTerm)) { shouldShow = false; } // Filtro de responsabilidades if (filtroResponsabilidade) { const responsabilidadeMap = { 'responsavel-financas': Militante.RESPONSAVEL_FINANCAS, 'responsavel-imprensa': Militante.RESPONSAVEL_IMPRENSA, 'quadro-orientador': Militante.QUADRO_ORIENTADOR, 'secretario': Militante.SECRETARIO, 'tesoureiro': Militante.TESOUREIRO, 'imprensa': Militante.IMPRENSA, 'mns': Militante.MNS, 'mps': Militante.MPS, 'juventude': Militante.JUVENTUDE, 'aspirante': Militante.ASPIRANTE }; const valorResponsabilidade = responsabilidadeMap[filtroResponsabilidade]; const responsabilidades = parseInt(row.getAttribute('data-responsabilidades') || '0'); if ((responsabilidades & valorResponsabilidade) === 0) { shouldShow = false; } } // Filtro de célula if (filtroCelula) { const celula = row.querySelector('[data-celula-id]')?.getAttribute('data-celula-id'); if (celula !== filtroCelula) { shouldShow = false; } } // Marcar linha como filtrada ou não if (shouldShow) { row.removeAttribute('data-filtered-out'); row.style.display = ''; } else { row.setAttribute('data-filtered-out', ''); row.style.display = 'none'; } }); // Resetar para a primeira página e atualizar paginação currentPage = 1; updateVisibleRows(); updatePagination(); } // Função para configurar um campo de data function configurarCampoData(campo) { if (!campo) return; // Remover campo de texto anterior se existir const campoTextoExistente = campo.previousElementSibling; if (campoTextoExistente && campoTextoExistente.classList.contains('campo-data-texto')) { campoTextoExistente.remove(); } // Configurar o campo de data campo.type = 'date'; // Se já tiver valor, garantir que está no formato ISO if (campo.value) { campo.value = converterDataParaISO(campo.value); } // Quando o valor mudar, garantir formato ISO campo.addEventListener('change', function() { if (this.value) { this.value = converterDataParaISO(this.value); } }); } // Função para carregar os dados do militante no modal de edição async function carregarDadosMilitante(militanteId) { try { console.log('Carregando dados do militante:', militanteId); const response = await fetch(`/militantes/dados/${militanteId}`); const data = await response.json(); if (data.status === 'error') { throw new Error(data.message); } console.log('Dados recebidos:', data); // Mapear campos básicos const campos = [ 'nome', 'cpf', 'titulo_eleitoral', 'data_nascimento', 'data_entrada_oci', 'data_efetivacao_oci', 'telefone1', 'telefone2', 'profissao', 'regime_trabalho', 'empresa', 'contratante', 'instituicao_ensino', 'tipo_instituicao', 'sindicato', 'cargo_sindical', 'central_sindical', 'dirigente_sindical' ]; campos.forEach(campo => { const elemento = document.getElementById(`edit_${campo}`); if (elemento) { if (elemento.type === 'checkbox') { elemento.checked = data[campo]; } else { elemento.value = data[campo] || ''; } } }); // Preencher o email (primeiro email da lista) const emailElement = document.getElementById('edit_email'); if (emailElement) { if (data.emails && data.emails.length > 0) { emailElement.value = data.emails[0]; // O email já vem como string } else { emailElement.value = ''; } } // Mapear campos de endereço if (data.endereco) { const camposEndereco = ['cep', 'estado', 'cidade', 'bairro', 'rua', 'numero', 'complemento']; camposEndereco.forEach(campo => { const elemento = document.getElementById(`edit_${campo}`); if (elemento) { elemento.value = data.endereco[campo] || ''; } }); } // Mapear estado const selectEstado = document.getElementById('edit_estado'); if (selectEstado && data.estado) { selectEstado.value = data.estado; } // Mapear célula const selectCelula = document.getElementById('edit_celula_id'); if (selectCelula && data.celula_id) { selectCelula.value = data.celula_id; } // Processar responsabilidades if (data.responsabilidades_valor !== undefined) { console.log('Valor das responsabilidades:', data.responsabilidades_valor); // Resetar todas as badges para seu estado inicial document.querySelectorAll('.badge-clickable').forEach(badge => { badge.classList.remove('active'); const originalClass = badge.getAttribute('data-original-class'); if (originalClass) { badge.className = `badge badge-clickable ${originalClass}`; } }); // Ativar as badges correspondentes document.querySelectorAll('.badge-clickable').forEach(badge => { const valor = parseInt(badge.getAttribute('data-value')); if (!isNaN(valor) && (data.responsabilidades_valor & valor)) { badge.classList.add('active'); } }); // Atualizar o campo hidden com o valor total document.getElementById('responsabilidades_values').value = data.responsabilidades_valor; } } catch (error) { console.error('Erro ao carregar dados:', error); alert('Erro ao carregar dados do militante'); } } // Função para mostrar alertas function mostrarAlerta(mensagem, tipo) { const alertDiv = document.createElement('div'); alertDiv.className = `alert alert-${tipo} alert-dismissible fade show`; alertDiv.role = 'alert'; alertDiv.innerHTML = ` ${mensagem} `; const container = document.querySelector('.container'); container.insertBefore(alertDiv, container.firstChild); // Remover o alerta após 5 segundos setTimeout(() => { alertDiv.remove(); }, 5000); } // Configurar o token CSRF para todas as requisições AJAX $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", getCsrfToken()); } } }); // Configurar eventos quando o DOM estiver carregado document.addEventListener('DOMContentLoaded', function() { console.log('DOM carregado, configurando eventos...'); // Configurar seletor de linhas por página const rowsPerPageSelect = document.getElementById('rowsPerPage'); if (rowsPerPageSelect) { rowsPerPageSelect.addEventListener('change', function() { rowsPerPage = parseInt(this.value); currentPage = 1; updateVisibleRows(); updatePagination(); }); } // Configurar pesquisa const searchInput = document.getElementById('searchInput'); if (searchInput) { let timeoutId; searchInput.addEventListener('input', function() { clearTimeout(timeoutId); timeoutId = setTimeout(filtrarMilitantes, 300); }); } // Configurar filtros document.querySelectorAll('.dropdown-item[data-filter]').forEach(item => { item.addEventListener('click', function(e) { e.preventDefault(); const filter = this.getAttribute('data-filter'); const celula = this.getAttribute('data-celula'); // Resetar filtros anteriores if (filter === 'todos') { filtroAtual = 'todos'; filtroResponsabilidade = null; filtroCelula = null; } else if (['responsavel-financas', 'responsavel-imprensa', 'quadro-orientador'].includes(filter)) { filtroAtual = 'todos'; filtroResponsabilidade = filter === 'responsavel-financas' ? 'Responsável de Finanças' : filter === 'responsavel-imprensa' ? 'Responsável de Imprensa' : 'Quadro-Orientador'; filtroCelula = null; } else if (filter === 'celula') { filtroAtual = 'todos'; filtroResponsabilidade = null; filtroCelula = celula; } filtrarMilitantes(); // Atualizar texto do botão de filtro const filterText = this.textContent; const dropdownButton = document.querySelector('.dropdown-toggle'); dropdownButton.innerHTML = `${filterText}`; }); }); console.log('Configurando modal de edição...'); // Configurar máscara para campos de data $('.date-mask').mask('00/00/0000', { placeholder: 'DD/MM/AAAA', clearIfNotMatch: true }); // Validar campos de data quando perderem o foco $('.date-mask').on('blur', function() { const valor = $(this).val(); if (valor && !validarData(valor)) { $(this).addClass('is-invalid'); if (!$(this).next('.invalid-feedback').length) { $(this).after('
Data inválida
'); } } else { $(this).removeClass('is-invalid'); $(this).next('.invalid-feedback').remove(); } }); // Configurar campos de data em todos os modais const modalNovoMilitante = document.getElementById('modalNovoMilitante'); const modalEditarMilitante = document.getElementById('modalEditarMilitante'); // Configurar modal de edição if (modalEditarMilitante) { modalEditarMilitante.addEventListener('show.bs.modal', async function(event) { console.log('Modal de edição aberto'); const button = event.relatedTarget; if (!button) { console.error('Botão não encontrado'); alert('Erro ao abrir modal: botão não encontrado'); return; } const militanteId = button.getAttribute('data-militante-id'); const militanteNome = button.getAttribute('data-militante-nome'); console.log('Dados do botão:', { militanteId, militanteNome }); if (!militanteId) { console.error('ID do militante não encontrado no botão'); alert('Erro ao abrir modal: ID do militante não encontrado'); return; } // Definir o ID do militante no campo hidden const idField = document.getElementById('edit_militante_id'); if (!idField) { console.error('Campo hidden para ID do militante não encontrado'); alert('Erro ao abrir modal: campo para ID do militante não encontrado'); return; } idField.value = militanteId; console.log('ID do militante definido:', idField.value); // Atualizar título do modal const modalTitle = this.querySelector('.modal-title'); if (modalTitle) { modalTitle.textContent = `Editar ${militanteNome}`; } try { // Carregar dados do militante const response = await fetch(`/militantes/dados/${militanteId}`); if (!response.ok) { throw new Error(`Erro HTTP: ${response.status}`); } const data = await response.json(); console.log('Dados recebidos:', data); if (data.status === 'error') { throw new Error(data.message || 'Erro ao carregar dados do militante'); } // Mapear campos básicos const campos = [ 'nome', 'cpf', 'titulo_eleitoral', 'data_nascimento', 'data_entrada_oci', 'data_efetivacao_oci', 'telefone1', 'telefone2', 'profissao', 'regime_trabalho', 'empresa', 'contratante', 'instituicao_ensino', 'tipo_instituicao', 'sindicato', 'cargo_sindical', 'central_sindical', 'dirigente_sindical' ]; campos.forEach(campo => { const elemento = document.getElementById(`edit_${campo}`); if (elemento) { if (elemento.type === 'checkbox') { elemento.checked = data[campo]; } else { elemento.value = data[campo] || ''; } } }); // Preencher o email (primeiro email da lista) const emailElement = document.getElementById('edit_email'); if (emailElement) { if (data.emails && data.emails.length > 0) { emailElement.value = data.emails[0]; // O email já vem como string } else { emailElement.value = ''; } } // Mapear campos de endereço if (data.endereco) { const camposEndereco = ['cep', 'estado', 'cidade', 'bairro', 'rua', 'numero', 'complemento']; camposEndereco.forEach(campo => { const elemento = document.getElementById(`edit_${campo}`); if (elemento) { elemento.value = data.endereco[campo] || ''; } }); } // Mapear estado const selectEstado = document.getElementById('edit_estado'); if (selectEstado && data.estado) { selectEstado.value = data.estado; } // Mapear célula const selectCelula = document.getElementById('edit_celula_id'); if (selectCelula && data.celula_id) { selectCelula.value = data.celula_id; } // Processar responsabilidades if (data.responsabilidades_valor !== undefined) { console.log('Valor das responsabilidades:', data.responsabilidades_valor); // Resetar todas as badges para seu estado inicial document.querySelectorAll('.badge-clickable').forEach(badge => { badge.classList.remove('active'); const originalClass = badge.getAttribute('data-original-class'); if (originalClass) { badge.className = `badge badge-clickable ${originalClass}`; } }); // Ativar as badges correspondentes document.querySelectorAll('.badge-clickable').forEach(badge => { const valor = parseInt(badge.getAttribute('data-value')); if (!isNaN(valor) && (data.responsabilidades_valor & valor)) { badge.classList.add('active'); } }); // Atualizar o campo hidden com o valor total document.getElementById('responsabilidades_values').value = data.responsabilidades_valor; } } catch (error) { console.error('Erro ao carregar dados:', error); alert('Erro ao carregar dados do militante'); } }); // Configurar clique nas badges document.querySelectorAll('.badge-clickable').forEach(badge => { badge.addEventListener('click', function() { // Toggle classe active this.classList.toggle('active'); // Atualizar classes visuais if (this.classList.contains('active')) { const originalClass = this.getAttribute('data-original-class'); this.className = `badge badge-clickable ${originalClass} active`; } else { const originalClass = this.getAttribute('data-original-class'); this.className = `badge badge-clickable ${originalClass}`; } // Atualizar o valor total das responsabilidades let valorTotal = 0; document.querySelectorAll('.badge-clickable.active').forEach(activeBadge => { const valor = parseInt(activeBadge.getAttribute('data-value')); if (!isNaN(valor)) { valorTotal |= valor; } }); // Atualizar o campo hidden const responsabilidadesInput = document.getElementById('responsabilidades_values'); if (responsabilidadesInput) { responsabilidadesInput.value = valorTotal; console.log('Valor total das responsabilidades atualizado:', valorTotal); } }); }); // Configurar formulário de edição const formEditarMilitante = document.getElementById('formEditarMilitante'); if (formEditarMilitante) { formEditarMilitante.addEventListener('submit', async function(event) { event.preventDefault(); console.log('Formulário de edição enviado'); // Validar todos os campos antes do envio const form = this; form.classList.add('was-validated'); // Verificar se o formulário é válido if (!form.checkValidity()) { event.stopPropagation(); // Encontrar o primeiro campo inválido const invalidField = form.querySelector(':invalid'); if (invalidField) { // Encontrar a aba que contém o campo inválido const tabPane = invalidField.closest('.tab-pane'); if (tabPane) { // Ativar a aba const tabId = tabPane.id; const tab = document.querySelector(`button[data-bs-target="#${tabId}"]`); if (tab) { const bsTab = new bootstrap.Tab(tab); bsTab.show(); // Focar no campo inválido após a aba ser exibida setTimeout(() => { invalidField.focus(); }, 200); } } } return; } // Se chegou aqui, o formulário é válido // Obter ID do militante const militanteId = document.getElementById('edit_militante_id').value; if (!militanteId) { console.error('ID do militante não encontrado'); alert('Erro ao salvar: ID do militante não encontrado'); return; } // Criar FormData com todos os campos const formData = new FormData(form); // Garantir que o valor das responsabilidades seja enviado const responsabilidadesValue = document.getElementById('responsabilidades_values').value; formData.set('responsabilidades_valor', responsabilidadesValue); try { const url = `/militantes/editar/${militanteId}`; const csrfToken = document.querySelector('input[name="csrf_token"]').value; const response = await fetch(url, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': csrfToken }, body: formData }); if (!response.ok) { throw new Error(`Erro HTTP: ${response.status}`); } const data = await response.json(); if (data.status === 'success') { const modal = bootstrap.Modal.getInstance(document.getElementById('modalEditarMilitante')); modal.hide(); mostrarAlerta('Militante atualizado com sucesso!', 'success'); setTimeout(() => { location.reload(); }, 1000); } else { throw new Error(data.message || 'Erro desconhecido ao salvar militante'); } } catch (error) { console.error('Erro ao salvar:', error); mostrarAlerta(`Erro ao salvar militante: ${error.message}`, 'danger'); } }); } // Limpar alertas quando o modal for fechado modalEditarMilitante.addEventListener('hidden.bs.modal', function () { const alerts = this.querySelectorAll('.alert'); alerts.forEach(alert => alert.remove()); }); } else { console.error('Modal de edição não encontrado!'); } // Ajustar o formulário de novo militante const formNovoMilitante = document.getElementById('formNovoMilitante'); if (formNovoMilitante) { formNovoMilitante.addEventListener('submit', function(e) { e.preventDefault(); // Validar todas as datas antes do envio const camposData = this.querySelectorAll('.date-mask'); let datasValidas = true; camposData.forEach(campo => { const valor = campo.value; if (valor && !validarData(valor)) { datasValidas = false; $(campo).addClass('is-invalid'); if (!$(campo).next('.invalid-feedback').length) { $(campo).after('
Data inválida
'); } } }); if (!datasValidas) { return; // Não envia o formulário se houver datas inválidas } // Converter datas para formato ISO antes do envio camposData.forEach(campo => { if (campo.value) { campo.value = converterDataParaISO(campo.value); } }); const formData = new FormData(this); fetch(this.action, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': getCsrfToken() }, body: formData }) .then(response => response.json()) .then(data => { if (data.status === 'success') { // Fechar o modal const modal = bootstrap.Modal.getInstance(modalNovoMilitante); modal.hide(); // Limpar o formulário formNovoMilitante.reset(); // Adicionar o novo militante à tabela const tbody = document.querySelector('#militantesTable tbody'); const tr = document.createElement('tr'); tr.setAttribute('data-militante', data.militante.id); tr.setAttribute('data-filiado', data.militante.filiado ? 'sim' : 'nao'); tr.innerHTML = ` ${data.militante.nome} ${data.militante.cpf} ${data.militante.emails && data.militante.emails.length > 0 ? data.militante.emails[0].endereco_email : ''} ${data.militante.telefone1} ${data.militante.filiado ? 'Sim' : 'Não'}
`; // Inserir no início da tabela tbody.insertBefore(tr, tbody.firstChild); // Atualizar contador const countElement = document.getElementById('countMilitantes'); countElement.textContent = parseInt(countElement.textContent) + 1; // Mostrar mensagem de sucesso const alertDiv = document.createElement('div'); alertDiv.className = 'alert alert-success alert-dismissible fade show'; alertDiv.innerHTML = ` ${data.message} `; document.querySelector('.container').insertBefore(alertDiv, document.querySelector('.container').firstChild); } else { // Mostrar erro const alertDiv = document.createElement('div'); alertDiv.className = 'alert alert-danger alert-dismissible fade show'; alertDiv.innerHTML = ` ${data.message} `; document.querySelector('.modal-body').insertBefore(alertDiv, formNovoMilitante); } }) .catch(error => { console.error('Erro:', error); // Mostrar erro genérico const alertDiv = document.createElement('div'); alertDiv.className = 'alert alert-danger alert-dismissible fade show'; alertDiv.innerHTML = ` Erro ao cadastrar militante. Tente novamente. `; document.querySelector('.modal-body').insertBefore(alertDiv, formNovoMilitante); }); }); } // Máscara para CPF const cpfInputs = document.querySelectorAll('input[name="cpf"]'); cpfInputs.forEach(input => { input.addEventListener('input', function(e) { let value = e.target.value.replace(/\D/g, ''); if (value.length <= 11) { value = value.replace(/(\d{3})(\d)/, '$1.$2'); value = value.replace(/(\d{3})(\d)/, '$1.$2'); value = value.replace(/(\d{3})(\d{1,2})$/, '$1-$2'); e.target.value = value; } }); }); // Máscara para telefone const telefoneInputs = document.querySelectorAll('input[name="telefone1"], input[name="telefone2"]'); telefoneInputs.forEach(input => { input.addEventListener('input', function(e) { let value = e.target.value.replace(/\D/g, ''); if (value.length <= 11) { value = value.replace(/(\d{2})(\d)/, '($1) $2'); value = value.replace(/(\d{4,5})(\d{4})$/, '$1-$2'); e.target.value = value; } }); }); // Configuração do modal de exclusão const deleteModal = document.getElementById('deleteModal'); if (deleteModal) { deleteModal.addEventListener('show.bs.modal', function(event) { const button = event.relatedTarget; const militanteId = button.getAttribute('data-militante-id'); const militanteNome = button.getAttribute('data-militante-nome'); document.getElementById('militanteNome').textContent = militanteNome; document.getElementById('deleteForm').action = `/militantes/excluir/${militanteId}`; }); } // Ordenação const headers = document.querySelectorAll('#militantesTable th[data-sort]'); headers.forEach(header => { header.addEventListener('click', function() { const column = this.getAttribute('data-sort'); const tbody = document.querySelector('#militantesTable tbody'); const rows = Array.from(tbody.querySelectorAll('tr')); const isAsc = !this.classList.contains('sort-asc'); // Remover classes de ordenação de todos os headers headers.forEach(h => { h.classList.remove('sort-asc', 'sort-desc'); h.querySelector('i').className = 'fas fa-sort'; }); // Adicionar classe de ordenação ao header clicado this.classList.add(isAsc ? 'sort-asc' : 'sort-desc'); this.querySelector('i').className = `fas fa-sort-${isAsc ? 'up' : 'down'}`; // Ordenar linhas rows.sort((a, b) => { const aVal = a.querySelector(`td[data-${column}]`).getAttribute(`data-${column}`); const bVal = b.querySelector(`td[data-${column}]`).getAttribute(`data-${column}`); return isAsc ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal); }); // Reposicionar linhas rows.forEach(row => tbody.appendChild(row)); }); }); // Exportar para CSV const btnExportar = document.getElementById('btnExportar'); if (btnExportar) { btnExportar.addEventListener('click', function() { const rows = document.querySelectorAll('#militantesTable tbody tr:not([style*="display: none"])'); const headers = ['Nome', 'CPF', 'Email', 'Telefone', 'Filiado']; let csv = headers.join(',') + '\n'; rows.forEach(row => { const cols = row.querySelectorAll('td'); const values = [ cols[0].textContent, cols[1].textContent, cols[2].textContent, cols[3].textContent, cols[4].textContent.trim() ].map(val => `"${val}"`); csv += values.join(',') + '\n'; }); const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' }); const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.setAttribute('download', 'militantes.csv'); document.body.appendChild(link); link.click(); document.body.removeChild(link); }); } // Configurar máscaras de input // CEP const cepInputs = document.querySelectorAll('input[name="cep"]'); cepInputs.forEach(input => { input.addEventListener('input', function(e) { let value = e.target.value.replace(/\D/g, ''); if (value.length <= 8) { value = value.replace(/(\d{5})(\d)/, '$1-$2'); e.target.value = value; } }); // Buscar endereço pelo CEP input.addEventListener('blur', function(e) { const cep = e.target.value.replace(/\D/g, ''); if (cep.length === 8) { fetch(`https://viacep.com.br/ws/${cep}/json/`) .then(response => response.json()) .then(data => { if (!data.erro) { const form = input.closest('form'); form.querySelector('input[name="logradouro"]').value = data.logradouro; form.querySelector('input[name="bairro"]').value = data.bairro; form.querySelector('input[name="cidade"]').value = data.localidade; form.querySelector('select[name="estado"]').value = data.uf; } }); } }); }); // Título Eleitoral const tituloInputs = document.querySelectorAll('input[name="titulo_eleitoral"]'); tituloInputs.forEach(input => { input.addEventListener('input', function(e) { let value = e.target.value.replace(/\D/g, ''); if (value.length <= 12) { value = value.replace(/(\d{4})(\d)/, '$1 $2'); value = value.replace(/(\d{4})(\d)/, '$1 $2'); e.target.value = value; } }); }); // Inicializar tooltips do Bootstrap const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')); tooltipTriggerList.map(function (tooltipTriggerEl) { return new bootstrap.Tooltip(tooltipTriggerEl, { placement: 'top', trigger: 'hover' }); }); // Inicializar paginação updateVisibleRows(); updatePagination(); }); // Função para atualizar o valor total das responsabilidades function atualizarValorResponsabilidades() { const badges = document.querySelectorAll('.badge-clickable.active'); let valorTotal = 0; badges.forEach(badge => { const valor = parseInt(badge.getAttribute('data-value')); if (!isNaN(valor)) { valorTotal |= valor; } }); const input = document.getElementById('responsabilidades_values'); if (input) { input.value = valorTotal; } return valorTotal; } // Função para salvar as alterações do militante async function salvarAlteracoesMilitante(militanteId) { try { const form = document.getElementById('formEditarMilitante'); const formData = new FormData(form); // Adicionar responsabilidades let responsabilidadesValor = 0; form.querySelectorAll('input[name="responsabilidades"]:checked').forEach(checkbox => { responsabilidadesValor |= parseInt(checkbox.value); }); formData.append('responsabilidades_valor', responsabilidadesValor); const response = await fetch(`/militantes/editar/${militanteId}`, { method: 'POST', body: formData, headers: { 'X-CSRFToken': getCsrfToken() } }); const data = await response.json(); if (data.status === 'success') { mostrarAlerta(data.message, 'success'); setTimeout(() => { window.location.reload(); }, 1500); } else { mostrarAlerta(data.message || 'Erro ao salvar alterações', 'danger'); } } catch (error) { console.error('Erro ao salvar alterações:', error); mostrarAlerta('Erro ao salvar alterações. Por favor, tente novamente.', 'danger'); } }