Files
medods_vk/static/js/vk.js
T

154 lines
5.5 KiB
JavaScript

// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function () {
updateStatusIndicators();
});
// Обновление индикаторов статуса
function updateStatusIndicators() {
const vkStatus = document.getElementById('vkStatus');
const saveButton = document.getElementById('saveButton');
if (pageData && pageData.vk_settings) {
vkStatus.innerHTML = '<span class="badge bg-success"><i class="bi bi-check-circle me-1"></i>Настроено</span>';
saveButton.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Обновить настройки';
saveButton.classList.remove('btn-primary');
saveButton.classList.add('btn-outline-primary');
} else {
vkStatus.innerHTML = '<span class="badge bg-warning"><i class="bi bi-exclamation-triangle me-1"></i>Не настроено</span>';
saveButton.innerHTML = '<i class="bi bi-save me-1"></i>Сохранить настройки';
saveButton.classList.remove('btn-outline-primary');
saveButton.classList.add('btn-primary');
}
}
// Переключение видимости пароля
function togglePassword(inputId) {
const input = document.getElementById(inputId);
const button = input.nextElementSibling.querySelector('i');
if (input.type === 'password') {
input.type = 'text';
button.classList.remove('bi-eye');
button.classList.add('bi-eye-slash');
} else {
input.type = 'password';
button.classList.remove('bi-eye-slash');
button.classList.add('bi-eye');
}
}
// Сброс формы
function resetForm() {
document.getElementById('vkForm').reset();
updateStatusIndicators();
}
// Сохранение настроек VK
async function saveVkSettings() {
const access_token = document.getElementById('access_token').value.trim();
const group_id = document.getElementById('group_id').value.trim();
const base_photo_url = document.getElementById('base_photo_url').value.trim();
// Проверка обязательных полей
if (!access_token || !group_id) {
showAlert('warning', 'Заполните обязательные поля: Access Token и ID сообщества');
return;
}
// Проверка формата group_id (должно быть число)
if (!/^\d+$/.test(group_id)) {
showAlert('warning', 'ID сообщества должен содержать только цифры');
return;
}
const settings = {
access_token,
group_id,
base_photo_url: base_photo_url || null
};
if (pageData && pageData.vk_settings) {
settings.id = pageData.vk_settings.id;
}
try {
const response = await fetch('/settings/vk', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(settings)
});
if (response.ok) {
const data = await response.json();
showAlert('success', 'Настройки VK успешно сохранены!');
updateStatusIndicators();
// Перезагружаем страницу для отображения обновленных данных
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
const error = await response.text();
showAlert('danger', 'Ошибка сохранения: ' + error);
}
} catch (error) {
console.error('Ошибка:', error);
showAlert('danger', 'Ошибка сохранения настроек!');
}
}
// Вспомогательные функции для уведомлений
function showAlert(type, message) {
const alertContainer = document.getElementById('alertContainer');
// Создаем алерт
const alert = document.createElement('div');
alert.className = `alert alert-${type} alert-dismissible fade show shadow`;
// Иконка для типа алерта
const icon = getAlertIcon(type);
alert.innerHTML = `
<div class="d-flex align-items-center">
<i class="bi ${icon} me-2 fs-5"></i>
<div class="flex-grow-1">${message}</div>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
`;
alertContainer.appendChild(alert);
// Автоматическое удаление через 5 секунд
setTimeout(() => {
if (alert.parentNode) {
alert.classList.remove('show');
setTimeout(() => alert.remove(), 150);
}
}, 5000);
}
function getAlertIcon(type) {
const icons = {
'success': 'bi-check-circle-fill',
'warning': 'bi-exclamation-triangle-fill',
'danger': 'bi-x-circle-fill',
'info': 'bi-info-circle-fill'
};
return icons[type] || 'bi-info-circle-fill';
}
// Дополнительная проверка при вводе данных
document.getElementById('group_id').addEventListener('input', function (e) {
this.value = this.value.replace(/[^\d]/g, '');
});
// Подсказка для base_photo_url при фокусе
document.getElementById('base_photo_url').addEventListener('focus', function () {
if (!this.value) {
showAlert('info', 'Формат ID фото: photo_id (например: 7236456789)');
}
});