using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ryCommon;

namespace ryControls
{
    /// <summary>
    /// 日历控件
    /// </summary>
    [DefaultEvent("OnClickItem")]
    [Description("农历日历控件")]
    public partial class ChinaCalendar : UserControl
    {
        /// <summary>
        /// 单击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="dt"></param>
        public delegate void ClickItemHandler(object sender, DateTime dt);
        private List<LunarDay> list_lunar = new List<LunarDay>();
        /// <summary>
        /// 单击某个日期事件
        /// </summary>
        public event ClickItemHandler OnClickItem;
        /// <summary>
        /// 日历控件
        /// </summary>
        public ChinaCalendar()
        {
            InitializeComponent();
            ryCommon.ListX list = new ListX(PnlDay)
            {
                MaxColCount = 7,
                spaceX = 1,
                spaceY = 1
            };
            int day_width = 0;
            for (int i = 0; i < 42; i++)
            {
                LunarDay lunarday = new LunarDay
                {
                    Day = i + 1,
                    Lunar_Day = (i + 1).ToString(),
                    //Size = new Size(120, 120)
                };
                lunarday.Click += Lunarday_Click;
                lunarday.OnProcessCmdKey += Lunarday_OnProcessCmdKey;
                if (day_width == 0)
                {
                    day_width = lunarday.Width;
                }
                list_lunar.Add(lunarday);
                list.Add(lunarday);
            }
            list.ReDraw();
            for(int i=0;i<7;i++)
            {
                Label lbl_week = new Label
                {
                    AutoSize = false,
                    TextAlign = ContentAlignment.MiddleCenter,
                    Text = "星期" + RyDate.GetWeekName(i + 1),
                    Left = i * day_width,
                    Width = day_width,
                    Parent = PnlWeek
                };
            }
            DateTime = DateTime.Now;
        }

        private void Lunarday_OnProcessCmdKey(object sender, ref Message msg, Keys keyData)
        {
            var _dt = DateTime;
            if (last_selected_item != null) { _dt = last_selected_item.Date; }
            switch (keyData)
            {
                case Keys.Right:
                    _dt = _dt.AddDays(1);
                    break;
                case Keys.Left:
                    _dt = _dt.AddDays(-1);
                    break;
                case Keys.Up://方向键不反应
                    _dt = _dt.AddDays(-7);
                    break;
                case Keys.Down:
                    _dt = _dt.AddDays(7);
                    break;
            }
            DateTime = _dt;
            //ChangeDate(_dt,true);
        }

        private LunarDay last_selected_item = null;
        private void Lunarday_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            LunarDay lunarday=(LunarDay)sender;
            if(last_selected_item!= lunarday)
            {
                if (last_selected_item != null) { last_selected_item.Selected = false; }
                last_selected_item = lunarday;
                lunarday.Selected = true;
            }
            lunarday.Focus();
            OnClickItem?.Invoke(this,lunarday.Date);
            //if(lunarday.Date.Month!=DateTime.Month)
            //{
            //    DateTime = lunarday.Date;
            //}
            //for (int i = 0; i < list_lunar.Count; i++)
            //{
            //    if(list_lunar[i]==lunarday)
            //    {
            //        list_lunar[i].Selected=true;
            //    }
            //    else { list_lunar[i].Selected = false ; }
            //}
        }

