using Caliburn.Micro;
using System;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Linq;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using System.Dynamic;
using System.Configuration;
using SimpleCRM.ViewDAO;
using Telerik.Windows.Controls;
using SimpleCRM.Units;
using Telerik.Windows.Controls.Calendar;
using System.Globalization;
using SimpleCRM.Service;

namespace SimpleCRM.ViewModels
{
    public class AppMainShellViewModel : Caliburn.Micro.Screen, IAppBaseShell, IHandle<OrderEventArgs>
    {
        private readonly IWindowManager windowManager;
        private readonly IEventAggregator eventAggregator;
        private readonly DictionarysService dictionarysService;
        private Dictionary<string, System.Action<object>> oMaps = new Dictionary<string, System.Action<object>>();
        public AppMainShellViewModel(IWindowManager _windowManager, IEventAggregator events, DictionarysService _DictionarysService)
        {
            windowManager = _windowManager;
            eventAggregator = events;
            eventAggregator.Subscribe(this);
            dictionarysService = _DictionarysService;
        }

        #region Properties
        private Object settingsPage = null;
        public Object SettingsPage
        {
            get
            {
                if (this.settingsPage == null)
                {
                    this.settingsPage = IoC.Get<OrderListViewModel>();
                    SetUpOrderCondition();
                }
                return settingsPage;
            }
            set { settingsPage = value; NotifyOfPropertyChange(() => SettingsPage); }
        }

        private DateTime _CurrentDate = DateTime.Now;
        public DateTime CurrentDate
        {
            get
            {
                return _CurrentDate;
            }
            set
            {
                if (_CurrentDate != value)
                {
                    _CurrentDate = value;
                    NotifyOfPropertyChange(() => CurrentDate);
                }
            }
        }

        private DateSelectionMode _DateSelectionMode = DateSelectionMode.Day;
        public DateSelectionMode DateSelectionMode
        {
            get
            {
                return _DateSelectionMode;
            }
            set
            {
                _DateSelectionMode = value;
                NotifyOfPropertyChange(() => DateSelectionMode);
            }
        }

        public Order CurrentOrder { get; set; }

        public StackPanel actionToolBar { get; set; }

        public int SelectedCustomerID { get; set; }
        public int SelectedSalerID { get; set; }

        public System.Windows.Controls.ContentControl MyContentControl { get; set; }
        #endregion

        protected override void OnViewLoaded(object view)
        {
            var content = ((System.Windows.Controls.ContentControl)view).Content;
            actionToolBar = ((System.Windows.Controls.StackPanel)((((System.Windows.Controls.Panel)(((System.Windows.Controls.Panel)content).Children[0]))).FindName("ToolBar")));
            //var comboBoxs = actionToolBar.ChildrenOfType<RadComboBox>();
            //foreach (var combo in comboBoxs)
            //{
            //    combo.IsEditable = false;
            //    combo.IsReadOnly = true;
            //    combo.SelectionChanged += Combo_SelectionChanged;
            //}
            //BindComboboxItems(comboBoxs, "Order_customerCondition", dictionarysService.GetAllCustomers());
            //BindComboboxItems(comboBoxs, "Order_salerCondition", dictionarysService.GetAllSalers());
            InitButtonAction();

            MyContentControl = ((System.Windows.Controls.ContentControl)((((System.Windows.Controls.Panel)(((System.Windows.Controls.Panel)content).Children[1]))).FindName("ContentControl")));
        }
        private void InitButtonAction()
        {
            oMaps.Add("Order_Add", (btn) => { Order_Add(btn); });
            oMaps.Add("Order_Print", (btn) => { Order_Print(btn); });
            oMaps.Add("Order_Condition_Month", (btn) => { Order_Condition_Month(btn); });
            oMaps.Add("Order_Condition_Day", (btn) => { Order_Condition_Day(btn); });
            oMaps.Add("Customer_Add", (btn) => { Customer_Add(btn); });
            oMaps.Add("Saler_Add", (btn) => { Saler_Add(btn); });
            oMaps.Add("Saler_Department_Add", (btn) => { Customer_Add(btn); });

            oMaps.Add("Report_Print", (btn) => { Report_Print(btn); });
            oMaps.Add("Report_Customer", (btn) => { Report_Customer(btn); });
            oMaps.Add("Report_Saler", (btn) => { Report_Saler(btn); });
            oMaps.Add("Report_PerMonth", (btn) => { Report_PerMonth(btn); });

        }

