174 lines
6.8 KiB
JavaScript
174 lines
6.8 KiB
JavaScript
let currentPage = 1;
|
||
let totalPages = 1;
|
||
const perPage = 20;
|
||
|
||
// Функция загрузки пользователей
|
||
function loadUsers(page) {
|
||
if (page < 1 || page > totalPages) return;
|
||
currentPage = page;
|
||
|
||
fetch(`/telezab/rest/api/users?page=${currentPage}&per_page=${perPage}`)
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
totalPages = data.total_pages;
|
||
updateUsersTable(data.users);
|
||
updatePagination(data.current_page, data.total_pages);
|
||
})
|
||
.catch(error => {
|
||
console.error('Error fetching users:', error);
|
||
});
|
||
}
|
||
|
||
// Функция обновления таблицы пользователей
|
||
function updateUsersTable(users) {
|
||
const tableBody = document.getElementById('users-table').querySelector('tbody');
|
||
tableBody.innerHTML = '';
|
||
|
||
users.forEach(user => {
|
||
const row = document.createElement('tr');
|
||
row.innerHTML = `
|
||
<td>${user.id}</td>
|
||
<td>${user.username}</td>
|
||
<td>${user.email}</td>
|
||
<td>${user.subscriptions.join(', ') || 'Нет подписок'}</td>
|
||
<td>${user.disaster_only}</td>
|
||
<td>${user.status}</td>
|
||
<td><button class="btn btn-primary editUserBtn" data-id="${user.id}">Редактировать</button></td>
|
||
`;
|
||
tableBody.appendChild(row);
|
||
});
|
||
|
||
setupEditButtons();
|
||
}
|
||
|
||
// Функция для обработки кнопок "Редактировать"
|
||
function setupEditButtons() {
|
||
document.querySelectorAll(".editUserBtn").forEach(button => {
|
||
button.addEventListener("click", function () {
|
||
const userId = this.dataset.id;
|
||
openUserModal(userId);
|
||
});
|
||
});
|
||
}
|
||
|
||
// Функция открытия модального окна
|
||
function openUserModal(userId) {
|
||
fetch(`/telezab/rest/api/users/${userId}`)
|
||
.then(response => response.json())
|
||
.then(data => {
|
||
document.getElementById("userId").innerText = data.id;
|
||
document.getElementById("username").innerText = data.username;
|
||
document.getElementById("userEmail").innerText = data.email;
|
||
|
||
const blockBtn = document.getElementById("toggleBlockUser");
|
||
blockBtn.innerText = data.blocked ? "Разблокировать" : "Заблокировать";
|
||
blockBtn.onclick = function () {
|
||
toggleUserBlock(userId);
|
||
};
|
||
|
||
document.getElementById("viewUserEvents").onclick = function () {
|
||
viewUserEvents(userId);
|
||
};
|
||
|
||
document.getElementById("deleteUser").onclick = function () {
|
||
deleteUser(userId);
|
||
};
|
||
|
||
// Использование Bootstrap для показа модального окна
|
||
var myModal = new bootstrap.Modal(document.getElementById('userModal'), {
|
||
keyboard: false
|
||
});
|
||
myModal.show(); // Открытие модального окна
|
||
})
|
||
.catch(error => {
|
||
console.error('Error fetching user data:', error);
|
||
});
|
||
}
|
||
|
||
// Обработчик закрытия модального окна
|
||
document.querySelector(".btn-close").addEventListener("click", function () {
|
||
var myModal = new bootstrap.Modal(document.getElementById('userModal'));
|
||
myModal.hide(); // Закрытие модального окна
|
||
});
|
||
|
||
|
||
// Функция для блокировки/разблокировки пользователя
|
||
function toggleUserBlock(userId) {
|
||
fetch(`/telezab/rest/api/users/${userId}/block`, { method: "POST" })
|
||
.then(() => {
|
||
alert("Статус пользователя изменён");
|
||
|
||
// Скрыть модальное окно с помощью Bootstrap (это не отменяет событий закрытия)
|
||
var myModal = new bootstrap.Modal(document.getElementById('userModal'));
|
||
myModal.hide(); // Закрытие модального окна
|
||
|
||
loadUsers(currentPage); // Перезагрузите список пользователей
|
||
})
|
||
.catch(error => {
|
||
console.error("Ошибка при изменении статуса пользователя:", error);
|
||
});
|
||
}
|
||
|
||
|
||
// Функция просмотра действий пользователя
|
||
function viewUserEvents(userId) {
|
||
window.location.href = `/telezab/rest/api/users/${userId}/events`;
|
||
}
|
||
|
||
// Функция для удаления пользователя
|
||
function deleteUser(userId) {
|
||
if (confirm("Вы уверены, что хотите удалить пользователя?")) {
|
||
fetch(`/telezab/rest/api/users/${userId}`, { method: "DELETE" })
|
||
.then(() => {
|
||
alert("Пользователь удалён");
|
||
var myModal = new bootstrap.Modal(document.getElementById('userModal'));
|
||
myModal.hide();
|
||
loadUsers(currentPage); // Перезагрузите список пользователей
|
||
});
|
||
}
|
||
}
|
||
|
||
window.onclick = function (event) {
|
||
if (event.target === document.getElementById("userModal")) {
|
||
$('#userModal').modal('hide'); // Закрываем модальное окно с помощью Bootstrap
|
||
}
|
||
};
|
||
|
||
// Функция обновления пагинации
|
||
function updatePagination(currentPage, totalPages) {
|
||
const paginationContainer = document.getElementById('pagination');
|
||
paginationContainer.innerHTML = '';
|
||
|
||
const prevButton = document.createElement('li');
|
||
prevButton.classList.add('page-item');
|
||
prevButton.classList.toggle('disabled', currentPage === 1);
|
||
prevButton.innerHTML = `<a class="page-link" href="#" aria-label="Previous" onclick="loadUsers(${currentPage - 1})">«</a>`;
|
||
paginationContainer.appendChild(prevButton);
|
||
|
||
for (let page = 1; page <= totalPages; page++) {
|
||
const pageItem = document.createElement('li');
|
||
pageItem.classList.add('page-item');
|
||
pageItem.classList.toggle('active', page === currentPage);
|
||
|
||
const pageLink = document.createElement('a');
|
||
pageLink.classList.add('page-link');
|
||
pageLink.href = "#";
|
||
pageLink.textContent = page;
|
||
pageLink.onclick = () => loadUsers(page);
|
||
|
||
pageItem.appendChild(pageLink);
|
||
paginationContainer.appendChild(pageItem);
|
||
}
|
||
|
||
const nextButton = document.createElement('li');
|
||
nextButton.classList.add('page-item');
|
||
nextButton.classList.toggle('disabled', currentPage === totalPages);
|
||
nextButton.innerHTML = `<a class="page-link" href="#" aria-label="Next" onclick="loadUsers(${currentPage + 1})">»</a>`;
|
||
paginationContainer.appendChild(nextButton);
|
||
}
|
||
|
||
// Запуск загрузки данных
|
||
document.addEventListener("DOMContentLoaded", () => {
|
||
loadUsers(currentPage);
|
||
});
|