using System;
using System.Collections.Generic;
using System.Globalization;
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 NEIntelligentControl2.Views.Basic
{
    /// <summary>
    /// 时间选择控件
    /// </summary>
    public partial class TimePicker : UserControl
    {
        public static readonly DependencyProperty SelectedDateTimeProperty = DependencyProperty.Register("SelectedDateTime", typeof(DateTime), typeof(TimePicker));

        public static readonly RoutedEvent SelectedDatesChangedEvent = EventManager.RegisterRoutedEvent("SelectedTimeChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TimePicker));

        /// <summary>
        /// 选中的时间
        /// </summary>
        public DateTime SelectedDateTime { get => (DateTime)GetValue(SelectedDateTimeProperty); set => SetValue(SelectedDateTimeProperty, value); }

        /// <summary>
        /// 时间选择改变事件
        /// </summary>
        public event RoutedEventHandler SelectedDateTimeChanged
        {
            add
            {
                AddHandler(SelectedDatesChangedEvent, value);
            }
            remove
            {
                RemoveHandler(SelectedDatesChangedEvent, value);
            }
        }
        private DateTime _StartTime;
        public TimePicker()
        {
            InitializeComponent();
            var dt = DateTime.Now;
            SelectedDateTime = dt.AddSeconds(-dt.Second);

            _StartTime = SelectedDateTime;
            Init();
        }

        private void Init()
        {
            int[] h = new int[24];
            int[] m = new int[60];
            for (int i = 0; i < 60; ++i)
            {
                if (i < 24) h[i] = i;
                m[i] = i;
            }
            _lbhour.ItemsSource = h;
            _lbminute.ItemsSource = m;

            _lbhour.SelectedIndex = SelectedDateTime.Hour;
            _lbminute.SelectedIndex = SelectedDateTime.Minute;
        }

        private void TextBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _popup.IsOpen = !_popup.IsOpen;

            if (SelectedDateTime.CompareTo(_StartTime) == 0 || _popup.IsOpen) return;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _popup.IsOpen = false;
            switch (((Control)sender).Tag)
            {
                case "cancel":
                    SelectedDateTime = _StartTime;
                    break;
                case "ok":
                    _StartTime = default(DateTime);
                    break;
                default: return;
            }
        }

        private void DateTimeChanged()
        {
            _StartTime = SelectedDateTime;
            RoutedEventArgs rea = new RoutedEventArgs(SelectedDatesChangedEvent, this);
            this.RaiseEvent(rea);
        }

        private async void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            var date = (DateTime)e.AddedItems[0];
            SelectedDateTime = date.Add(SelectedDateTime.TimeOfDay);

            Mouse.Capture(null);
            await Task.Delay(100);
            _tb.Focus();
        }

        private async void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int i = (int)e.AddedItems[0];
            if (((Control)sender).Tag as string == "minute")
            {
                i -= SelectedDateTime.Minute;
                SelectedDateTime = SelectedDateTime.AddMinutes(i);
            }
            else
            {
                i -= SelectedDateTime.Hour;
                SelectedDateTime = SelectedDateTime.AddHours(i);
            }
            await Task.Delay(200);
            _tb.Focus();
        }

        private async void TextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            await Task.Delay(200);
            if (_tb.IsFocused && _popup.IsMouseOver) return;
            _popup.IsOpen = false;
            if (SelectedDateTime.CompareTo(_StartTime) == 0) return;
            DateTimeChanged();
        }
    }

    /// <summary>
    /// 时间转换
    /// </summary>
    public class DateTimeConver : IValueConverter
    {
        //当值从绑定源传播给绑定目标时，调用方法Convert
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return DependencyProperty.UnsetValue;
            DateTime date = (DateTime)value;
            return date.ToString("yyyy-MM-dd HH:mm:ss");
        }

        //当值从绑定目标传播给绑定源时，调用此方法ConvertBack
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string str = value as string;
            DateTime txtDate;
            if (DateTime.TryParse(str, out txtDate))
            {
                return txtDate;
            }
            return DependencyProperty.UnsetValue;
        }
    }
}