        #region combobox
        private void Combo_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            var combobox = sender as Telerik.Windows.Controls.RadComboBox;
            var selectedItem = e.AddedItems;
            switch (combobox.Name)
            {
                case "Order_customerCondition":
                    var customerItem = selectedItem[0] as Customer;
                    SelectedCustomerID = customerItem.ID;
                    break;

                case "Order_salerCondition":
                    var salerItem = selectedItem[0] as Saler;
                    SelectedSalerID = salerItem.ID;
                    break;
            }
            SetUpOrderCondition();
        }

        private void BindComboboxItems(IEnumerable<RadComboBox> comboBoxs, string comboxName, IEnumerable datas)
        {
            var combobox = comboBoxs.FirstOrDefault(t => t.Name == comboxName);
            if (combobox == null)
            {
                return;
            }
            combobox.ItemsSource = datas;
            combobox.DisplayMemberPath = "Name";
        }
        #endregion combobox

        #region button
        public void MainButton_Click(object sender)
        {
            Telerik.Windows.Controls.RadButton mainButton = (Telerik.Windows.Controls.RadButton)sender;
            System.Windows.Controls.TextBlock ctlLocaltion = (System.Windows.Controls.TextBlock)actionToolBar.FindName("LocaltionMessage");
            ctlLocaltion.Text = ((System.Windows.Controls.TextBlock)(((System.Windows.Controls.Panel)mainButton.Content).Children[1])).Text + ":";
            string strName = mainButton.Name;
            foreach (var element in actionToolBar.Children)
            {
                var item = element as FrameworkElement;
                if (item == null)
                {
                    continue;
                }

                if (item is TextBlock)
                {
                    continue;
                }

                if (item.Name.Contains(strName))
                {
                    item.Visibility = Visibility.Visible;
                }
                else
                {
                    item.Visibility = Visibility.Collapsed;
                }
            }

            switch (strName)
            {
                case "Order":
                    SettingsPage = IoC.Get<OrderListViewModel>();
                    SetUpOrderCondition();
                    break;
                case "Customer":
                    SettingsPage = IoC.Get<CustomerListViewModel>();
                    break;
                case "Saler":
                    SettingsPage = IoC.Get<SalerListViewModel>();
                    break;
                case "Report":
                   
                    break;
            }
        }

        public void ToolBarButton_Click(object sender)
        {
            var mainButton = (Telerik.Windows.Controls.RadButton)sender;
            System.Action<object> btnAction = null;
            if (oMaps.TryGetValue(mainButton.Name, out btnAction))
            {
                btnAction(sender);
            }
        }

