using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using VeterinaryContracts.BindingModels;
using VeterinaryContracts.ViewModels;
using VeterinaryShowOwnerApp.Models;
using VeterinaryShowOwnerApp;
using System.Reflection;
using VeterinaryDataModels.Models;
using VeterinaryContracts.SearchModels;
using Microsoft.Extensions.Hosting;
using System.Globalization;

namespace VeterinaryShowOwnerApp.Controllers
{
	public class HomeController : Controller
	{
		private readonly ILogger<HomeController> _logger;

		public HomeController(ILogger<HomeController> logger)
		{
			_logger = logger;
		}

		public IActionResult Index()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			return
			View(APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerId={APIOwner.Owner.Id}"));
		}
		[HttpGet]
		public IActionResult Privacy()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIOwner.Owner);
		}
		[HttpPost]
		public void Privacy(string login, string password, string fio)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(login) ||
			string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
			{
				throw new Exception("Введите логин, пароль и ФИО");
			}
			APIOwner.PostRequest("api/owner/updatedata", new OwnerBindingModel
			{
				Id = APIOwner.Owner.Id,
				OwnerFIO = fio,
				Login = login,
				Password = password
			});
			APIOwner.Owner.OwnerFIO = fio;
			APIOwner.Owner.Login = login;
			APIOwner.Owner.Password = password;
			Response.Redirect("Index");
		}
		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
		{
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
		}
		[HttpGet]
		public IActionResult Enter()
		{
			return View();
		}
		[HttpPost]
		public void Enter(string login, string password)
		{
			if (string.IsNullOrEmpty(login) ||
			string.IsNullOrEmpty(password))
			{
				throw new Exception("Введите логин и пароль");
			}
			APIOwner.Owner = APIOwner.GetRequest<OwnerViewModel>($"api/owner/login?login={login}&password={password}");
			if (APIOwner.Owner == null)
			{
				throw new Exception("Неверный логин/пароль");
			}
			Response.Redirect("Index");
		}
		[HttpGet]
		public IActionResult Register()
		{
			return View();
		}
		[HttpPost]
		public void Register(string login, string password, string fio)
		{
			if (string.IsNullOrEmpty(login) ||
			string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
			{
				throw new Exception("Введите логин, пароль и ФИО");
			}
			APIOwner.PostRequest("api/owner/register", new
			OwnerBindingModel
			{
				OwnerFIO = fio,
				Login = login,
				Password = password
			});
			Response.Redirect("Enter");
			return;
		}
		[HttpGet]
		public IActionResult Pets()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerid={APIOwner.Owner.Id}"));
		}
		public IActionResult CreatePet()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View();
		}
		[HttpPost]
		public void CreatePet(string name, string type, string breed, string gender)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(breed) || string.IsNullOrEmpty(gender))
			{
				throw new Exception("Ошибка в введённых данных");
			}
			APIOwner.PostRequest("api/pet/createpet", new PetBindingModel
			{
				PetName = name,
				PetType = type,
				PetBreed = breed,
				PetGender = gender,
				OwnerId = APIOwner.Owner.Id
			});
			Response.Redirect("Index");
		}
		public IActionResult DeletePet()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Pets = APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerid={APIOwner.Owner.Id}");
			return View();
		}
		[HttpPost]
		public void DeletePet(int pet)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIOwner.PostRequest("api/pet/deletepet", new PetBindingModel
			{
				Id = pet
			});
			Response.Redirect("Index");
		}
		public IActionResult UpdatePet()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Pets = APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerid={APIOwner.Owner.Id}");
			return View();
		}
		[HttpPost]
		public void UpdatePet(int pet, string name, string type, string breed, string gender)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(type) || string.IsNullOrEmpty(breed) || string.IsNullOrEmpty(gender))
			{
				throw new Exception("Ошибка введённых данных");
			}
			APIOwner.PostRequest("api/pet/updatepet", new PetBindingModel
			{
				Id = pet,
				PetName = name,
				PetType = type,
				PetBreed = breed,
				PetGender = gender,
			});
			Response.Redirect("Index");
		}
		[HttpGet]
		public Tuple<PetViewModel, List<string>>? GetPet(int petId)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			var result = APIOwner.GetRequest<Tuple<PetViewModel, List<string>>>($"api/pet/getpet?petid={petId}");
			if (result == null)
			{
				return default;
			}
			return result;
		}
		[HttpGet]
		public IActionResult Visits()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIOwner.GetRequest<List<VisitViewModel>>($"api/visit/getallvisits?ownerid={APIOwner.Owner.Id}"));
		}
		public IActionResult CreateVisit()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Pets = APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerid={APIOwner.Owner.Id}");
			ViewBag.Doctors = APIOwner.GetRequest<List<DoctorViewModel>>($"api/doctor/getdoctors");

			return View();
		}
		[HttpPost]
		public void CreateVisit(string name, List<int> pets, DateTime dateTime, int doctor)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || dateTime < DateTime.Now)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			Dictionary<int, IPetModel> a = new Dictionary<int, IPetModel>();
			foreach (int pet in pets)
			{
				a.Add(pet, new PetSearchModel { Id = pet } as IPetModel);
			}
			APIOwner.PostRequest("api/visit/createvisit", new VisitBindingModel
			{
				VisitName = name,
				VisitPet = a,
				DateVisit = dateTime,
				DoctorId = doctor,
				OwnerId = APIOwner.Owner.Id,
			});
			Response.Redirect("Visits");
		}
		public IActionResult DeleteVisit()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Visits = APIOwner.GetRequest<List<VisitViewModel>>($"api/visit/getvisits?ownerid={APIOwner.Owner.Id}");
			return View();
		}

		[HttpPost]
		public void DeleteVisit(int visit)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIOwner.PostRequest("api/visit/deletevisit", new VisitBindingModel
			{
				Id = visit
			});
			Response.Redirect("Index");
		}
		public IActionResult UpdateVisit()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Visits = APIOwner.GetRequest<List<VisitViewModel>>($"api/visit/getvisits?ownerid={APIOwner.Owner.Id}");
			return View();
		}

		[HttpPost]
		public void UpdateVisit(int visit, string name)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name))
			{
				throw new Exception("Ошибка в введенных данных");
			}
			APIOwner.PostRequest("api/visit/updatevisit", new VisitBindingModel
			{
				Id = visit,
				VisitName = name,
				OwnerId = APIOwner.Owner.Id,
			});
			Response.Redirect("Visits");
		}
		[HttpGet]
		public Tuple<VisitViewModel, List<Tuple<string, int>>>? GetVisit(int visitId)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			var result = APIOwner.GetRequest<Tuple<VisitViewModel, List<Tuple<string>>>>($"api/visit/getvisit?visitid={visitId}");
			if (result == null)
			{
				return default;
			}
			string table = "";
			result.Item1.VisitPet.Clear();
			for (int i = 0; i < result.Item2.Count; i++)
			{
				var pet = result.Item2[i].Item1;
				table += "<tr>";
				table += $"<td>{pet}</td>";
				table += "</tr>";
			}
			//return Tuple.Create(result.Item1, table);
			return null;
		}
		public IActionResult Purchases()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIOwner.GetRequest<List<PurchaseViewModel>>($"api/purchase/getpurchases?ownerid={APIOwner.Owner.Id}"));

		}
		public IActionResult CreatePurchase()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Pets = APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerid={APIOwner.Owner.Id}");
			ViewBag.Drugs = APIOwner.GetRequest<List<DrugViewModel>>($"api/drug/getdrugs?doctorid={null}");
			return View();
		}
		[HttpPost]
		public void CreatePurchase(int drug, List<int> pets, int count)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (count <= 0)
			{
				throw new Exception("Количество должно быть выше 0");
			}
			Dictionary<int, IPetModel> a = new Dictionary<int, IPetModel>();
			foreach (int pet in pets)
			{
				a.Add(pet, new PetSearchModel { Id = pet } as IPetModel);
			}
			APIOwner.PostRequest("api/purchase/createpurchase", new PurchaseBindingModel
			{
				OwnerId = APIOwner.Owner.Id,
				DrugId = drug,
				PurchasePet = a,
				Sum = Calc(count, drug),
				DateCreate = DateTime.Now,
				Count = count
			});
			Response.Redirect("Purchases");
		}
		[HttpPost]
		public double Calc(int count, int drug)
		{
			var price = APIOwner.GetRequest<DrugViewModel>($"api/drug/getonedrug?drugId={drug}");
			return count * (price?.Price ?? 1);
		}
		
		[HttpGet]
		public Tuple<PurchaseViewModel, List<string>>? GetPurchase(int purchaseId)
		{
			if (APIOwner.Owner == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			var result = APIOwner.GetRequest<Tuple<PurchaseViewModel, List<string>>>($"api/purchase/getpurchase?purchaseid={purchaseId}");
			if (result == null)
			{
				return default;
			}
			return result;
		}
		[HttpGet]
		public IActionResult ServicePetReport()
		{
			if (APIOwner.Owner == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Pets = APIOwner.GetRequest<List<PetViewModel>>($"api/pet/getpets?ownerid={APIOwner.Owner.Id}");
			return View();
		}
        [HttpPost]
        public void ServicePetReport(List<int> pets, string type)
        {
            if (APIOwner.Owner == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }

            if (pets.Count <= 0)
            {
                throw new Exception("Количество должно быть больше 0");
            }

            if (string.IsNullOrEmpty(type))
            {
                throw new Exception("Неверный тип отчета");
            }

            if (type == "docx")
            {
                APIOwner.PostRequest("api/reportowner/createservicelistwordfile", new ReportServicesBindingModel
                {
                    Pets = pets,
                    FileName = "C:\\Users\\1\\Downloads\\wordfile.docx"
				});
                Response.Redirect("GetWordFile");
            }
            else
            {
                APIOwner.PostRequest("api/reportowner/createservicelistexcelfile", new ReportServicesBindingModel
                {
                    Pets = pets,
                    FileName = "C:\\Users\\1\\Downloads\\excelfile.xlsx"
				});
                Response.Redirect("GetExcelFile");
            }
        }

		[HttpGet]
		public IActionResult GetWordFile()
		{
			return new PhysicalFileResult("C:\\Users\\1\\Downloads\\wordfile.docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
		}

		public IActionResult GetExcelFile()
		{
			return new PhysicalFileResult("C:\\Users\\1\\Downloads\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		}
		[HttpGet]
        public IActionResult Report()
        {
            ViewBag.Report = new List<ReportVisitsDrugsBindingModel>();
            return View();
        }
        [HttpGet]
        public string GetPetsReport(DateTime dateFrom, DateTime dateTo)
        {
            if (APIOwner.Owner == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            List<ReportVisitsDrugsViewModel> result;
            try
            {
                string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
                string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
                result = APIOwner.GetRequest<List<ReportVisitsDrugsViewModel>>
                    ($"api/reportowner/getvisitsdrugsreport?datefrom={dateFromS}&dateto={dateToS}&ownerid={APIOwner.Owner.Id}")!;

            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Ошибка создания отчета");
                throw;
            }
            string table = "";
            table += "<h2 class=\"text-custom-color-1\">Предварительный отчет</h2>";
            table += "<div class=\"table-responsive\">";
            table += "<table class=\"table table-striped table-bordered table-hover\">";
            table += "<thead class=\"table-dark\">";
            table += "<tr>";
            table += "<th scope=\"col\">Дата</th>";
            table += "<th scope=\"col\">Животное</th>";
            table += "<th scope=\"col\">Название посещенияы</th>";
            table += "<th scope=\"col\">Лекарство</th>";
            table += "</tr>";
            table += "</thead>";
            foreach (var medication in result)
            {
                table += "<tbody>";
                table += "<tr>";
                table += $"<td></td>";
                table += $"<td>{medication.PetName}</td>";
                table += $"<td></td>";
                table += $"<td></td>";
                table += "</tr>";
                foreach (var visit in medication.Visits)
                {
                    table += "<tr>";
                    table += $"<td>{visit.DateVisit}</td>";
                    table += $"<td></td>";
					table += $"<td>{visit.VisitName}</td>";
					table += $"<td></td>";
                    table += "</tr>";
                }
                foreach (var drug in medication.Drugs)
                {
                    table += "<tr>";
                    table += $"<td>{drug.DateCreate}</td>";
                    table += $"<td></td>";
                    table += $"<td></td>";
					table += $"<td>{drug.DrugName}</td>";
					table += "</tr>";
                }
                table += "</tbody>";
            }
            table += "</table>";
            table += "</div>";
            return table;
        }

        [HttpPost]
        public void Report(DateTime dateFrom, DateTime dateTo)
        {
            if (APIOwner.Owner == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            APIOwner.PostRequest("api/reportowner/sendvisitsdrugsreporttoemail", new ReportVisitsDrugsBindingModel
            {
                FileName = "C:\\Users\\niyaz\\Downloads\\pdffile.pdf",
                OwnerId = APIOwner.Owner.Id,
                DateFrom = dateFrom,
                DateTo = dateTo,
                Email = APIOwner.Owner.Login

            });
            Response.Redirect("Report");

        }
    }
}