From abc551e31d62c988b8d13898511c9d1e3820e029 Mon Sep 17 00:00:00 2001 From: Professional Date: Fri, 23 May 2025 23:16:25 +0700 Subject: [PATCH] =?UTF-8?q?=D0=B8=D0=B7=D0=BC=D0=B5=D0=BD=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5=20=D1=80=D0=B5=D0=B4=D0=B0=D0=BA=D1=82=D0=B8=D1=80?= =?UTF-8?q?=D0=BE=D0=B2=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=BF=D1=80=D0=BE=D1=84?= =?UTF-8?q?=D0=B8=D0=BB=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/views/ProfileView.vue | 1163 +++++++++++-------------------------- 1 file changed, 337 insertions(+), 826 deletions(-) diff --git a/src/views/ProfileView.vue b/src/views/ProfileView.vue index 81099a2..954151e 100644 --- a/src/views/ProfileView.vue +++ b/src/views/ProfileView.vue @@ -107,13 +107,7 @@

Основная информация

-
- -
+
@@ -379,6 +373,7 @@ const loading = ref(true); const initialLoading = ref(true); const error = ref(''); const isEditMode = ref(false); +let originalProfileData = ''; // Для хранения исходных данных профиля в формате JSON // Для управления фото const photoActionLoading = ref(false); @@ -421,11 +416,25 @@ const mainPhoto = computed(() => { }); // Methods -const toggleEditMode = () => { - isEditMode.value = !isEditMode.value; - +const toggleEditMode = async () => { + // Если выходим из режима редактирования if (isEditMode.value) { - // При входе в режим редактирования копируем данные профиля в редактируемый объект + // Проверяем, были ли изменения + const hasChanges = checkForChanges(); + + if (hasChanges) { + // Если были изменения, автоматически сохраняем профиль + await saveProfileChanges(); + } + + // В любом случае переключаемся в режим просмотра + isEditMode.value = false; + clearProfileMessages(); + } else { + // При входе в режим редактирования + isEditMode.value = true; + + // Копируем данные профиля в редактируемый объект // Преобразуем формат даты из ISO в yyyy-MM-dd let formattedDate = ''; if (profileData.value.dateOfBirth) { @@ -449,13 +458,21 @@ const toggleEditMode = () => { } }; + // Сохраняем оригинальные данные для последующего сравнения + originalProfileData = JSON.stringify(editableProfileData.value); + // Устанавливаем поисковый запрос города if (profileData.value.location?.city) { citySearchQuery.value = profileData.value.location.city; } - } else { - // При выходе из режима редактирования сбрасываем ошибки и сообщения - clearProfileMessages(); + + // Устанавливаем поисковый запрос пола + if (profileData.value.gender) { + const genderOption = genderOptions.value.find(option => option.value === profileData.value.gender); + if (genderOption) { + genderSearchQuery.value = genderOption.text; + } + } } }; @@ -841,288 +858,108 @@ const saveProfileChanges = async () => { } }; -// Методы для работы с городами -const loadCities = async () => { - if (cities.length > 0) return; +const checkForChanges = () => { + // Сравниваем текущие редактируемые данные с оригинальными + const currentData = JSON.stringify(editableProfileData.value); + console.log('[ProfileView] Проверка изменений:'); + console.log('Оригинал:', originalProfileData); + console.log('Текущие:', currentData); + console.log('Есть изменения:', currentData !== originalProfileData); - try { - // Используем правильный путь к файлу для Vite - const response = await import('@/assets/russian-cities.json'); - const rawData = response.default || []; - - // Проверяем, что данные - массив - if (Array.isArray(rawData)) { - // Извлекаем названия городов из объектов - cities = rawData.map(city => { - // Проверяем, является ли city объектом и содержит ли поле name - return typeof city === 'object' && city !== null && city.name ? city.name : null; - }).filter(cityName => cityName !== null); // Удаляем null элементы - } else { - cities = []; - console.error('[ProfileView] Неверный формат данных городов:', typeof rawData); - } - - console.log('[ProfileView] Загружен список городов:', cities.length); - } catch (err) { - console.error('[ProfileView] Ошибка при загрузке списка городов:', err); - cities = []; // Инициализируем пустым массивом в случае ошибки - } + return currentData !== originalProfileData; }; - -const onCitySearch = () => { - if (!cities.length) { - loadCities(); - return; - } - - if (citySearchQuery.value.length < 2) { - filteredCities.value = []; - return; - } - - const query = citySearchQuery.value.toLowerCase().trim(); - filteredCities.value = cities - .filter(city => typeof city === 'string' && city.toLowerCase().includes(query)) - .slice(0, 10); // Ограничиваем количество результатов -}; - -const selectCity = (city) => { - console.log('[ProfileView] Выбран город:', city, typeof city); - citySearchQuery.value = city; - - if (!editableProfileData.value.location) { - editableProfileData.value.location = {}; - } - - editableProfileData.value.location.city = city; - showCityList.value = false; -}; - -const clearCitySelection = () => { - citySearchQuery.value = ''; - - if (editableProfileData.value.location) { - editableProfileData.value.location.city = ''; - } -}; - -// Методы для выбора пола -const onGenderSearch = () => { - filteredGenders.value = genderOptions.value.filter(option => - option.text.toLowerCase().includes(genderSearchQuery.value.toLowerCase()) - ); -}; - -const selectGender = (genderOption) => { - genderSearchQuery.value = genderOption.text; - editableProfileData.value.gender = genderOption.value; - showGenderList.value = false; -}; - -const clearGenderSelection = () => { - genderSearchQuery.value = ''; - editableProfileData.value.gender = ''; -}; - -const clearProfileMessages = () => { - profileActionError.value = ''; - profileActionSuccess.value = ''; -}; - -// Функция выхода из аккаунта -const logoutUser = async () => { - try { - await logout(); - console.log('[ProfileView] Пользователь успешно вышел из системы'); - } catch (error) { - console.error('[ProfileView] Ошибка при выходе из системы:', error); - } -}; - -watch(authUserFromStore, (newUser) => { - if (newUser) { - profileData.value = { ...newUser }; - console.log('[ProfileView] Данные профиля обновлены из authUserFromStore:', profileData.value); - } -}, { immediate: true, deep: true }); - -watch(profileData, (newData) => { - if (newData) { - editableProfileData.value = { ...newData }; - } -}, { immediate: true, deep: true }); - -// Lifecycle -onMounted(async () => { - if (!authUserFromStore.value || Object.keys(authUserFromStore.value).length === 0) { - await fetchProfileDataLocal(); - } else { - profileData.value = { ...authUserFromStore.value }; - loading.value = false; - initialLoading.value = false; - console.log('[ProfileView] Данные профиля уже были в хранилище:', profileData.value); - } -}); \ No newline at end of file +