using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using VeterinaryShowDoctorApp.Models;
using VeterinaryContracts.ViewModels;
using VeterinaryContracts.BindingModels;
using System.Text;
using VeterinaryDataModels.Models;
using VeterinaryContracts.SearchModels;
using VeterinaryContracts.StorageContracts;
using System.Globalization;

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

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

		public IActionResult Index()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}"));
		}

		public IActionResult Privacy()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIDoctor.Doctor);
		}

		[HttpPost]
		public void Privacy(string login, string password, string fio)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(login) ||
			string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
			{
				throw new Exception("Введите логин, пароль и ФИО");
			}
			APIDoctor.PostRequest("api/doctor/updatedata", new DoctorBindingModel
			{
				Id = APIDoctor.Doctor.Id,
				DoctorFIO = fio,
				Login = login,
				Password = password
			});
			APIDoctor.Doctor.DoctorFIO = fio;
			APIDoctor.Doctor.Login = login;
			APIDoctor.Doctor.Password = password;
			Response.Redirect("Index");
		}

		[HttpGet]
		public IActionResult Enter()
		{
			return View();
		}
		[HttpPost]
		public void Enter(string login, string password)
		{
			if (string.IsNullOrEmpty(login) ||
			string.IsNullOrEmpty(password))
			{
				throw new Exception("Введите логин и пароль");
			}
			APIDoctor.Doctor =
			APIDoctor.GetRequest<DoctorViewModel>($"api/doctor/login?login={login}&password={password}");
			if (APIDoctor.Doctor == 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("Введите логин, пароль и ФИО");
			}
			APIDoctor.PostRequest("api/doctor/register", new
			DoctorBindingModel
			{
				DoctorFIO = fio,
				Login = login,
				Password = password
			});
			Response.Redirect("Enter");
			return;
		}
		// medications
		[HttpGet]
		public MedicationViewModel? GetMedication(int medicationId)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			var result = APIDoctor.GetRequest <MedicationViewModel>($"api/medication/getmedication?medicationid={medicationId}");
			if (result == null)
			{
				return default;
			}
			return result;
		}
		public IActionResult CreateMedication()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View();
		}
		[HttpPost]
		public void CreateMedication(string name, int price)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || price <= 0)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			APIDoctor.PostRequest("api/medication/createmedication", new MedicationBindingModel
			{
				MedicationName = name,
				Price = price,
				DoctorId = APIDoctor.Doctor.Id
			});
			Response.Redirect("Index");
		}

		public IActionResult DeleteMedication()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}
		[HttpPost]
		public void DeleteMedication(int medication)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIDoctor.PostRequest("api/medication/deletemedication", new MedicationBindingModel
			{
				Id = medication
			});
			Response.Redirect("Index");
		}
		public IActionResult UpdateMedication()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}
		[HttpPost]
		public void UpdateMedication(int medication, string name, int price)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || price <= 0)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			APIDoctor.PostRequest("api/medication/updatemedication", new MedicationBindingModel
			{
				Id = medication,
				MedicationName = name,
				Price = price,
				DoctorId = APIDoctor.Doctor.Id
			});
			Response.Redirect("Index");
		}
		// drugs
		public IActionResult Drugs()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIDoctor.GetRequest<List<DrugViewModel>>($"api/drug/getdrugs?doctorid={APIDoctor.Doctor.Id}"));

		}

		public IActionResult CreateDrug()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");

			return View();
		}

		[HttpPost]
		public void CreateDrug(string name, List<int> medications, int count)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || count <=0)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			Dictionary<int, IMedicationModel> a = new Dictionary<int, IMedicationModel>();
			foreach (int medication in medications)
			{
				a.Add(medication, new MedicationSearchModel { Id = medication } as IMedicationModel);
			}
			APIDoctor.PostRequest("api/drug/createdrug", new DrugBindingModel
			{
				DrugName = name,
				Price = 0,
				DrugMedications = a,
				Count = count,
				DoctorId = APIDoctor.Doctor.Id,
				DateCreate = DateTime.Now,
			});
			Response.Redirect("Drugs");
		}

		public IActionResult DeleteDrug()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Drugs = APIDoctor.GetRequest<List<DrugViewModel>>($"api/drug/getdrugs?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}

		[HttpPost]
		public void DeleteDrug(int drug)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIDoctor.PostRequest("api/drug/deletedrug", new DrugBindingModel
			{
				Id = drug
			});
			Response.Redirect("Drugs");
		}

		public IActionResult UpdateDrug()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Drugs = APIDoctor.GetRequest<List<DrugViewModel>>($"api/drug/getdrugs?doctorid={APIDoctor.Doctor.Id}");
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}

		[HttpPost]
		public void UpdateDrug(int drug, string name, List<int> medications, int count)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name) || count <= 0)
			{
				throw new Exception("Ошибка в введенных данных");
			}
			Dictionary<int, IMedicationModel> a = new Dictionary<int, IMedicationModel>();
			foreach (int medication in medications)
			{
				a.Add(medication, new MedicationSearchModel { Id = medication } as IMedicationModel);
			}
			APIDoctor.PostRequest("api/drug/updatedrug", new DrugBindingModel
			{
				Id = drug,
				DrugName = name,
				Price = 0,
				DrugMedications = a,
				Count = count
			});
			Response.Redirect("Drugs");
		}

		[HttpGet]
		public Tuple<DrugViewModel, List<Tuple<string, int>>>? GetDrug(int drugId)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			var result = APIDoctor.GetRequest<Tuple<DrugViewModel, List<Tuple<string, int>>>>($"api/drug/getdrug?drugid={drugId}");
			if (result == null)
			{
				return default;
			}

			return result;
		}
		// services
		public IActionResult Services()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIDoctor.GetRequest<List<ServiceViewModel>>($"api/service/getservices?doctorid={APIDoctor.Doctor.Id}"));

		}
		public IActionResult CreateService()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
			ViewBag.Visits = APIDoctor.GetRequest<List<VisitViewModel>>($"api/visit/getallvisits");

			return View();
		}
		[HttpPost]
		public void CreateService(string name, List<int> medications, int visit)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name))
			{
				throw new Exception("Ошибка в введенных данных");
			}
			Dictionary<int, IMedicationModel> a = new Dictionary<int, IMedicationModel>();
			foreach (int medication in medications)
			{
				a.Add(medication, new MedicationSearchModel { Id = medication } as IMedicationModel);
			}

			APIDoctor.PostRequest("api/service/createservice", new ServiceBindingModel
			{
				ServiceName = name,
				ServiceMedications = a,
				VisitId = visit,
				DoctorId = APIDoctor.Doctor.Id
			});
			Response.Redirect("Services");
		}
		public IActionResult DeleteService()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Services = APIDoctor.GetRequest<List<ServiceViewModel>>($"api/service/getservices?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}
		[HttpPost]
		public void DeleteService(int service)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIDoctor.PostRequest("api/service/deleteservice", new ServiceBindingModel
			{
				Id = service
			});
			Response.Redirect("Services");
		}
		public IActionResult UpdateService()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Services = APIDoctor.GetRequest<List<ServiceViewModel>>($"api/service/getservices?doctorid={APIDoctor.Doctor.Id}");
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}
		// возможно нужно прописать визит айди
		[HttpPost]
		public void UpdateService(int service, string name, List<int> medications)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			if (string.IsNullOrEmpty(name))
			{
				throw new Exception("Ошибка в введенных данных");
			}
			Dictionary<int, IMedicationModel> a = new Dictionary<int, IMedicationModel>();
			foreach (int medication in medications)
			{
				a.Add(medication, new MedicationSearchModel { Id = medication } as IMedicationModel);
			}
			APIDoctor.PostRequest("api/service/updateservice", new ServiceBindingModel
			{
				Id = service,
				ServiceName = name,
				ServiceMedications = a
			});
			Response.Redirect("Services");
		}
		[HttpGet]
		public Tuple<ServiceViewModel, List<Tuple<string, int>>>? GetService(int serviceId)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			var result = APIDoctor.GetRequest<Tuple<ServiceViewModel, List<Tuple<string, int>>>>($"api/service/getservice?serviceid={serviceId}");
			if (result == null)
			{
				return default;
			}

			return result;
		}

		[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
		public IActionResult Error()
		{
			return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
		}
		// визиты
		public IActionResult Visits()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIDoctor.GetRequest<List<VisitViewModel>>($"api/visit/getallvisits"));

		}
		// отчеты
		[HttpGet]
		public IActionResult PurchaseMedicationReport()
		{
			if (APIDoctor.Doctor == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Medications = APIDoctor.GetRequest<List<MedicationViewModel>>($"api/medication/getmedications?doctorid={APIDoctor.Doctor.Id}");
			return View();
		}

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

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

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

			if (type == "docx")
			{
				APIDoctor.PostRequest("api/report/createpurchaselistwordfile", new ReportPurchaseMedicationBindingModel
				{
					Medications = medications,
					FileName = "C:\\Users\\1\\Downloads\\wordfile.docx"
				});
				Response.Redirect("GetWordFile");
			}
			else
			{
				APIDoctor.PostRequest("api/report/createpurchaselistexcelfile", new ReportPurchaseMedicationBindingModel
				{
					Medications = medications,
					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<ReportDrugsVisitsBindingModel>();
			return View();
		}
		[HttpGet]
		public string GetMedicationsReport(DateTime dateFrom, DateTime dateTo)
		{
			if (APIDoctor.Doctor == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			List<ReportDrugsVisitsViewModel> result;
			try
			{
				string dateFromS = dateFrom.ToString("s", CultureInfo.InvariantCulture);
				string dateToS = dateTo.ToString("s", CultureInfo.InvariantCulture);
				result = APIDoctor.GetRequest<List<ReportDrugsVisitsViewModel>>
					($"api/report/getdrugsvisitsreport?datefrom={dateFromS}&dateto={dateToS}&doctorid={APIDoctor.Doctor.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.MedicationName}</td>";
				table += $"<td></td>";
				table += $"<td></td>";
				table += "</tr>";
				foreach (var drug in medication.Drugs)
				{
					table += "<tr>";
					table += $"<td>{drug.DateCreate}</td>";
					table += $"<td></td>";
					table += $"<td>{drug.DrugName}</td>";
					table += $"<td></td>";
					table += "</tr>";
				}
				foreach (var visit in medication.Visits)
				{
					table += "<tr>";
					table += $"<td>{visit.DateVisit}</td>";
					table += $"<td></td>";
					table += $"<td></td>";
					table += $"<td>{visit.VisitName}</td>";
					table += "</tr>";
				}
				table += "</tbody>";
			}
			table += "</table>";
			table += "</div>";
			return table;
		}

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

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

		}

	}
}