using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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;
using System.Windows.Threading;


namespace Txgy.Controls
{
    /// <summary>
    /// CalendarClock.xaml 的交互逻辑
    /// </summary>
    public partial class CalendarClock3row : UserControl
    {
        private readonly TaskScheduler _syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
        private bool _isDisposed=false;
        List<Task> tasks = new List<Task>();

        public Color ForegroundColor
        {
            get { return (Color)GetValue(ForegroundColorProperty); }
            set { SetValue(ForegroundColorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ForegroundColor.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ForegroundColorProperty =
            DependencyProperty.Register("ForegroundColor", typeof(Color), typeof(CalendarClock3row), new PropertyMetadata(Color.FromRgb(122, 64, 242)));


        public CalendarClock3row()
        {
            InitializeComponent();          
            var runtask = Task.Factory.StartNew(async () =>
            {
                while (!_isDisposed)
                {
                    DateTime dt = DateTime.Now;
                    string DateStr = "公历 " + dt.ToString("yyyy年MM月dd日");
                    Task.Factory.StartNew(() => UpdateLabel(this.lblGL, DateStr),
                        new CancellationTokenSource().Token, TaskCreationOptions.None, _syncContextTaskScheduler).Wait();

                    DateStr = SolarToChineseLunisolarDate(dt);
                    Task.Factory.StartNew(() => UpdateLabel(this.lblNL, DateStr),
                       new CancellationTokenSource().Token, TaskCreationOptions.None, _syncContextTaskScheduler).Wait();
                    DateStr = dt.ToString("T");
                    Task.Factory.StartNew(() => UpdateLabel(this.lblTime, dt.ToString("T")),
                       new CancellationTokenSource().Token, TaskCreationOptions.None, _syncContextTaskScheduler).Wait();
                    await Task.Delay(1000);
                }
            });
            tasks.Add(runtask);
        }
        ~CalendarClock3row()
        {
            Dispose();
        }
        public void Dispose()
        {
            if (!_isDisposed)
            {
                _isDisposed = true;
                Task.WaitAll(tasks.ToArray());
                GC.SuppressFinalize(this);
            }
        }
        private void UpdateLabel(Label lbl, string text)
        {
            lbl.Content = text;
        }
        /// <summary>
        /// 公历转为农历的函数
        /// </summary>
        /// <param name="solarDateTime">公历日期</param>
        /// <returns>农历的日期</returns>
        public string SolarToChineseLunisolarDate(DateTime solarDateTime)
        {
            System.Globalization.ChineseLunisolarCalendar cal = new System.Globalization.ChineseLunisolarCalendar();

            int year = cal.GetYear(solarDateTime);
            int month = cal.GetMonth(solarDateTime);
            int day = cal.GetDayOfMonth(solarDateTime);
            int leapMonth = cal.GetLeapMonth(year);
            return string.Format("农历 {0}{1}月{2}{3}  {4}"
                                , month == leapMonth ? "闰" : ""
                                ,"无正二三四五六七八九十冬腊"[leapMonth > 0 && leapMonth <= month ? month - 1 : month]
                                , "初十廿三"[day / 10]
                                , "日一二三四五六七八九"[day % 10]
                                , GetDayName(solarDateTime));
        }
        /// <summary>
        /// 公历转为农历的函数
        /// </summary>
        /// <param name="solarDateTime">公历日期</param>
        /// <returns>农历的日期</returns>
        static string SolarToChineseLunisolarAllDate(DateTime solarDateTime)
        {
            System.Globalization.ChineseLunisolarCalendar cal = new System.Globalization.ChineseLunisolarCalendar();

            int year = cal.GetYear(solarDateTime);
            int month = cal.GetMonth(solarDateTime);
            int day = cal.GetDayOfMonth(solarDateTime);
            int leapMonth = cal.GetLeapMonth(year);
            return string.Format("农历{0}{1}（{2}）年{3}{4}月{5}{6}"
                                , "甲乙丙丁戊己庚辛壬癸"[(year - 4) % 10]
                                , "子丑寅卯辰巳午未申酉戌亥"[(year - 4) % 12]
                                , "鼠牛虎兔龙蛇马羊猴鸡狗猪"[(year - 4) % 12]
                                , month == leapMonth ? "闰" : ""
                                , "无正二三四五六七八九十冬腊"[leapMonth > 0 && leapMonth <= month ? month - 1 : month]
                                , "初十廿三"[day / 10]
                                , "日一二三四五六七八九"[day % 10]
                                );
        }
        private string GetDayName(DateTime today)
        {
            string result = "";
            if (today.DayOfWeek == DayOfWeek.Monday)
            {
                result = "星期一";
            }
            else if (today.DayOfWeek == DayOfWeek.Tuesday)
            {
                result = "星期二";
            }
            else if (today.DayOfWeek == DayOfWeek.Wednesday)
            {
                result = "星期三";
            }
            else if (today.DayOfWeek == DayOfWeek.Thursday)
            {
                result = "星期四";
            }
            else if (today.DayOfWeek == DayOfWeek.Friday)
            {
                result = "星期五";
            }
            else if (today.DayOfWeek == DayOfWeek.Saturday)
            {
                result = "星期六";
            }
            else if (today.DayOfWeek == DayOfWeek.Sunday)
            {
                result = "星期日";
            }
            return result;
        }
    }
}
