using Microsoft.AspNetCore.Mvc; using VeterinaryClinicContracts.BindingModels; using VeterinaryClinicContracts.BusinessLogicsContracts; using VeterinaryClinicContracts.SearchModels; using VeterinaryClinicDataModels.Models; namespace VeterinaryClinicWebApp.Controllers { public class AnimalController : Controller { private readonly ILogger _logger; private readonly IAnimalLogic _animalLogic; private readonly IMedicationLogic _medicationLogic; public AnimalController(ILogger logger, IAnimalLogic animalLogic, IMedicationLogic medicationLogic) { _logger = logger; _animalLogic = animalLogic; _medicationLogic = medicationLogic; } /// /// Вывести список животных /// [HttpGet] public IActionResult Animals() { if (APIClient.User == null) { return Redirect("~/Home/Enter"); } return View(_animalLogic.ReadList(new AnimalSearchModel { UserId = APIClient.User.Id, })); } /// /// Создать животного /// [HttpGet] public IActionResult CreateAnimal() { if (APIClient.User == null) { return Redirect("~/Home/Enter"); } ViewBag.Medications = _medicationLogic.ReadList(null); return View(); } [HttpPost] public void CreateAnimal(string type, string breed, int age, List medication) { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(breed) || age < 0 || medication == null) { throw new Exception("Введены не все данные!"); } Dictionary animalMedication = new Dictionary(); foreach (var medicationId in medication) { animalMedication.Add(medicationId, _medicationLogic.ReadElement(new MedicationSearchModel { Id = medicationId })!); } _animalLogic.Create(new AnimalBindingModel { Type = type, Breed = breed, Age = age, AnimalMedications = animalMedication, UserId = APIClient.User.Id }); Response.Redirect("/Animal/Animals"); } /// /// Редактировать животного /// [HttpGet] public IActionResult UpdateAnimal(int id) { if (APIClient.User == null) { return Redirect("~/Home/Enter"); } ViewBag.Medications = _medicationLogic.ReadList(null); return View(_animalLogic.ReadElement(new AnimalSearchModel { Id = id })); } [HttpPost] public void UpdateAnimal(int id, string type, string breed, int age, List medication) { if (APIClient.User == null) { throw new Exception("Необходимо авторизоваться!"); } if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(breed) || age < 0 || medication == null) { throw new Exception("Введены не все данные!"); } Dictionary animalMedication = new Dictionary(); foreach (var medicationId in medication) { animalMedication.Add(medicationId, _medicationLogic.ReadElement(new MedicationSearchModel { Id = medicationId })!); } _animalLogic.Update(new AnimalBindingModel { Id = id, Type = type, Breed = breed, Age = age, AnimalMedications = animalMedication, UserId = APIClient.User.Id }); Response.Redirect("/Animal/Animals"); } /// /// Удалить животного /// } }