        public void Order_Add(object sender)
        {
            object addView = IoC.Get<OrderFormViewModel>();
            eventAggregator.PublishOnUIThread(new OrderEventArgs() { Order = new Order(), FormViewModel = FormViewModel.Insert });
            OpenWindow(addView);
        }
        public void Order_Condition_Month(object sender)
        {
            DateSelectionMode = DateSelectionMode.Month;
            SetUpOrderCondition();
        }
        public void Order_Condition_Day(object sender)
        {
            DateSelectionMode = DateSelectionMode.Day;
            SetUpOrderCondition();
        }
        public void Order_Print(object sender)
        {
            if (CurrentOrder == null)
            {
                MessageBox.Show("先选择一个订单!");
                return;
            }

            object addView = IoC.Get<OrderPrintViewModel>();
            eventAggregator.PublishOnUIThread(new OrderEventArgs() { Order = CurrentOrder, FormViewModel = FormViewModel.Edit });
            OpenWindow(addView);
        }
        public void Customer_Add(object sender)
        {
            object addView = IoC.Get<CustomerFormViewModel>();
            eventAggregator.PublishOnUIThread(new CustomerEventArgs() { Customer = new Customer(), FormViewModel = FormViewModel.Insert });
            OpenWindow(addView);
        }
        public void Saler_Add(object sender)
        {
            object addView = IoC.Get<SalerFormViewModel>();
            eventAggregator.PublishOnUIThread(new SalerEventArgs() { Saler = new Saler(), FormViewModel = FormViewModel.Insert });
            OpenWindow(addView);
        }

        public void Report_Print(object sender)
        {
            PrintDialog dialog = new PrintDialog();
            if (dialog.ShowDialog() == true)
            {
                dialog.PrintVisual(MyContentControl, "Print Test");
            }
        }


        public void Report_Customer(object sender)
        {
            eventAggregator.PublishOnUIThread(new ReportEventArgs()
            {
                ReportType = ReportType.Customer
            });
        }


        public void Report_Saler(object sender)
        {
            eventAggregator.PublishOnUIThread(new ReportEventArgs()
            {
                ReportType = ReportType.Saler
            });
        }


        public void Report_PerMonth(object sender)
        {
            eventAggregator.PublishOnUIThread(new ReportEventArgs()
            {
                ReportType = ReportType.PerMonth
            });
        }

        #endregion


        public void Order_DateCondition_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RadDateTimePicker DTP = (RadDateTimePicker)sender;
            SetUpOrderCondition();
        }
        public void Order_DateCondition_ParseDateTimeValue(object sender, ParseDateTimeEventArgs args)
        {
            Int32 month;
            if (Int32.TryParse(args.TextToParse, out month))
            {
                if (month >= 1 && month <= 12)
                {
                    args.Result = new DateTime(DateTime.Now.Year, month, 1);
                }
            }
        }

        public void Handle(OrderEventArgs message)
        {
            CurrentOrder = message.Order;
        }

        private void SetUpOrderCondition()
        {
            OrderAddedEventArgs args = new OrderAddedEventArgs();
            string strCondition = string.Empty;

            if (this.SelectedCustomerID != 0)
            {
                strCondition = " AND CUSTOMER=" + SelectedCustomerID;
            }

            if (this.SelectedSalerID != 0)
            {
                strCondition = " AND SALER=" + SelectedSalerID;
            }

            if (this.DateSelectionMode == DateSelectionMode.Month)
            {
                //DateTime begin = DateTimeHelper.FirstDayOfMonth(this.CurrentDate);
                //DateTime end = DateTimeHelper.FirstDayOfNextMonth(this.CurrentDate);
                strCondition = string.Format(" AND YEAR={0} AND MONTH={1} ", this.CurrentDate.Year, this.CurrentDate.Month);
            }
            else
            {
                string date = DateTimeConvertHelper.GetFormatDate(this.CurrentDate);
                strCondition = " AND DATE='" + date + "'";
            }


            args.Condition = strCondition;
            eventAggregator.PublishOnUIThread(args);
        }

        private void OpenWindow(object addView)
        {
            dynamic settings = new ExpandoObject();
            settings.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            //settings.WindowStyle = WindowStyle.ToolWindow;
            //settings.Title = "添加出货单";
            //settings.ResizeMode = ResizeMode.NoResize;
            settings.AllowsTransparency = true;
            settings.WindowStyle = WindowState.Normal;
            //Screen screen = addView as Screen;
            //screen.ViewAttached += Screen_ViewAttached;
            windowManager.ShowDialog(addView, null, settings);
        }
    }
}