using CalcS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ExamBoldin
{
    /// <summary>
    /// Логика взаимодействия для pgBasket.xaml
    /// </summary>
    public partial class pgBasket : Page
    {
        List<BookShop> books;
        bool CanGoBack = true;
        public pgBasket(List<BookShop> books)
        {
            InitializeComponent();
            this.books = books;
            lbBooksBasket.ItemsSource = books;
        }


        private void btnDeleteBook_Click(object sender, RoutedEventArgs e)
        {
            Button btn = (Button)sender;
            int id = Convert.ToInt32(btn.Uid);
            BookShop delBook = books.FirstOrDefault(x => x.id == id);
            books.Remove(delBook);
            lbBooksBasket.Items.Refresh();
        }

        private void btnBuy_Click(object sender, RoutedEventArgs e)
        {
            int numOreder;
            if (BaseConnect.BaseModel.Orders.Count() != 0)
                numOreder = BaseConnect.BaseModel.Orders.Max(x => x.NOrder) + 1;
            else
                numOreder = 1;
            bool flag = false;
            int count = 0;
            int sale = 0;
            decimal CountCost = 0;
            foreach (BookShop book in books)
            {

                BookShop bk = BaseConnect.BaseModel.BookShop.FirstOrDefault(x => x.id == book.id);
                if (bk.CountStore >= book.AllCount)
                {
                    flag = true;
                    bk.CountStore -= book.AllCount;
                    BaseConnect.BaseModel.SaveChanges();
                }
                else
                {
                    int res = book.AllCount - bk.CountStore;
                    bk.CountStore = 0;
                    bk.CountStock -= res;
                    BaseConnect.BaseModel.SaveChanges();
                }
                Orders or = new Orders();
                or.IdBook = book.id;
                or.NOrder = numOreder;
                or.Count = book.AllCount;
                count += book.AllCount;
                sale = book.Sale;
                CountCost += book.Cost * book.AllCount;
                or.DateOrder = DateTime.Now;
                BaseConnect.BaseModel.Orders.Add(or);
            }

            if (flag)
                MessageBox.Show("Заказ: " + numOreder + "\nПоловина заказа прибудет: " + DateTime.Now.ToShortDateString() + "\nОстальная часть заказа прибудет: " + DateTime.Now.AddDays(3).ToShortDateString() + "\nКниги зарезервированы до: " + DateTime.Now.AddDays(7).ToShortDateString() + "\nКоличество книг в заказе: " + count + "\nЦена:" + Math.Floor(CountCost - (CountCost * sale / 100)) + "\nСкидка:" + sale + "%");
            else
            {
                MessageBox.Show("Заказ: " + numOreder + "\nЗаказ можно забрать: " + DateTime.Now.ToShortDateString() + "\nЗарезервировано до: " + DateTime.Now.AddDays(7).ToShortDateString() + "\nКоличество книг в заказе: " + count + "\nЦена:" + Math.Floor(CountCost - (CountCost * sale / 100)) + "\nСкидка:" + sale + "%");
            }

            books.Clear();
            lbBooksBasket.Items.Refresh();
            CanGoBack = false;
        }

        private void btnDel_Click(object sender, RoutedEventArgs e)
        {
            books.Clear();
            lbBooksBasket.Items.Refresh();
            CanGoBack = false;
        }

        private void btnBack_Click(object sender, RoutedEventArgs e)
        {
            if (!CanGoBack)
                LoadPages.GoPage.Navigate(new pgListBooks());
            else
                LoadPages.GoPage.GoBack();
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            TextBox tb = (TextBox)sender;
            int id = Convert.ToInt32(tb.Uid);
            BookShop book = books.FirstOrDefault(x => x.id == id);
            int tmpValue = book.AllCount ;
            try
            {
                BookShop checkCountBook = BaseConnect.BaseModel.BookShop.FirstOrDefault(x => x.id == id);
                int countBase = checkCountBook.CountStore + checkCountBook.CountStock;
                if (countBase >= Convert.ToInt32(tb.Text))
                {
                    CalcSale cs = new CalcSale();
                    book.AllCount = Convert.ToInt32(tb.Text);
                    int count=0;
                    decimal cost =0;
                    foreach (BookShop booke in books)
                    {
                        cost += booke.Cost * booke.AllCount;
                        count += booke.AllCount;
                  
                    }
                    foreach (BookShop booke in books)
                    {
                        booke.Sale = cs.Calc(count, cost);
                    }
                    lbBooksBasket.ItemsSource = books;
                    lbBooksBasket.Items.Refresh();

                }
                else
                {
                    MessageBox.Show("Данного количества нет на скалде!");
                    tb.Text = tmpValue.ToString();
                }
            }
            catch { }
        }
    }
}
