using FLY.Thick.FilmCasting.Server.Model;
using FLY.Thick.FilmCasting.UI.DbViewer.Core;
using FLY.Thick.FilmCasting.UI.DbViewer.Db;
using GalaSoft.MvvmLight.Command;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace FLY.Thick.FilmCasting.UI.DbViewer
{
    /// <summary>
    /// PageSelect.xaml 的交互逻辑
    /// </summary>
    public partial class PgSelect : Page
    {
        PgSelectVm viewModel;
        DbViewerModel dbViewerModel;
        public PgSelect()
        {
            InitializeComponent();
        }

        [Unity.InjectionMethod]
        public void Init(DbViewerModel dBViewerModel)
        {
            this.dbViewerModel = dBViewerModel;
            viewModel = new PgSelectVm();
            viewModel.Init(dbViewerModel, dgridProfiles);
            this.DataContext = viewModel;

            viewModel.OkSuccessEvent += ViewModel_SearchSuccessEvent;
            
        }

        private void ViewModel_SearchSuccessEvent(object sender, EventArgs e)
        {
            this.NavigationService.GoBack();
            this.NavigationService.RemoveBackEntry();
        }

        private void ButtonBack_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.GoBack();
            this.NavigationService.RemoveBackEntry();
        }

    }
    public class PgSelectVm : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        public DateTime BeginDate { get; set; }
        public DateTime EndDate { get; set; }
        public string ProductNameFilter { get; set; }
        public string BatchFilter { get; set; }

        public bool IsJustRunning { get; set; }

        public ObservableCollection<Db_Profile> Profiles { get; } = new ObservableCollection<Db_Profile>();
        //public ObservableCollection<Db_Profile> SelectedItems { get; } = new ObservableCollection<Db_Profile>();

        public string MonthPath { get; private set; }
        public DateTime DbBeginTime{ get; private set; }
        public DateTime DbEndTime { get; private set; }

        #region CMD
        public RelayCommand SearchCmd { get; private set; }
        public RelayCommand DeleteCmd { get; private set; }
        public RelayCommand OkCmd { get; private set; }

        public RelayCommand SelectMonthPathCmd { get; private set; }
        #endregion
        public DbHelper DbHelper => dbHelper;
        DbViewerModel dbViewerModel;
        DataGrid dgridProfiles;
        DbHelper dbHelper;
        public event EventHandler OkSuccessEvent;

        public PgSelectVm()
        {
            SearchCmd = new RelayCommand(Search);
            DeleteCmd = new RelayCommand(Delete);
            OkCmd = new RelayCommand(Ok);
            SelectMonthPathCmd = new RelayCommand(SelectMonthPath);
        }



        public void Init(DbViewerModel dbViewerModel,DataGrid dgridProfiles)
        {
            this.dbViewerModel = dbViewerModel;
            this.dbHelper = dbViewerModel.mDbHelper;
            this.dgridProfiles = dgridProfiles;



            IsJustRunning = dbViewerModel.IsJustRunning;

            this.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(IsJustRunning))
                {
                    dbViewerModel.IsJustRunning = IsJustRunning;
                    dbViewerModel.Save();
                }
            };
            Misc.BindingOperations.SetBinding(dbHelper, nameof(dbHelper.MonthPath), () =>
            {
                if (string.IsNullOrEmpty(this.dbHelper.MonthPath))
                {
                    MonthPath = "最近2个月";
                }
                else
                {
                    MonthPath = this.dbHelper.MonthPath;
                }
            });

            updateDate();
            dbHelper.PropertyChanged += DbHelper_PropertyChanged;


        }

        private void DbHelper_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if ((e.PropertyName == nameof(dbHelper.DbEndTime)) || (e.PropertyName == nameof(dbHelper.DbBeginTime))) {
                updateDate();
            }
        }

        void updateDate() 
        {
            DbEndTime = dbHelper.DbEndTime;
            DbBeginTime = dbHelper.DbBeginTime;
            EndDate = DbEndTime;
            BeginDate = EndDate.AddDays(-1);
        }
        private async void SelectMonthPath()
        {
            DgSelectMonth dialog = new DgSelectMonth();
            dialog.Init(dbHelper); ;
            await App.MetroWindow.ShowMetroDialogAsync(dialog);
        }

        async void Search()
        {
            var controller = await App.MetroWindow.ShowProgressAsync("请等待...", "开始搜索",
                settings: new MetroDialogSettings()
                {
                    NegativeButtonText = "停止",
                    AnimateShow = false,
                    AnimateHide = false,

                });
            //controller.SetCancelable(true);
            controller.SetIndeterminate();

            var list = dbHelper.GetProfileList(BeginDate, EndDate, ProductNameFilter, BatchFilter);
            Profiles.Clear();
            foreach (var p in list)
            {
                Profiles.Add(p);
            }

            await controller.CloseAsync();
            await App.MetroWindow.ShowMessageAsync("搜索完成",
                    $"搜索结果 为 {Profiles.Count}条");
            return;
        }

        async void Delete()
        {

            var SelectedItems = dgridProfiles.SelectedItems;
            if (SelectedItems.Count == 0)
            {
                await App.MetroWindow.ShowMessageAsync("删除异常",
                    $"没有选择任何一个记录！！");
                return;
            }
            var result = await App.MetroWindow.ShowMessageAsync("警告",
                   $"是否确定删除这些记录?",
                   MessageDialogStyle.AffirmativeAndNegative,
                   new MetroDialogSettings()
                   {
                       AffirmativeButtonText = "确定删除",
                       NegativeButtonText = "取消",
                       DefaultButtonFocus = MessageDialogResult.Negative,
                       ColorScheme = MetroDialogColorScheme.Inverted
                   });
            if (result != MessageDialogResult.Affirmative)
            {
                return;
            }

            List<Db_Profile> dels = new List<Db_Profile>();
            foreach (Db_Profile p in SelectedItems)
            {
                dbHelper.DeleteProfile(p);
                dels.Add(p);
            }
            foreach (var del in dels)
                Profiles.Remove(del);

            SelectedItems.Clear();


            await App.MetroWindow.ShowMessageAsync("删除完成",
                    $"删除 {dels.Count}条 数据");
            return;
        }

        async void Ok()
        {
            var SelectedItems = dgridProfiles.SelectedItems;
            if (SelectedItems.Count == 0)
            {
                await App.MetroWindow.ShowMessageAsync("加载异常",
                    $"没有选择任何一个记录,也许忘记按 【搜索】 了！！");
                return;
            }

            //开始加载
            var controller = await App.MetroWindow.ShowProgressAsync("请等待...", "开始加载数据",
                settings: new MetroDialogSettings()
                {
                    NegativeButtonText = "停止",
                    AnimateShow = false,
                    AnimateHide = false,
                });
            //controller.SetCancelable(true);
            controller.SetIndeterminate();


            List<Db_Profile> profiles = new List<Db_Profile>();
            if (SelectedItems.Count > 0)
            {
                foreach (Db_Profile p in SelectedItems)
                {
                    profiles.Add(p);
                }
                //按顺序排列
                profiles.Sort((p1, p2) =>
                {
                    return p1.ID.CompareTo(p2.ID);
                });
            }
            bool ret = await Task.Factory.StartNew(() =>
            {
                return dbViewerModel.GetProfilePacks(profiles);
            });



            if (!ret)
            {
                //获取出错
                await controller.CloseAsync();
                await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("加载出错", "数据异常，请检测数据库");
                return;
            }

            await controller.CloseAsync();

            string msg = $"扫描数据 {dbViewerModel.ProfilePacks.Sum(p=>p.ScanDatas.Count())}幅";

            //加载成功
            await ((MetroWindow)Application.Current.MainWindow).ShowMessageAsync("加载成功", msg);
            OkSuccessEvent?.Invoke(this, null);

        }
    }
    public class PgSelectVmUt : PgSelectVm
    {

    }
}
