using Sessioa.BaseModel;
using Sessioa.Classes;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Sessioa.Pages
{
    /// <summary>
    /// Логика взаимодействия для ProductsPage.xaml
    /// </summary>
    public partial class ProductsPage : Page
    {
        List<Product> listProduct = BaseClass.C_Base.Product.Include(x => x.Manufacturer).ToList();
        List<Product> listOrder = new List<Product>();
        User user = null;
        List<string> sort = new List<string>() { "Без сортировки", "По возрастанию", "По убыванию" };
        List<string> filtr = new List<string>() { "Все диапазоны", "0 - 9,99%", "10 - 14,99%", "15% >" };
        string selectSort = "Без сортировки";
        string selectFiltr = "Все диапазоны";

        public ProductsPage()
        {
            InitializeComponent();
            UserSign.Text = "Вход не выполнен";
            Init();
        }
        public ProductsPage(User userSign)
        {
            InitializeComponent();
            listOrder = (List<Product>)Application.Current.Properties["ListOrderUser"];
            user = userSign;
            UserSign.Text = $"Вход выолнен: {user.UserSurname} {user.UserName} {user.UserPatronymic}";
            Init();
            if(listOrder != null)
            {
                if (listOrder.Count > 0)
                {
                    OrderActUser.Visibility = Visibility.Visible;
                    OrderActUser.Content = $"Корзина({listOrder.Count})";
                }
            }
        }
        private void Init()
        {
            LB_Product.ItemsSource = listProduct;
            CB_Sort.ItemsSource = sort;
            CB_Sort.SelectedItem = selectSort;
            CB_Filtr.ItemsSource = filtr;
            CB_Filtr.SelectedItem = selectFiltr;
            TB_CountAll.Text = BaseClass.C_Base.Product.Count().ToString();
        }

        private void countPr_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock)sender;
            Product product = BaseClass.C_Base.Product.FirstOrDefault(x => x.ProductArticleNumber == tb.Uid);
            if (product.ProductDiscountAmount != null && product.ProductDiscountAmount != 0)
                tb.TextDecorations = TextDecorations.Strikethrough;
        }

        private void countPr_Loaded_1(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock)sender;
            Product product = BaseClass.C_Base.Product.FirstOrDefault(x => x.ProductArticleNumber == tb.Uid);
            if (product.ProductDiscountAmount != null && product.ProductDiscountAmount != 0)
            {
                double j = (double)product.ProductDiscountAmount / 100;
                double ji = (double)(product.ProductCost) * j;

                double n = (double)(product.ProductCost) - ji;
                tb.Text = n.ToString() + "₽";
                tb.Visibility = Visibility.Visible;
            }
        }

        private void Border_Loaded(object sender, RoutedEventArgs e)
        {
            Border border = (Border)sender;
            Product product = BaseClass.C_Base.Product.FirstOrDefault(x => x.ProductArticleNumber == border.Uid);
            if (product.ProductDiscountAmount != null && product.ProductDiscountAmount > 15)
                border.Background = (Brush)(new BrushConverter().ConvertFrom("#7fff00"));
        }

        private void Discount_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock)sender;
            Product product = BaseClass.C_Base.Product.FirstOrDefault(x => x.ProductArticleNumber == tb.Uid);
            if (product.ProductDiscountAmount != null && product.ProductDiscountAmount != 0)
                tb.Text = $"Скидка {product.ProductDiscountAmount}%";
        }

        private void SearchTB_TextChanged(object sender, TextChangedEventArgs e)
        {
            setting();
        }
        private void setting()
        {
            if (SearchTB.Text.Length > 0)
                listProduct = BaseClass.C_Base.Product.Where(x => x.ProductName.ToLower().Contains(SearchTB.Text.ToLower())).ToList();
            else listProduct = BaseClass.C_Base.Product.ToList();
            if (CB_Sort.SelectedIndex != 0)
            {
                if (CB_Sort.SelectedIndex == 1)
                {
                    listProduct = listProduct.OrderBy(x => (x.ProductDiscountAmount != null ? x.ProductCost - x.ProductCost * x.ProductDiscountAmount / 100 : x.ProductCost)).ToList();
                }
                if (CB_Sort.SelectedIndex == 2)
                {
                    listProduct = listProduct.OrderByDescending(x => (x.ProductDiscountAmount != null ? x.ProductCost - x.ProductCost * x.ProductDiscountAmount / 100 : x.ProductCost)).ToList();
                }
            }
            if (CB_Filtr.SelectedIndex != 0)
            {
                switch (CB_Filtr.SelectedIndex)
                {
                    case 1:
                        listProduct = listProduct.Where(x => x.ProductDiscountAmount >= 0 && x.ProductDiscountAmount <= 9.99).ToList();
                        break;
                    case 2:
                        listProduct = listProduct.Where(x => x.ProductDiscountAmount >= 10 && x.ProductDiscountAmount <= 14.99).ToList();
                        break;
                    case 3:
                        listProduct = listProduct.Where(x => x.ProductDiscountAmount >= 15).ToList();
                        break;
                }
            }
            LB_Product.ItemsSource = null;
            LB_Product.ItemsSource = listProduct;
            TB_CountActual.Text = listProduct.Count.ToString();
        }

        private void CB_Filtr_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            setting();
        }

        private void CB_Sort_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            setting();
        }

        private void SignOf_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Properties["ListOrderUser"] = new List<Product>();
            FrameClass.C_Frame.Navigate(new Autorization());
        }
        private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
        {
            ContextMenu cm = (ContextMenu)(sender);

            if (user == null)
                cm.Visibility = Visibility.Collapsed;
        }

        private void EditProduct_Loaded(object sender, RoutedEventArgs e)
        {
            MenuItem mt = (MenuItem)(sender);
            if (user == null)
                mt.Visibility = Visibility.Collapsed;
            else if (user.UserRole != 2)
                mt.Visibility = Visibility.Collapsed;
        }

        private void DeleteProduct_Loaded(object sender, RoutedEventArgs e)
        {
            MenuItem dt = (MenuItem)(sender);
            if (user == null)
                dt.Visibility = Visibility.Collapsed;
            else if (user.UserRole != 2)
                dt.Visibility = Visibility.Collapsed;
        }

        private void NewProduct_Click(object sender, RoutedEventArgs e)
        {
            FrameClass.C_Frame.Navigate(new ProductCard(user));
        }

        private void NewProduct_Loaded(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)(sender);
            if (user != null && user.UserRole == 2)
                btn.Visibility = Visibility.Visible;
        }

        private void EditProduct_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FrameClass.C_Frame.Navigate(new ProductCard(user, (Product)LB_Product.SelectedItem));
            }
            catch
            {
                MessageBox.Show("Непредвиденная ошибка.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void DeleteProduct_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult mbr = MessageBox.Show("Удалить продукт?", "квешченс", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (mbr == MessageBoxResult.Yes)
            {
                try
                {
                    BaseClass.C_Base.Product.Remove((Product)LB_Product.SelectedItem);
                    BaseClass.C_Base.SaveChanges();
                    MessageBox.Show("Продукт удален", "Оповещение", MessageBoxButton.OK, MessageBoxImage.Information);
                    FrameClass.C_Frame.Navigate(new ProductsPage(user));
                }
                catch
                {
                    MessageBox.Show("Ошибка. Продукт не может быть удален.", "Оповещение", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        private void OrdersUser_Loaded(object sender, RoutedEventArgs e)
        {
            Button button = (Button)sender;
            if (user != null)
            {
                if (user.UserRole > 0)
                    button.Visibility = Visibility.Visible;
                else if (BaseClass.C_Base.Order.Where(x => x.UserID == user.UserID).Count() > 0)
                    button.Visibility = Visibility.Visible;
            }
        }

        private void OrdersUser_Click(object sender, RoutedEventArgs e)
        {
            FrameClass.C_Frame.Navigate(new OrderNew(user));
        }

        private void AddOrder_Click(object sender, RoutedEventArgs e)
        {
            if (listOrder.Contains((Product)LB_Product.SelectedItem))
                MessageBox.Show("Данный товар уже находится в корзине", "Предупреждение", MessageBoxButton.OK, MessageBoxImage.Warning);
            else
            {
                listOrder.Add((Product)LB_Product.SelectedItem);
                OrderActUser.Content = $"Корзина({listOrder.Count})";
            }
            OrderActUser.Visibility = Visibility.Visible;
        }

        private void OrderActUser_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Properties["ListOrderUser"] = listOrder;
            FrameClass.C_Frame.Navigate(new OrderCard(user));
        }
    }
}
