using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using PharmacistApp.Models;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using VetClinicContracts.BindingModels;
using VetClinicContracts.BusinessLogicsContracts;
using VetClinicContracts.SearchModels;
using VetClinicContracts.ViewModels;
using VetClinicDataBaseImplement.Implements;
using VetClinicDataBaseImplement.Models;
using VetClinicDataModels.Models;

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

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

		public IActionResult Index()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			return
View(APIPharmacist.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines?pharmacistid={APIPharmacist.Pharmacist.Id}"));

		}

		[HttpGet]
		public IActionResult Privacy()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIPharmacist.Pharmacist);
		}

		[HttpPost]
		public void Privacy(string email, string password, string fio)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(email) ||
			string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
			{
				throw new Exception("Введите email, пароль и ФИО");
			}
			APIPharmacist.PostRequest("api/pharmacist/updatedata", new
			PharmacistBindingModel
			{
				Id = APIPharmacist.Pharmacist.Id,
				PharmacistFIO = fio,
				Email = email,
				Password = password
			});
			APIPharmacist.Pharmacist.PharmacistFIO = fio;
			APIPharmacist.Pharmacist.Email = email;
			APIPharmacist.Pharmacist.Password = password;
			Response.Redirect("Index");
		}

		[HttpGet]
		public IActionResult Enter()
		{
			return View();
		}
		[HttpPost]
		public void Enter(string email, string password)
		{
			if (string.IsNullOrEmpty(email) ||
			string.IsNullOrEmpty(password))
			{
				throw new Exception("Введите email и пароль");
			}
			APIPharmacist.Pharmacist =
			APIPharmacist.GetRequest<PharmacistViewModel>($"api/pharmacist/login?email={email}&password={password}");
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Неверный логин/пароль");
			}
			Response.Redirect("Index");
		}
		[HttpGet]
		public IActionResult Register()
		{
			return View();
		}
		[HttpPost]
		public void Register(string email, string password, string fio)
		{
			if (string.IsNullOrEmpty(email) ||
			string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
			{
				throw new Exception("Введите логин, пароль и ФИО");
			}
			APIPharmacist.PostRequest("api/pharmacist/register", new
			PharmacistBindingModel
			{
				PharmacistFIO = fio,
				Email = email,
				Password = password
			});
			Response.Redirect("Enter");
			return;
		}

		public IActionResult CreateMedicine()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View();
		}



		[HttpPost]
		public void CreateMedicine(string name, string price)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			StringBuilder st = new StringBuilder(price);
			for (int i = 0; i < price.Length; i++)
			{
				if (price[i] == '.')
					st[i] = ',';
			}
			price = st.ToString();
			double _price;
			try
			{
				_price = Convert.ToDouble(price);
			}
			catch (Exception ex)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			if (string.IsNullOrEmpty(name) || _price <= 0)
			{
				throw new Exception("Ошибка в введенных данных");
			}

			APIPharmacist.PostRequest("api/medicine/createmedicine", new MedicineBindingModel
			{
				MedicineName = name,
				Price = Math.Round(_price, 2),
				PharmacistId = APIPharmacist.Pharmacist.Id
			});
			Response.Redirect("Index");
		}

		public IActionResult DeleteMedicine()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medicines = APIPharmacist.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}

		[HttpPost]
		public void DeleteMedicine(int medicine)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			APIPharmacist.PostRequest("api/medicine/deletemedicine", new MedicineBindingModel
			{
				Id = medicine
			});
			Response.Redirect("Index");
		}

		public IActionResult UpdateMedicine()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medicines = APIPharmacist.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}

		[HttpPost]
		public void UpdateMedicine(int medicine, string name, string price)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			StringBuilder st = new StringBuilder(price);
			for (int i = 0; i < price.Length; i++)
			{
				if (price[i] == '.')
					st[i] = ',';
			}
			price = st.ToString();
			double _price;
			try
			{
				_price = Convert.ToDouble(price);
			}
			catch (Exception ex)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			if (string.IsNullOrEmpty(name) || _price <= 0)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			APIPharmacist.PostRequest("api/medicine/updatemedicine?isconnection=false", new MedicineBindingModel
			{
				Id = medicine,
				MedicineName = name,
				Price = Math.Round(_price, 2),
				PharmacistId = APIPharmacist.Pharmacist.Id,
			});
			Response.Redirect("Index");
		}

		public IActionResult MedicineAnimals()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medicines = APIPharmacist.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines?pharmacistid={APIPharmacist.Pharmacist.Id}");
			ViewBag.Animals = APIPharmacist.GetRequest<List<AnimalViewModel>>($"api/animal/getanimallist");
			return View();
		}


		[HttpPost]
		public void MedicineAnimals(int medicine, string name, string price,
			List<int> animals)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			StringBuilder st = new StringBuilder(price);
			for (int i = 0; i < price.Length; i++)
			{
				if (price[i] == '.')
					st[i] = ',';
			}
			price = st.ToString();
			double _price;
			try
			{
				_price = Convert.ToDouble(price);
			}
			catch (Exception ex)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			if (string.IsNullOrEmpty(name) || _price <= 0)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			Dictionary<int, IAnimalModel> a = new Dictionary<int, IAnimalModel>();
			foreach (int animal in animals)
			{
				a.Add(animal, new AnimalSearchModel { Id = animal } as IAnimalModel);
			}
			APIPharmacist.PostRequest("api/medicine/updatemedicine?isconnection=true", new MedicineBindingModel
			{
				Id = medicine,
				MedicineName = name,
				Price = Math.Round(_price, 2),
				PharmacistId = APIPharmacist.Pharmacist.Id,
				MedicineAnimals = a
			});
			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 Tuple<MedicineViewModel, List<string>>? GetMedicine(int medicineId)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			var result = APIPharmacist.GetRequest<Tuple<MedicineViewModel, List<string>>>($"api/medicine/getmedicine?medicineid={medicineId}");
			if (result == null)
			{
				return default;
			}

			return result;
		}

		[HttpGet]
		public AnimalViewModel? GetAnimal(int animalId)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как сюда попали? Сюда вход только авторизованным");
			}
			var result = APIPharmacist.GetRequest<AnimalViewModel>($"api/animal/getanimal?animalid={animalId}");
			return result;
		}

		public IActionResult Services()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			return