        private DateTime _DateTime = DateTime.Now;
        /// <summary>
        /// 设置日期
        /// </summary>
        public DateTime DateTime
        {
            get { return _DateTime; }
            set
            {
                if (_DateTime != value)
                {
                    _DateTime = value;
                    ChangeDate(value,true);
                }
            }

        }
        private void ChangeDate(DateTime dt)
        {
            ChangeDate(dt, false);
        }
        /// <summary>
        /// 放假数据表
        /// </summary>
        public string HolidayFolder { get; set; } = Application.StartupPath + "\\SysDb\\Holidays";
        private void ChangeDate(DateTime dt,bool selected)
        {
            ProcUse = true;
            NumYear.Value = dt.Year;
            CbbMonth.SelectedIndex = dt.Month - 1;
            ProcUse = false;
            var gl_daycount = 0;
            if (dt.Year < 1582 || (dt.Year == 1582 && dt.Month <= 10)) { gl_daycount =11; }
            var month_date= RyDate.GetMonthStart(dt);
            var start_week = RyDate.GetWeek_index(month_date.AddDays(-gl_daycount));
            var dt_now = DateTime.Now;
            Ini ini = new Ini(HolidayFolder+"\\"+dt.Year+".ini");
            last_selected_item = null;
            DateTime? dt_1fu = null;
            DateTime? dt_2fu = null;
            DateTime? dt_3fu = null;
            if (dt.Month==7 || dt.Month==8)
            {
                dt_1fu = ChinaDate.Get3Fu(dt.Year, 0);
                dt_2fu = dt_1fu.Value.AddDays(10);
                dt_3fu = ChinaDate.Get3Fu(dt.Year, 2);
            }
            for (int i = 0; i <42; i++)
            {
                var dt_2 = month_date.AddDays(i+1- start_week);
                if(month_date.Year==1582 && month_date.Month==10)
                {
                    if(i>=4)
                    {
                        dt_2 = dt_2.AddDays(10);
                    }
                }
                var lunar = list_lunar[i];
                lunar.Day = dt_2.Day;
                lunar.Selected = false;
                if(i>=35)
                {
                    lunar.Visible = month_date.AddDays(36 - start_week).Month == dt.Month;
                    if (!lunar.Visible) { continue; }
                }
                if ((i+1)%7==0)
                {
                    lunar.SetRestState(1);
                }
                else { lunar.SetRestState(0); }
                if(dt_2.Date==dt.Date)
                {
                    if (last_selected_item != lunar)
                    {
                        if (last_selected_item != null) { last_selected_item.Selected = false; }
                        last_selected_item = lunar;
                        lunar.Selected = true;
                    }
                }
                if (dt_2.Year == dt.Year)
                {
                    int state = ini.ReadIni("date", dt_2.ToString("MMdd"), -2);
                    if (state != -2)
                    { lunar.SetRestState(state); }
                }
                else
                {
                    Ini ini2 = new Ini(HolidayFolder + "\\" + dt_2.Year + ".ini");
                    int state = ini2.ReadIni("date", dt_2.ToString("MMdd"), -2);
                    if (state != -2)
                    { lunar.SetRestState(state); }
                }
                var ChinaHoliday= ChinaDate.GetChinaHoliday(dt_2);
                var WorldHoliday = ChinaDate.GetHoliday(dt_2);
                var WeekHoliday = ChinaDate.GetWeekHoliday(dt_2);
                var JieqiHoliday = ChinaDate.GetSolarTerm(dt_2);
                bool Holiday = false;
                string Holiday_Str = "";
                if (ChinaHoliday != "")
                { Holiday_Str = ChinaHoliday;}
                if (dt_2 ==dt_1fu)
                { Holiday_Str += " 初伏"; }
                if (dt_2 == dt_2fu)
                { Holiday_Str += " 中伏"; }
                if (dt_2 == dt_3fu)
                { Holiday_Str += " 末伏"; }
                if (WorldHoliday != "")
                { Holiday_Str += " " + WorldHoliday; }
                if (WeekHoliday != "")
                { Holiday_Str += " " + WeekHoliday; }
                if (JieqiHoliday!="")
                { Holiday_Str += " " + JieqiHoliday; }
                if (Holiday_Str!="")
                {
                    lunar.Lunar_Day = Holiday_Str.Trim(); lunar.Lunar_Day_ForeColor = Color.Orange; Holiday = true;
                }
                else
                {
                    var lunar_day_str = ChinaDate.GetDay(dt_2);
                    if (lunar_day_str == "初一")
                    {
                        lunar.Lunar_Day = ChinaDate.GetMonth(dt_2);
                    }
                    else
                    {
                        lunar.Lunar_Day = lunar_day_str;
                    }
                }
                lunar.Date = dt_2;
                if (dt_2.Month!=dt.Month)//不是当月
                {
                    lunar.Day_ForeColor = Color.FromArgb(190,190,190);
                    if (!Holiday)
                    { lunar.Lunar_Day_ForeColor = Color.FromArgb(190, 190, 190); }
                    lunar.BackColor = Color.White;
                }
                else
                {
                    if (dt_2.Date == dt_now.Date)
                    {
                        lunar.BackColor = Color.FromArgb(47, 152, 222);
                        lunar.Day_ForeColor = Color.White;
                        if (!Holiday)
                        { lunar.Lunar_Day_ForeColor = Color.White; }
                    }
                    else
                    {
                        lunar.Day_ForeColor = Color.Black;
                        if (!Holiday)
                        { lunar.Lunar_Day_ForeColor = Color.Black; }
                        lunar.BackColor = Color.White;
                    }
                }
            }
        }
        bool ProcUse = false;
        private void NumYear_ValueChanged(object sender, EventArgs e)
        {
            if (ProcUse) { return; }
            DateTime = new DateTime(NumYear.Value.ToInt(), CbbMonth.SelectedIndex + 1, 1);
            OnClickItem?.Invoke(this, DateTime.Date);
        }

        private void CbbMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ProcUse) { return; }
            DateTime = new DateTime(NumYear.Value.ToInt(), CbbMonth.SelectedIndex + 1, 1);
            OnClickItem?.Invoke(this, DateTime.Date);
        }

        private void BtnMonthPrev_Click(object sender, EventArgs e)
        {
            DateTime = DateTime.AddMonths(-1);
            OnClickItem?.Invoke(this, DateTime.Date);
        }

        private void BtnMonthNext_Click(object sender, EventArgs e)
        {
            DateTime = DateTime.AddMonths(1);
            OnClickItem?.Invoke(this, DateTime.Date);
        }

        private void BtnToday_Click(object sender, EventArgs e)
        {
            DateTime = DateTime.Now;
            OnClickItem?.Invoke(this, DateTime.Date);
        }
    }
}
