using ComputerShopContracts.BindingModels;
using ComputerShopContracts.SearchModels;
using ComputerShopContracts.ViewModels;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.Office2010.Excel;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Mvc;
using OrdererClientApp.Models;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;

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

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

		public IActionResult Index()
		{
			if (APIClient.Client == null)
			{
				return Redirect("~/Home/Enter");
			}
			return View(APIClient.GetRequest<List<EquipmentReceivingViewModel>>($"api/equipmentreceiving/getreceivings?clientId={APIClient.Client.Id}"));
		}

		public IActionResult Receivings()
        {
            if (APIClient.Client == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest<List<EquipmentReceivingViewModel>>($"api/equipmentreceiving/getreceivings?clientId={APIClient.Client.Id}"));
        }

		public IActionResult Order()
        {
            if (APIClient.Client == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest<List<OrderViewModel>>($"api/order/getorderlist?clientId={APIClient.Client.Id}"));
        }

        public IActionResult Supply()
        {
            if (APIClient.Client == null)
            {
                return Redirect("~/Home/Enter");
            }
            return View(APIClient.GetRequest<List<SupplyViewModel>>($"api/supply/getsupplylist?clientId={APIClient.Client.Id}"));
        }

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

        [HttpPost]
        public void Privacy(string login, string password, string fio)
        {
            if (APIClient.Client == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(fio))
            {
                throw new Exception("Введите логин, пароль и ФИО");
            }
            APIClient.PostRequest("api/client/updatedata", new ClientBindingModel
            {
                Id = APIClient.Client.Id,
                ClientFIO = fio,
                Email = login,
                Password = password
            });

            APIClient.Client.ClientFIO = fio;
            APIClient.Client.Email = login;
            APIClient.Client.Password = password;
            Response.Redirect("Receivings");
        }

        [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("Введите логин и пароль");
            }
            APIClient.Client = APIClient.GetRequest<ClientViewModel>($"api/client/login?login={login}&password={password}");
            if (APIClient.Client == null)
            {
                throw new Exception("Неверный логин/пароль");
            }
            Response.Redirect("Receivings");
        }

        [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("Введите логин, пароль и ФИО");
            }
            APIClient.PostRequest("api/client/register", new ClientBindingModel
            {
                ClientFIO = fio,
                Email = login,
                Password = password
            });
            Response.Redirect("Enter");
            return;
        }

        [HttpPost]
        public void CreateReceiving()

		{
			if (APIClient.Client == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}

			APIClient.PostRequest("api/equipmentreceiving/createreceiving", new EquipmentReceivingBindingModel
			{
				ClientId = APIClient.Client.Id
			});
			Response.Redirect("Receivings");
        }

		[HttpPost]
		public void SetFinish(int id)
		{
			if (APIClient.Client == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIClient.PostRequest($"api/equipmentreceiving/setfinish?id={id}", id);
			Response.Redirect("Receivings");
		}

		[HttpPost]
		public void DeleteReceiving(int id)
		{
			if (APIClient.Client == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIClient.PostRequest($"api/equipmentreceiving/deletereceiving?id={id}", id);
			Response.Redirect("Receivings");

		}

		[HttpGet]
        public IActionResult CreateOrder()
        {
			ViewBag.Components = APIClient.GetRequest<List<AssemblyViewModel>>($"api/assembly/getassemblylist?clientId={APIClient.Client.Id}");
			return View();
        }
        [HttpPost]
        public void CreateOrder(int sum, int assembly_id, int amount)
        {
            if (APIClient.Client == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
			OrderBindingModel order = new OrderBindingModel
            {
                ClientId = APIClient.Client.Id,
                Sum = sum
            };

            APIClient.PostRequest($"api/order/createorder?assembly_id={assembly_id}&amount={amount}", order);

			Response.Redirect("Order");
        }

		[HttpGet]
        public IActionResult DeleteOrder()
        {
            ViewBag.Orders = APIClient.GetRequest<List<OrderViewModel>>($"api/main/getorderlist/?clientId={APIClient.Client.Id}");
            return View();
        }
        [HttpPost]
        public void DeleteOrder(int id)
        {
            if (APIClient.Client == null)
            {
                throw new Exception("Вы как суда попали? Суда вход только авторизованным");
            }
            APIClient.PostRequest($"api/order/deleteorder", new ComponentBindingModel
			{
				Id = id
			});
			Response.Redirect("Order");
        }

		public IActionResult AddComponent()
		{
			if (APIClient.Client == null)
			{
				return Redirect("~/Home/Enter");
			}
			ViewBag.Components = APIClient.GetRequest<List<ComponentViewModel>>($"api/component/getcomponentlist?clientId={APIClient.Client.Id}");
			ViewBag.Orders = APIClient.GetRequest<List<OrderViewModel>>($"api/order/getorderlist?clientId={APIClient.Client.Id}");
			return View();
		}

		[HttpPost]
		public void AddComponent(int order, int component, int amount)
		{
			if (APIClient.Client == null)
			{
				throw new Exception("Необходима авторизация");
			}
			APIClient.PostRequest("api/order/AddComponent", Tuple.Create(
				new OrderSearchModel() { Id = order },
				new ComponentSearchModel() { Id = component },			
				amount
			));
			Response.Redirect("Order");
		}

		[HttpPost]
		public void FinishOrder(int id)
		{
			if (APIClient.Client == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIClient.PostRequest($"api/order/finishorder?id={id}", id);
			Response.Redirect("Order");
		}

		[HttpGet]
		public IActionResult EditOrder(int id)
		{
			if (APIClient.Client == null)
			{
				return Redirect("~/Home/Enter");
			}
			var componentViewModels = APIClient.GetRequest<List<AssemblyViewModel>?>($"api/order/GetAssembliesByOrder?orderid={id}");
			var assemblies = APIClient.GetRequest<List<AssemblyViewModel>?>($"api/assembly/getassemblylist?clientId={APIClient.Client.Id}");

			ViewBag.Order = id;
            ViewBag.Components = componentViewModels;
			ViewBag.Assemblies = assemblies;

			return View();
		}

		[HttpPost]
        public void AddAssemblyToOrder(int order, double cost, int component, int amount)
        {
			if (APIClient.Client == null)
			{
				throw new Exception("Необходима авторизация");
			}
			if (cost < 0)
			{
				throw new Exception("Стоимость не может быть меньше нуля");
			}

			if (component >= 0 & amount > 1)
			{
				APIClient.PostRequest("api/order/AddAssembly", Tuple.Create(
				new OrderSearchModel() { Id = order },
				new AssemblySearchModel() { Id = component },
				amount
			));
			}
			APIClient.PostRequest($"api/order/editorder", new OrderBindingModel
			{
				Id = component,
				Sum = cost,
				ClientId = APIClient.Client.Id
			});
		}

		[HttpPost]
		public void DeliveryOrder(int id)
		{
			if (APIClient.Client == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIClient.PostRequest($"api/order/deliveryorder?id={id}", id);
			Response.Redirect("Order");
		}
		[HttpPost]
		public void TakeOrderInWork(int id)
		{
			if (APIClient.Client == null)
			{
				throw new Exception("Вы как суда попали? Суда вход только авторизованным");
			}
			APIClient.PostRequest($"api/order/takeorderinwork?id={id}", id);
			Response.Redirect("Order");
		}

		[HttpPost]
        public double Calc(int count, int assembly)
        {
            var ass = APIClient.GetRequest<AssemblyViewModel>($"api/main/getassembly?assemblyId={assembly}");
            return count * (ass?.Price ?? 1);
        }

		[HttpPost]
		public double CalcOrder(int count, int componentid)
		{
			var or = APIClient.GetRequest<OrderViewModel>($"api/main/getassembly?assemblyId={componentid}");
			return count * (or?.Sum ?? 1);
		}
	}
}