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

namespace Sessioa.Pages
{
    /// <summary>
    /// Логика взаимодействия для OrderNew.xaml
    /// </summary>
    public partial class OrderNew : Page
    {
        User user = null;
        List<string> sortList = new List<string>() { "Без сортировки", "По убыванию стоимости", "По возрастанию стоимости" };
        List<string> filtList = new List<string>() { "Без фильтрации", "0-10%", "11-14%", "15% >" };
        List<Order> orders = new List<Order>();
        public OrderNew(User userSign)
        {
            InitializeComponent();
            user = userSign;
            if (userSign.UserRole == 2 || userSign.UserRole == 3)
            {
                orders = BaseClass.C_Base.Order.Include(x => x.PointsOfIssue).Include(x => x.User).Include(x => x.OrderProduct).ToList();
                LB_OrderProduct.ItemsSource = orders;
            }
            else if (userSign.UserRole == 1)
            {
                orders = BaseClass.C_Base.Order.Include(x => x.PointsOfIssue).Where(x => x.UserID == userSign.UserID).Include(x => x.OrderProduct).ToList();
                LB_OrderProduct.ItemsSource = orders;
            }
            Sort.ItemsSource = sortList;
            Sort.SelectedItem = sortList[0];

            Filt.ItemsSource = filtList;
            Filt.SelectedItem = filtList[0];
        }

        private void UserOrder_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock)sender;
            if (tb.Uid != null && (user.UserRole == 2 || user.UserRole == 3))
            {
                User us = BaseClass.C_Base.User.FirstOrDefault(x => x.UserID.ToString() == tb.Uid);
                tb.Text = $"Заказчик: {us.UserSurname} {us.UserName[0]}.{(us.UserPatronymic != null && us.UserPatronymic != string.Empty ? $"{us.UserPatronymic[0]}." : "")}";
            }
        }

        private void B_Back_Click(object sender, RoutedEventArgs e)
        {
            Application.Current.Properties["ListOrderUser"] = new List<Product>();
            Application.Current.Properties["ListOrderCountUser"] = new Dictionary<string, int>();
            FrameClass.C_Frame.Navigate(new ProductsPage(user));
        }

        private void TextBlock_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock)sender;
            Order tmp = BaseClass.C_Base.Order.FirstOrDefault(x => x.OrderID.ToString() == tb.Uid);
            if (tmp.OrderDeliveryDate == null)
            {
                tb.Text = "Дата выдачи не указана";
                tb.Foreground = new SolidColorBrush(Color.FromRgb(235, 156, 0));
            }
        }

        private void Border_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ClickCount > 1)
            {
                FrameClass.C_Frame.Navigate(new OrderCard(user, ((Order)LB_OrderProduct.SelectedItem).OrderID));
            }
        }

        private void TB_StatusOrder_Loaded(object sender, RoutedEventArgs e)
        {
            TextBlock tb = (TextBlock)sender;
            Order tmp = BaseClass.C_Base.Order.FirstOrDefault(x => x.OrderID.ToString() == tb.Uid);
            if (tmp.OrderStatus == 2)
            {
                tb.Text = "Статус: Новый";
                tb.Foreground = new SolidColorBrush(Color.FromRgb(73, 140, 81));
            }
            else
            {
                tb.Text = "Статус: Завершен";
                tb.Foreground = new SolidColorBrush(Color.FromRgb(255, 0, 0));
            }
        }

        private void Border_Loaded(object sender, RoutedEventArgs e)
        {
            Border brd = (Border)sender;
            List<OrderProduct> op = BaseClass.C_Base.OrderProduct.Where(x => x.OrderID.ToString() == brd.Uid).ToList();
            foreach (OrderProduct opItem in op)
            {
                Product prd = BaseClass.C_Base.Product.FirstOrDefault(x => x.ProductArticleNumber == opItem.ProductArticleNumber);
                if (prd.ProductQuantityInStock < 3)
                    brd.BorderBrush = new SolidColorBrush(Color.FromRgb(255, 140, 0));
            }
        }

        private void Sort_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Sett();
        }

        private void Filt_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Sett();
        }
        private void Sett()
        {
            foreach (Order od in orders)
            {
                decimal itogoBezSkidki = 0;
                decimal itogoSoSkidkoy = 0;
                List<OrderProduct> tmpOP = BaseClass.C_Base.OrderProduct.Where(x => x.OrderID == od.OrderID).ToList();
                foreach (OrderProduct opItem in tmpOP)
                {
                    Product prAdd = BaseClass.C_Base.Product.FirstOrDefault(x => x.ProductArticleNumber == opItem.ProductArticleNumber);
                    itogoBezSkidki += prAdd.ProductCost * opItem.ProductCount;
                    if (prAdd.ProductDiscountAmount != null && prAdd.ProductDiscountAmount != 0)
                    {
                        itogoSoSkidkoy += (prAdd.ProductCost - (prAdd.ProductCost * ((decimal)prAdd.ProductDiscountAmount / 100))) * opItem.ProductCount;
                    }
                    else
                        itogoSoSkidkoy += prAdd.ProductCost * opItem.ProductCount;
                }
                od.Cost = itogoSoSkidkoy;
                od.Discount = Math.Round((1 - (itogoSoSkidkoy / itogoBezSkidki)) * 100, 2);
            }

            if (user.UserRole == 2 || user.UserRole == 3)
                orders = BaseClass.C_Base.Order.Include(x => x.PointsOfIssue).Include(x => x.User).Include(x => x.OrderProduct).ToList();
            else if (user.UserRole == 1)
                orders = BaseClass.C_Base.Order.Include(x => x.PointsOfIssue).Where(x => x.UserID == user.UserID).Include(x => x.OrderProduct).ToList();

            switch (Filt.SelectedIndex)
            {

                case 1:
                    {
                        orders = orders.Where(x => x.Discount <= 10).ToList();
                        break;
                    }
                case 2:
                    {
                        orders = orders.Where(x => x.Discount > 10 && x.Discount <= 14).ToList();
                        break;
                    }
                case 3:
                    {
                        orders = orders.Where(x => x.Discount >= 15).ToList();
                        break;
                    }
            }
            switch (Sort.SelectedIndex)
            {
                case 1:
                    {
                        orders = orders.OrderByDescending(x => x.Cost).ToList();
                        LB_OrderProduct.ItemsSource = orders;
                        break;
                    }
                case 2:
                    {
                        orders = orders.OrderBy(x => x.Cost).ToList();
                        LB_OrderProduct.ItemsSource = orders;
                        break;
                    }
                default:
                    {
                        break;
                    }
            }

            LB_OrderProduct.ItemsSource = orders;
        }
    }
}
