forked from CIT/RehabilitationPatient
130 lines
4.8 KiB
Kotlin
130 lines
4.8 KiB
Kotlin
package com.example.rehabilitation
|
||
|
||
import android.os.Bundle
|
||
import android.view.LayoutInflater
|
||
import android.view.View
|
||
import android.view.ViewGroup
|
||
import androidx.fragment.app.Fragment
|
||
import androidx.lifecycle.ViewModelProvider
|
||
import androidx.navigation.fragment.findNavController
|
||
import com.example.rehabilitation.databinding.FragmentAuthBinding
|
||
import com.example.rehabilitation.Pref.ConclusionPref
|
||
import com.example.rehabilitation.Toast.showErrorToast
|
||
import com.example.rehabilitation.Toast.showSuccessToast
|
||
|
||
/**
|
||
* Фрагмент авторизации пользователя
|
||
* Отвечает за вход в систему и сохранение данных авторизации
|
||
*/
|
||
class AuthFragment : Fragment() {
|
||
// ViewBinding для доступа к элементам интерфейса
|
||
private var _binding: FragmentAuthBinding? = null
|
||
private val binding get() = _binding!!
|
||
|
||
// ViewModel для работы с данными авторизации
|
||
private lateinit var viewModel: AuthViewModel
|
||
|
||
// Класс для работы с настройками
|
||
private lateinit var conclusionPref: ConclusionPref
|
||
|
||
override fun onCreateView(
|
||
inflater: LayoutInflater,
|
||
container: ViewGroup?,
|
||
savedInstanceState: Bundle?
|
||
): View {
|
||
_binding = FragmentAuthBinding.inflate(inflater, container, false)
|
||
return binding.root
|
||
}
|
||
|
||
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
|
||
super.onViewCreated(view, savedInstanceState)
|
||
|
||
// Инициализация ViewModel и настроек
|
||
viewModel = ViewModelProvider(this)[AuthViewModel::class.java]
|
||
conclusionPref = ConclusionPref()
|
||
|
||
// Настройка обработчиков нажатий
|
||
setupClickListeners()
|
||
|
||
// Наблюдение за изменениями данных
|
||
observeViewModel()
|
||
}
|
||
|
||
/**
|
||
* Настройка обработчиков нажатий
|
||
*/
|
||
private fun setupClickListeners() {
|
||
// Обработка нажатия кнопки входа
|
||
binding.btnLogin.setOnClickListener {
|
||
val login = binding.etLogin.text.toString()
|
||
val password = binding.etPassword.text.toString()
|
||
|
||
if (validateInput(login, password)) {
|
||
viewModel.login(login, password)
|
||
}
|
||
}
|
||
|
||
// Обработка нажатия кнопки регистрации
|
||
binding.btnRegister.setOnClickListener {
|
||
findNavController().navigate(R.id.action_authFragment_to_registerFragment)
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Проверка введенных данных
|
||
* @param login Логин пользователя
|
||
* @param password Пароль пользователя
|
||
* @return true если данные валидны, false в противном случае
|
||
*/
|
||
private fun validateInput(login: String, password: String): Boolean {
|
||
if (login.isEmpty()) {
|
||
showErrorToast(requireContext(), "Введите логин")
|
||
return false
|
||
}
|
||
if (password.isEmpty()) {
|
||
showErrorToast(requireContext(), "Введите пароль")
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
|
||
/**
|
||
* Наблюдение за изменениями данных в ViewModel
|
||
*/
|
||
private fun observeViewModel() {
|
||
// Наблюдение за статусом загрузки
|
||
viewModel.isLoading.observe(viewLifecycleOwner) { isLoading ->
|
||
binding.progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
|
||
binding.btnLogin.isEnabled = !isLoading
|
||
}
|
||
|
||
// Наблюдение за результатом авторизации
|
||
viewModel.authResult.observe(viewLifecycleOwner) { result ->
|
||
result?.let {
|
||
if (it.success) {
|
||
// Сохранение данных авторизации
|
||
conclusionPref.saveToken(requireContext(), it.token)
|
||
conclusionPref.saveUserId(requireContext(), it.userId)
|
||
conclusionPref.saveLoginStatus(requireContext(), true)
|
||
|
||
showSuccessToast(requireContext(), "Успешный вход")
|
||
findNavController().navigate(R.id.action_authFragment_to_mainFragment)
|
||
} else {
|
||
showErrorToast(requireContext(), it.message)
|
||
}
|
||
}
|
||
}
|
||
|
||
// Наблюдение за ошибками
|
||
viewModel.error.observe(viewLifecycleOwner) { error ->
|
||
error?.let {
|
||
showErrorToast(requireContext(), it)
|
||
}
|
||
}
|
||
}
|
||
|
||
override fun onDestroyView() {
|
||
super.onDestroyView()
|
||
_binding = null
|
||
}
|
||
} |