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

namespace TimeClock.DbOp
{
    public partial class FrmFullScreenTip : Form
    {
        public FrmFullScreenTip()
        {
            InitializeComponent();
            LblTimeStr.Text = "弹窗时间:" + DateTime.Now.ToString("yyyy年MM月dd日 HH:mm");
            DateTime dt = DateTime.Now;
            LblTime.Text = DateTime.Now.ToString("HH:mm:ss");
            timer1.Enabled = true;
            int n = 5-dt.Minute % 5;
            contextMenuStrip1.Items.Add("推迟到" + dt.AddMinutes(n - 1).ToString("HH:mm") + "提醒").Tag = dt.AddMinutes(n - 1);
            if (n<=1)
            {
                contextMenuStrip1.Items[0].Visible = false;
            }
            contextMenuStrip1.Items.Add("推迟到"+dt.AddMinutes(n).ToString("HH:mm")+"提醒").Tag = dt.AddMinutes(n);
            contextMenuStrip1.Items.Add("推迟1分钟提醒").Tag = 1;
            contextMenuStrip1.Items.Add("推迟2分钟提醒").Tag = 2;
            contextMenuStrip1.Items.Add("推迟5分钟提醒").Tag = 5;
            contextMenuStrip1.Items.Add("推迟10分钟提醒").Tag = 10;
            contextMenuStrip1.Items.Add("推迟15分钟提醒").Tag = 15;
            contextMenuStrip1.Items.Add("推迟半小时提醒").Tag = 30;
            contextMenuStrip1.Items.Add("推迟1小时提醒").Tag = 60;
            contextMenuStrip1.Items.Add("推迟到明天提醒").Tag = 60 * 24;
            for(int i=0;i<contextMenuStrip1.Items.Count;i++)
            {
                contextMenuStrip1.Items[i].Click += FrmFullScreenTip_Click;
            }
            _CloseMinute = Itrycn_Info.AutoCloseMinute*60;
            _HaveCloseMinute = Itrycn_Info.AutoCloseMinute > 0;
            if (!_HaveCloseMinute) { LblCloseTime.Visible = false; }
            sound.Volume = Itrycn_Info.MusicVolume / 100f;
        }
        /// <summary>
        /// 自定义显示
        /// </summary>
        /// <param name="CustomShowXML"></param>
        public void AddCustomShow(string CustomShowXML,DateTime NextTipTime)
        {
            if (CustomShowXML == "") { return; }
            ryCommon.Storage myCustomShow_XML = new Storage(CustomShowXML);
            myCustomShow_XML.SelectNodeBySet();
            var iCount = myCustomShow_XML.GetAttrValue("Count", 0);
            Color[] color = new Color[] { Color.Magenta,Color.LightCoral,Color.YellowGreen,Color.SeaGreen,
                Color.DeepSkyBlue,Color.MediumPurple,Color.MediumOrchid,Color.Fuchsia };
            ListX listx = new ListX(panel1)
            {
                MaxColCount = 6,
                spaceX = 15
            };
            for (int m = 0; m < iCount; m++)
            {
                CustomShowInfo dt_info = new CustomShowInfo()
                {
                    Type = myCustomShow_XML.GetAttrValue("CsType" + (m + 1).ToString(), 1),
                    Name = myCustomShow_XML.GetAttrValue("CsName" + (m + 1).ToString(), ""),
                    IsLunar = myCustomShow_XML.GetAttrValue("CsIsLunar" + (m + 1).ToString(), false),
                    Year = myCustomShow_XML.GetAttrValue("CsYear" + (m + 1).ToString(), 1),
                    Month = myCustomShow_XML.GetAttrValue("CsMonth" + (m + 1).ToString(), 1),
                    Day = myCustomShow_XML.GetAttrValue("CsDay" + (m + 1).ToString(), 1)
                };
                Random rd = new Random(Guid.NewGuid().GetHashCode());
                switch (dt_info.Type)
                {
                    case 0: //出生日期提醒
                        var days = (NextTipTime.Date - DateTime.Now.Date).TotalDays.ToInt();
                        CustomShow.BirthDayUI b_ui = new CustomShow.BirthDayUI();
                        b_ui.Title = dt_info.Name;
                        b_ui.DateStr = dt_info.DateStr;
                        if (days > 0)
                        { b_ui.AgeUnit = "岁(" + days + "天后)"; }
                        else if (days < 0)
                        { b_ui.AgeUnit = "岁(" + days + "天前)"; }
                        #region 计算岁数
                        int age = NextTipTime.Year - dt_info.Year;
                        if (dt_info.IsLunar)
                        {
                            if (ChinaDate.GetDayFromLunar(NextTipTime.Year, dt_info.Month, dt_info.Day, false, out int AYear, out int AMonth, out int ADay))
                            {
                                var getdate = new DateTime(AYear, AMonth, ADay);
                                if (getdate < NextTipTime.Date)
                                {
                                    age--;
                                }
                            }
                        }
                        else
                        {
                            var getdate = new DateTime(NextTipTime.Year, dt_info.Month, dt_info.Day);
                            if (getdate < NextTipTime.Date)
                            {
                                age--;
                            }
                        }
                        b_ui.Age = age.ToString();
                        #endregion
                        b_ui.BackColor = color[rd.Next(0, color.Length - 1)];
                        listx.Add(b_ui);
                        break;
                    case 1: //纪念日提醒
                        var days2 = (NextTipTime.Date - DateTime.Now.Date).TotalDays.ToInt();
                        CustomShow.BirthDayUI b_ui2 = new CustomShow.BirthDayUI();
                        b_ui2.Title = dt_info.Name;
                        b_ui2.DateStr = dt_info.DateStr;
                        if (days2 > 0)
                        { b_ui2.AgeUnit = "周年(" + days2 + "天后)"; }
                        else if (days2 < 0)
                        { b_ui2.AgeUnit = "周年(" + days2 + "天前)"; }
                        else
                        {
                            b_ui2.AgeUnit = "周年";
                        }
                        #region 计算周年
                        int age2 = NextTipTime.Year - dt_info.Year;
                        if (dt_info.IsLunar)
                        {
                            if (ChinaDate.GetDayFromLunar(NextTipTime.Year, dt_info.Month, dt_info.Day, false, out int AYear, out int AMonth, out int ADay))
                            {
                                var getdate = new DateTime(AYear, AMonth, ADay);
                                if (getdate < NextTipTime.Date)
                                {
                                    age2--;
                                }
                            }
                        }
                        else
                        {
                            var getdate = new DateTime(NextTipTime.Year, dt_info.Month, dt_info.Day);
                            if (getdate < NextTipTime.Date)
                            {
                                age2--;
                            }
                        }
                        b_ui2.Age = age2.ToString();
                        #endregion
                        b_ui2.BackColor = color[rd.Next(0, color.Length - 1)];
                        listx.Add(b_ui2);
                        break;
                    case 2: //倒计时提醒
                        CustomShow.DJSDayUI b_ui3= new CustomShow.DJSDayUI();
                        b_ui3.Title = dt_info.Name;
                        b_ui3.DateStr = dt_info.DateStr;
                        #region 计算周年
                        int dsj_day = -1;
                        bool get_info = true;
                        if (dt_info.IsLunar)
                        {
                            if (ChinaDate.GetDayFromLunar(dt_info.Year, dt_info.Month, dt_info.Day, false, out int AYear, out int AMonth, out int ADay))
                            {
                                var getdate = new DateTime(AYear, AMonth, ADay);
                                dsj_day =(getdate - DateTime.Now.Date).TotalDays.ToString().ToInt();
                            }
                            else { get_info = false; }
                        }
                        else
                        {
                            var getdate = new DateTime(dt_info.Year, dt_info.Month, dt_info.Day);
                            dsj_day = (getdate - DateTime.Now.Date).TotalDays.ToString().ToInt();
                        }
                        if (!get_info)
                        { b_ui3.Day = "未知"; }
                        else                        
                        {
                            if (dsj_day < 0)
                            {
                                b_ui3.DayBefore = "过期";
                                b_ui3.Day = (-dsj_day).ToString(); 
                            }
                            else
                            {
                               b_ui3.DayBefore = "还有";
                               b_ui3.Day = dsj_day.ToString();
                            }
                        }
                        #endregion
                        b_ui3.BackColor = color[rd.Next(0, color.Length - 1)];
                        listx.Add(b_ui3);
                        break;
                }
            }
            listx.ReDraw2();
        }
        public void PlaySound(string path)
        {
            string _path = ryCommon.RyFiles.GetRealPath(path);
            if (_path.IndexOf("\\") == -1) //如果只是文件名，则播放默认目录下的
            {
                _path = Itrycn_Info.SysDbFolder + @"\animation\sound\" + _path;
            }
            Thread th = new Thread(delegate() { sound.Play(_path); });
            th.Start();
        }
        API.SoundPlay sound = new API.SoundPlay();
        public void LoadFromFile(string path)
        {
            try
            {
                if (!System.IO.File.Exists(path)) { return; }
                //pictureBox1.Image = Image.FromFile(path);return;
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
                //把文件读取到字节数组 
                byte[] data = new byte[fs.Length];
                fs.Read(data, 0, data.Length);
                fs.Close();

                //实例化一个内存流--->把从文件流中读取的内容[字节数组]放到内存流中去 
                MemoryStream ms = new MemoryStream(data);
                //设置图片框 pictureBox1中的图片 
                this.pictureBox1.Image = Image.FromStream(ms);
                //pictureBox1.Image = Image.FromStream(fileStream);
                //fileStream.Close();
                //fileStream.Dispose();
            }
            catch { pictureBox1.Image = null; }
        }
        private int _CloseMinute =-1;
        private bool _HaveCloseMinute = false;
        private void FrmFullScreenTip_Click(object sender, EventArgs e)
        {
            //if (isProcUse) { return; }
            ToolStripItem item = (ToolStripItem)sender;
            DataProvider mydb = new DataProvider();
            IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
            if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
            {
                switch(item.Tag)
                {
                    case int n when n>0:
                        Itrycn_Db.AddTip(TxtTitle.Text, labelTx1.Text, DateTime.Now.AddMinutes(item.Tag.ToInt()), 1, RunTimeStr);
                        this.Close();
                        break;
                    case DateTime n:
                        if (n > DateTime.Now)
                        {
                            Itrycn_Db.AddTip(TxtTitle.Text, labelTx1.Text, n, 1, RunTimeStr);
                            this.Close();
                        }
                        else
                        {
                            MessageBox.Show("当前时间已经过期,请选择合适的时间。","提示",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                        }
                        break;
                }
            }
        }

        //private bool isProcUse = false;
        public int Id { get; set; } = 0;
        public string RunTimeStr { get; set; } = "";
        public int isTemp { get; set; } = 0;
        public string gif_path { get; set; } = "";
        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            LblTime.Text = DateTime.Now.ToString("HH:mm:ss");
            if(_HaveCloseMinute)
            {
                _CloseMinute--;
                if(_CloseMinute>0)
                {
                    LblCloseTime.Text ="本界面将在 "+ GetDateStr(_CloseMinute)+" 后关闭";
                }
                else
                {
                    timer1.Enabled = false;
                    this.Close();
                }
            }
            string GetDateStr(int size)
            {
                string date_str = "";
                int hour = size / 60 / 60;
                if (hour > 0) { date_str =hour+ "小时"; }
                int minute = (size-hour*60) / 60;
                if (minute > 0) { date_str += minute + "分钟"; }
                int second = (size - hour * 60- minute*60);
                if (second > 0) { date_str += second + "秒"; }
                return date_str;
            }
        }

