using BBWY.Client.Models;
using BBWY.Client.Views.SelectShop;
using BBWY.Common.Extensions;
using GalaSoft.MvvmLight.Command;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace BBWY.Client.ViewModels
{
    public partial class OrderListViewModel
    {
        private int sdGroupButtonIndex;
        private Shop sdGroupSelectedShop;

        public int SDGroupButtonIndex { get => sdGroupButtonIndex; set { Set(ref sdGroupButtonIndex, value); } }

        public ICommand SetSDButtinIndexCommand { get; set; }
        public ICommand SDGroupSelectedShopChangedCommand { get; set; }

        public ICommand SDGroupPullCommand { get; set; }

        public Shop SdGroupSelectedShop { get => sdGroupSelectedShop; set { Set(ref sdGroupSelectedShop, value); } }

        public SDGroupPersonStatistics SDGroupPersonStatistics { get; set; }

        private void SDGroupInit()
        {
            SetSDButtinIndexCommand = new RelayCommand<int>(SetSDButtinIndex);
            SDGroupSelectedShopChangedCommand = new RelayCommand<OnShopChangedEventArgs>(SDGroupSelectedShopChanged);
            SDGroupPullCommand = new RelayCommand(SDGroupPull);
            SDGroupPersonStatistics = new SDGroupPersonStatistics();
        }

        private void SetSDButtinIndex(int index)
        {
            SDGroupButtonIndex = index;
            OrderList.Clear();
            SearchOrderId = string.Empty;
            OrderCount = 0;
            PageIndex = 1;
        }

        private void SDGroupSelectedShopChanged(OnShopChangedEventArgs args)
        {
            this.SdGroupSelectedShop = args.SelectedShop;
        }

        private void SDGroupPull()
        {
            if (string.IsNullOrEmpty(SearchOrderId) || this.SdGroupSelectedShop == null)
            {
                MessageBox.Show("拉取条件不齐全", "提示");
                return;
            }
            IsLoading = true;
            Task.Factory.StartNew(() => orderService.SDGroupPullOrder(SearchOrderId, SdGroupSelectedShop)).ContinueWith(t =>
            {
                IsLoading = false;
                var response = t.Result;
                if (!response.Success)
                {
                    App.Current.Dispatcher.Invoke(() => MessageBox.Show(response.Msg, "拉取订单"));
                    return;
                }
                PageIndex = 1;
                OrderCount = 1;
                var order = response.Data.Map<Order>();
                App.Current.Dispatcher.Invoke(() =>
                {
                    OrderList.Clear();
                    OrderList.Add(order);
                });
            });
        }

        private void LoadSDGroupPersonStatistics()
        {
            var response = statisticsService.GetSDGroupPersonStatistics(querySDOperator, StartDate, EndDate);
            if (response.Success)
                response.Data.Map(SDGroupPersonStatistics);
        }
    }
}