View(APIPharmacist.GetRequest<List<ServiceViewModel>>($"api/service/getservices?pharmacistid={APIPharmacist.Pharmacist.Id}"));

		}


		public IActionResult CreateService()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medicines = APIPharmacist.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines");

			return View();
		}



		[HttpPost]
		public void CreateService(string name, string price, List<int> medicines)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Âû êàê ñþäà ïîïàëè? Ñþäà âõîä òîëüêî àâòîðèçîâàííûì");
			}
			StringBuilder st = new StringBuilder(price);
			for (int i = 0; i < price.Length; i++)
			{
				if (price[i] == '.')
					st[i] = ',';
			}
			price = st.ToString();
			double _price;
			try
			{
				_price = Convert.ToDouble(price);
			}
			catch (Exception ex)
			{
				throw new Exception("Îøèáêà â ââåäåííûõ äàííûõ");
			}
			if (string.IsNullOrEmpty(name) || _price <= 0)
			{
				throw new Exception("Îøèáêà â ââåäåííûõ äàííûõ");
			}
			Dictionary<int, IMedicineModel> a = new Dictionary<int, IMedicineModel>();
			foreach (int medicine in medicines)
			{
				a.Add(medicine, new MedicineSearchModel { Id = medicine } as IMedicineModel);
			}

			APIPharmacist.PostRequest("api/service/createservice", new ServiceBindingModel
			{
				ServiceName = name,
				Price = Math.Round(_price, 2),
				PharmacistId = APIPharmacist.Pharmacist.Id,
				ServiceMedicines = a
			});
			Response.Redirect("Index");
		}

		public IActionResult DeleteService()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Services = APIPharmacist.GetRequest<List<ServiceViewModel>>($"api/service/getservices?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}

		[HttpPost]
		public void DeleteService(int service)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Âû êàê ñþäà ïîïàëè? Ñþäà âõîä òîëüêî àâòîðèçîâàííûì");
			}
			APIPharmacist.PostRequest("api/service/deleteservice", new ServiceBindingModel
			{
				Id = service
			});
			Response.Redirect("Index");
		}

		public IActionResult UpdateService()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Services = APIPharmacist.GetRequest<List<ServiceViewModel>>($"api/service/getservices?pharmacistid={APIPharmacist.Pharmacist.Id}");
			ViewBag.Medicines = APIPharmacist.GetRequest<List<MedicineViewModel>>($"api/medicine/getmedicines");
			return View();
		}

		[HttpPost]
		public void UpdateService(int service, string name, string price,
			List<int> medicines)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Âû êàê ñþäà ïîïàëè? Ñþäà âõîä òîëüêî àâòîðèçîâàííûì");
			}
			StringBuilder st = new StringBuilder(price);
			for (int i = 0; i < price.Length; i++)
			{
				if (price[i] == '.')
					st[i] = ',';
			}
			price = st.ToString();
			double _price;
			try
			{
				_price = Convert.ToDouble(price);
			}
			catch (Exception ex)
			{
				throw new Exception("Îøèáêà â ââåäåííûõ äàííûõ");
			}
			if (string.IsNullOrEmpty(name) || _price <= 0)
			{
				throw new Exception("Îøèáêà â ââåäåííûõ äàííûõ");
			}
			Dictionary<int, IMedicineModel> a = new Dictionary<int, IMedicineModel>();
			foreach (int medicine in medicines)
			{
				a.Add(medicine, new MedicineSearchModel { Id = medicine } as IMedicineModel);
			}
			APIPharmacist.PostRequest("api/service/updateservice", new ServiceBindingModel
			{
				Id = service,
				ServiceName = name,
				Price = Math.Round(_price, 2),
				PharmacistId = APIPharmacist.Pharmacist.Id,
				ServiceMedicines = a
			});
			Response.Redirect("Index");
		}

		[HttpGet]
		public Tuple<ServiceViewModel, List<string>>? GetService(int serviceId)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Âû êàê ñþäà ïîïàëè? Ñþäà âõîä òîëüêî àâòîðèçîâàííûì");
			}
			var result = APIPharmacist.GetRequest<Tuple<ServiceViewModel, List<string>>>($"api/service/getservice?serviceid={serviceId}");
			if (result == null)
			{
				return default;
			}

			return result;
		}

		public IActionResult Guidances()
		{
			if (APIPharmacist.Pharmacist == null)
			{
				return Redirect("~/Home/Enter");
			}
			var res = APIPharmacist.GetRequest<List<GuidanceViewModel>>($"api/guidance/getguidances?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return
View(res);

		}

		[HttpGet]
		public IActionResult CreateGuidance()
		{
			ViewBag.Services = APIPharmacist.GetRequest<List<ServiceViewModel>>($"api/service/getservices?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}
		[HttpPost]
		public void CreateGuidance(int service, string text)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(text))
			{
				throw new Exception("Рекомендация не может быть пустой");
			}
			APIPharmacist.PostRequest("api/guidance/createguidance", new
			GuidanceBindingModel
			{
				ServiceId = service,
				Text = text,
			});
			Response.Redirect("Index");
		}
		[HttpGet]
		public IActionResult UpdateGuidance()
		{
			ViewBag.Services = APIPharmacist.GetRequest<List<ServiceViewModel>>($"api/service/getservices?pharmacistid={APIPharmacist.Pharmacist.Id}");
			ViewBag.Guidances = APIPharmacist.GetRequest<List<GuidanceViewModel>>($"api/guidance/getguidances?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}
		[HttpPost]
		public void UpdateGuidance(int guidance, int service, string text)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(text))
			{
				throw new Exception("Рекомендация не может быть пустой");
			}
			APIPharmacist.PostRequest("api/guidance/updateguidance", new
			GuidanceBindingModel
			{
				Id = guidance,
				ServiceId = service,
				Text = text,
			});
			Response.Redirect("Index");
		}

		[HttpGet]
		public IActionResult DeleteGuidance()
		{
			ViewBag.Guidances = APIPharmacist.GetRequest<List<GuidanceViewModel>>($"api/guidance/getguidances?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}

		[HttpPost]
		public void DeleteGuidance(int guidance)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIPharmacist.PostRequest("api/guidance/deleteguidance", new
			GuidanceBindingModel
			{
				Id = guidance
			});
			Response.Redirect("Index");
		}

		[HttpGet]
		public GuidanceViewModel GetGuidance(int guidanceId)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Âû êàê ñþäà ïîïàëè? Ñþäà âõîä òîëüêî àâòîðèçîâàííûì");
			}
			var result = APIPharmacist.GetRequest<GuidanceViewModel>($"api/guidance/getguidance?guidanceid={guidanceId}");
			if (result == null)
			{
				return default;
			}

			return result;
		}
		[HttpGet]
		public IActionResult AnimalListReport()
		{
			ViewBag.Services = APIPharmacist.GetRequest<List<ServiceViewModel>>($"api/service/getservices?pharmacistid={APIPharmacist.Pharmacist.Id}");
			return View();
		}

		[HttpPost]
		public void AnimalListReport(List<int> services, string type)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}

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

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



			if (type == "docx")
			{
				APIPharmacist.PostRequest("api/report/createanimallistwordfile", new ListAnimalsBindingModel
				{
					Services = services,
					FileName = "C:\\ReportsCourseWork\\wordfile.docx"
				});
				Response.Redirect("GetWordFile");
			}
			else
			{
				APIPharmacist.PostRequest("api/report/createanimallistexcelfile", new ListAnimalsBindingModel
				{
					Services = services,
					FileName = "C:\\ReportsCourseWork\\excelfile.xlsx"
				});
				Response.Redirect("GetExcelFile");
			}
		}

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

		public IActionResult GetExcelFile()
		{
			return new PhysicalFileResult("C:\\ReportsCourseWork\\excelfile.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		}
		[HttpGet]
		public IActionResult Report()
		{
			ViewBag.Report = new List<VisitsGuidesBindingModel>();
			return View();
		}

		[HttpGet]
		public string GetAnimalsReport(DateTime dateFrom, DateTime dateTo)
		{
			if (APIPharmacist.Pharmacist == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			List<VisitsGuidesViewModel> result;
			try
			{
				string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
                string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
                result = APIPharmacist.GetRequest<List<VisitsGuidesViewModel>>
					($"api/report/getvisitsguidesreport?datefrom={dateFromS}&dateto={dateToS}&pharmacistid={APIPharmacist.Pharmacist.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 medicine in result)
			{
				table += "<tbody>";
				table += "<tr>";
				table += $"<td></td>";
				table += $"<td>{medicine.MedicineName}</td>";
				table += $"<td></td>";
				table += $"<td></td>";
				table += "</tr>";
				foreach(var guidance in medicine.Guidances)
				{
					table += "<tr>";
					table += $"<td>{guidance.Date}</td>";
					table += $"<td></td>";
					table += $"<td>{guidance.ServiceName}</td>";
					table += $"<td></td>";
					table += "</tr>";
				}
				foreach (var visit in medicine.Visits)
				{
					table += "<tr>";
					table += $"<td>{visit.DateVisit}</td>";
					table += $"<td></td>";
					table += $"<td></td>";
					table += $"<td>{visit.NameVisit}</td>";
					table += "</tr>";
				}
				table += "</tbody>";
			}
			table += "</table>";
			table += "</div>";
			return table;
		}

        [HttpPost]
        public void Report(DateTime dateFrom, DateTime dateTo)
        {
            if (APIPharmacist.Pharmacist == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            APIPharmacist.PostRequest("api/report/sendvisitsguidesreporttoemail", new VisitsGuidesBindingModel
            {
                FileName = "C:\\ReportsCourseWork\\pdffile.pdf",
				PharmacistId = APIPharmacist.Pharmacist.Id,
				DateFrom = dateFrom,
				DateTo = dateTo,
				Email = APIPharmacist.Pharmacist.Email

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

        }
    }

}