        private void FrmFullScreenTip_Load(object sender, EventArgs e)
        {
            if (gif_path.Length==0)
            {
                string title = TxtTitle.Text;
                string[] rule = RyFiles.ReadAllLines(Itrycn_Info.SysDbFolder + "\\animation\\gif.db");
                if (rule == null) { return; }
                for (int i = 0; i < rule.Length; i++)
                {
                    if (rule[i] == "") { continue; }
                    string[] item = rule[i].Split('|');
                    if (item.Length <= 1) { continue; }
                    string tip = item[0];
                    if (title.IndexOfEx(tip) < 0) { continue; }
                    Random rd = new Random();
                    string filename = item[rd.Next(1, item.Length - 1)];
                    string path = Itrycn_Info.SysDbFolder + "\\animation\\" + filename;
                    if (!System.IO.File.Exists(path)) { continue; }
                    LoadFromFile(path);
                    break;
                }
            }
            else
            {
                LoadFromFile(gif_path);
            }
        }

        private void BtnTuichi_Click(object sender, EventArgs e)
        {
            Button btn = (Button)sender;
            Point p = new Point(0, btn.Height);
            contextMenuStrip1.Show(btn, p);
        }

        private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            DateTime dt = DateTime.Now;
            int n =5- dt.Minute % 5;
            contextMenuStrip1.Items[0].Text = "推迟到" + dt.AddMinutes(n - 1).ToString("HH:mm") + "提醒";
            contextMenuStrip1.Items[0].Tag = dt.AddMinutes(n - 1);
            contextMenuStrip1.Items[0].Visible = n>1;
            contextMenuStrip1.Items[1].Text = "推迟到" + dt.AddMinutes(n).ToString("HH:mm") + "提醒";
            contextMenuStrip1.Items[1].Tag = dt.AddMinutes(n);
        }

        private void FrmFullScreenTip_FormClosing(object sender, FormClosingEventArgs e)
        {
            sound.Stop();
        }
    }
}
