Reflex/src/views/ProfileView.vue

238 lines
10 KiB
Vue
Raw Normal View History

2025-05-21 22:13:09 +07:00
<template>
<div class="profile-view container mt-4">
<h2>Мой профиль</h2>
<div v-if="loading && initialLoading" class="d-flex justify-content-center my-3">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Загрузка...</span>
</div>
</div>
<div v-if="error" class="alert alert-danger">{{ error }}</div>
<div v-if="profileData && !initialLoading" class="card mb-4">
<div class="card-body">
<h5 class="card-title">Привет, {{ profileData.name }}!</h5>
<p class="card-text"><strong>ID:</strong> {{ profileData._id }}</p>
<p class="card-text"><strong>Email:</strong> {{ profileData.email }}</p>
<p class="card-text"><strong>Дата регистрации:</strong> {{ formatDate(profileData.createdAt) }}</p>
<p v-if="profileData.dateOfBirth" class="card-text"><strong>Дата рождения:</strong> {{ formatDate(profileData.dateOfBirth) }}</p>
<p v-if="profileData.gender" class="card-text"><strong>Пол:</strong> {{ profileData.gender === 'male' ? 'Мужской' : profileData.gender === 'female' ? 'Женский' : 'Другой' }}</p>
<p v-if="profileData.bio" class="card-text"><strong>О себе:</strong> {{ profileData.bio }}</p>
<!-- Добавь другие поля -->
</div>
</div>
<!-- Отображение фотографий пользователя -->
<div v-if="profileData && profileData.photos && profileData.photos.length > 0 && !initialLoading" class="card mb-4">
<div class="card-body">
<h5 class="card-title">Мои фотографии</h5>
2025-05-21 23:43:24 +07:00
<p v-if="photoActionError" class="alert alert-danger">{{ photoActionError }}</p>
<p v-if="photoActionSuccess" class="alert alert-success">{{ photoActionSuccess }}</p>
2025-05-21 22:13:09 +07:00
<div class="row">
2025-05-21 23:43:24 +07:00
<div v-for="photo in profileData.photos" :key="photo.public_id || photo._id" class="col-md-4 mb-3">
<div class="photo-container position-relative">
<img :src="photo.url" class="img-fluid img-thumbnail" alt="Фото пользователя">
<div class="photo-actions position-absolute bottom-0 start-0 end-0 p-2 bg-dark bg-opacity-50">
<button
@click="setAsMainPhoto(photo._id)"
class="btn btn-sm btn-light me-1"
:disabled="photo.isProfilePhoto || photoActionLoading"
title="Сделать главной">
<i class="bi" :class="{'bi-star-fill text-warning': photo.isProfilePhoto, 'bi-star': !photo.isProfilePhoto}"></i>
</button>
<button
@click="confirmDeletePhoto(photo._id)"
class="btn btn-sm btn-danger"
:disabled="photoActionLoading"
title="Удалить фото">
<i class="bi bi-trash"></i>
</button>
</div>
<span v-if="photo.isProfilePhoto" class="badge bg-primary position-absolute top-0 start-0 m-1">Главная</span>
</div>
2025-05-21 22:13:09 +07:00
</div>
</div>
</div>
</div>
<div v-else-if="profileData && (!profileData.photos || profileData.photos.length === 0) && !initialLoading" class="alert alert-info">
У вас пока нет загруженных фотографий.
</div>
<!-- Форма редактирования профиля -->
<EditProfileForm v-if="isAuthenticated && !initialLoading" />
<!-- Показываем форму, если пользователь аутентифицирован и начальная загрузка завершена -->
<div v-if="!profileData && !initialLoading && !error" class="alert alert-warning">
<p>Не удалось загрузить данные профиля. Возможно, вы не авторизованы или произошла ошибка.</p>
<router-link to="/login" class="btn btn-primary">Войти</router-link>
</div>
2025-05-21 23:43:24 +07:00
<!-- Модальное окно подтверждения удаления -->
<div class="modal fade" id="deletePhotoModal" tabindex="-1" aria-labelledby="deletePhotoModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="deletePhotoModalLabel">Подтвердить удаление</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
Вы уверены, что хотите удалить эту фотографию?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-danger" @click="executeDeletePhoto" :disabled="photoActionLoading">
<span v-if="photoActionLoading" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Удалить
</button>
</div>
</div>
</div>
</div>
2025-05-21 22:13:09 +07:00
</div>
</template>
<script setup>
import { ref, onMounted, computed, watch } from 'vue'; // Добавлен watch
import { useAuth } from '@/auth';
import api from '@/services/api';
2025-05-21 23:43:24 +07:00
// import router from '@/router'; // Закомментировано, так как router не используется напрямую
2025-05-21 22:13:09 +07:00
import EditProfileForm from '@/components/EditProfileForm.vue';
2025-05-21 23:43:24 +07:00
import { Modal } from 'bootstrap'; // Импортируем Modal
2025-05-21 22:13:09 +07:00
2025-05-21 23:43:24 +07:00
const { isAuthenticated, user: authUserFromStore, token, fetchUser } = useAuth();
2025-05-21 22:13:09 +07:00
const profileData = ref(null);
const loading = ref(true);
const initialLoading = ref(true);
const error = ref('');
2025-05-21 23:43:24 +07:00
// Для управления фото
const photoActionLoading = ref(false);
const photoActionError = ref('');
const photoActionSuccess = ref('');
const photoToDeleteId = ref(null);
let deleteModalInstance = null;
2025-05-21 22:13:09 +07:00
const fetchProfileDataLocal = async () => {
loading.value = true;
error.value = '';
if (!isAuthenticated.value || !token.value) {
error.value = "Вы не авторизованы для просмотра этой страницы.";
loading.value = false;
initialLoading.value = false;
return;
}
try {
await fetchUser();
} catch (err) {
console.error('[ProfileView] Ошибка при вызове fetchUser:', err);
error.value = (err.response && err.response.data && err.response.data.message)
? err.response.data.message
: 'Не удалось загрузить данные профиля. Попробуйте позже.';
} finally {
loading.value = false;
initialLoading.value = false;
}
};
watch(authUserFromStore, (newUser) => {
if (newUser) {
2025-05-21 23:43:24 +07:00
profileData.value = { ...newUser };
2025-05-21 22:13:09 +07:00
console.log('[ProfileView] Данные профиля обновлены из authUserFromStore:', profileData.value);
}
2025-05-21 23:43:24 +07:00
}, { immediate: true, deep: true });
2025-05-21 22:13:09 +07:00
2025-05-21 23:43:24 +07:00
onMounted(async () => {
2025-05-21 22:13:09 +07:00
if (!authUserFromStore.value || Object.keys(authUserFromStore.value).length === 0) {
2025-05-21 23:43:24 +07:00
await fetchProfileDataLocal();
2025-05-21 22:13:09 +07:00
} else {
2025-05-21 23:43:24 +07:00
profileData.value = { ...authUserFromStore.value };
loading.value = false;
initialLoading.value = false;
console.log('[ProfileView] Данные профиля уже были в хранилище:', profileData.value);
}
// Инициализация модального окна
const modalElement = document.getElementById('deletePhotoModal');
if (modalElement) {
deleteModalInstance = new Modal(modalElement);
2025-05-21 22:13:09 +07:00
}
});
const formatDate = (dateString) => {
if (!dateString) return '';
const options = { year: 'numeric', month: 'long', day: 'numeric' };
return new Date(dateString).toLocaleDateString(undefined, options);
};
2025-05-21 23:43:24 +07:00
const setAsMainPhoto = async (photoId) => {
photoActionLoading.value = true;
photoActionError.value = '';
photoActionSuccess.value = '';
try {
const response = await api.setMainPhoto(photoId);
await fetchUser(); // Обновляем данные пользователя (и profileData через watch)
photoActionSuccess.value = response.data.message || 'Главное фото обновлено.';
} catch (err) {
console.error('[ProfileView] Ошибка при установке главного фото:', err);
photoActionError.value = err.response?.data?.message || 'Не удалось установить главное фото.';
} finally {
photoActionLoading.value = false;
}
};
const confirmDeletePhoto = (photoId) => {
photoToDeleteId.value = photoId;
if (deleteModalInstance) {
deleteModalInstance.show();
}
};
const executeDeletePhoto = async () => {
if (!photoToDeleteId.value) return;
photoActionLoading.value = true;
photoActionError.value = '';
photoActionSuccess.value = '';
try {
const response = await api.deletePhoto(photoToDeleteId.value);
await fetchUser(); // Обновляем данные пользователя
photoActionSuccess.value = response.data.message || 'Фотография удалена.';
} catch (err) {
console.error('[ProfileView] Ошибка при удалении фото:', err);
photoActionError.value = err.response?.data?.message || 'Не удалось удалить фотографию.';
} finally {
photoActionLoading.value = false;
if (deleteModalInstance) {
deleteModalInstance.hide();
}
photoToDeleteId.value = null;
}
};
2025-05-21 22:13:09 +07:00
</script>
<style scoped>
.profile-view {
max-width: 700px;
margin: auto;
}
.spinner-border {
width: 3rem;
height: 3rem;
}
.img-thumbnail {
border: 1px solid #dee2e6;
padding: 0.25rem;
background-color: #fff;
border-radius: 0.25rem;
2025-05-21 23:43:24 +07:00
max-width: 100%;
height: auto;
}
.photo-container .photo-actions {
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.photo-container:hover .photo-actions {
opacity: 1;
2025-05-21 22:13:09 +07:00
}
</style>