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

namespace TimeClock.DbOp
{
    public partial class FrmSticky : Form
    {
        public FrmSticky()
        {
            InitializeComponent();
            Itrycn_Info.StickyList.Add(this);
            ryCommon.SuperForm superform = new ryCommon.SuperForm(this);
            superform.Resizable = true;
            superform.SetFormMove(this);
            superform.SetFormMove(PnlTop);
            superform.SetFormMove(PnlBottom);
            timer1.Start();
            //RyForm.SetDesktopForm(Handle);
        }
        //定义图像反色函数
        private Bitmap PContray(Image a,Color _rev_color)
        {
            int Height = a.Height;
            int Width = a.Width;
            Bitmap bitmap = new Bitmap(Width, Height);
            Bitmap MyBitmap = (Bitmap)a;
            Color pixel;
            Color img_color = _rev_color;
            for (int x = 1; x < Width; x++)
            {
                for (int y = 1; y < Height; y++)
                {
                    pixel = MyBitmap.GetPixel(x, y);
                    if (pixel.A==0 && pixel.R==0 && pixel.G==0 && pixel.B==0) { continue; }
                    bitmap.SetPixel(x, y, img_color);
                }
            }
            return bitmap;
        }
        /// <summary>
        /// 设置或获取当前便捷的ID号
        /// </summary>
        public int Id { get; set; } = 0;
        /// <summary>
        /// 是否是新增便笺
        /// </summary>
        public bool IsAdd { get; set; } = false;
        /// <summary>
        /// 设置或获取便笺背景色
        /// </summary>
        public Color StickyBackColor
        {
            get { return txtContent.BackColor; }
            set
            {
                BackColor = value;
                PnlTop.BackColor = value;
                PnlBottom.BackColor = value;
                txtContent.BackColor = value;
                var rev_color= GetRevColor();
                LblTopMost.Image = PContray(Itrycn_Db.GetSkinImg("top"), rev_color);
                LblClose.Image = PContray(Itrycn_Db.GetSkinImg("close"), rev_color);
                txtContent.ForeColor = rev_color;
                LblAdd.ForeColor = rev_color;
                LblBold.ForeColor = rev_color;
                LblItalic.ForeColor = rev_color;
                LblUnderline.ForeColor = rev_color;
                LblStrikeout.ForeColor = rev_color;
                LblBullet.ForeColor = rev_color;
                LblImage.ForeColor = rev_color;
            }
        }
        private Color GetRevColor()
        {
            if (StickyBackColor == Color.Blue) { return Color.White; }
            if (StickyBackColor == Color.FromArgb(255,0,128,255)) { return Color.White; }
            if (StickyBackColor == Color.Gray) { return Color.White; }
            if (StickyBackColor == Color.Red) { return Color.White; }
            if (StickyBackColor == Color.FromArgb(255, 255, 0, 128)) { return Color.White; }
            if (StickyBackColor == Color.FromArgb(255, 255, 128, 0)) { return Color.White; }
            if (StickyBackColor == Color.FromArgb(255, 0, 0, 160)) { return Color.White; }
            if (StickyBackColor == Color.FromArgb(255, 128, 0, 255)) { return Color.White; }
            if (StickyBackColor == Color.Navy) { return Color.White; }
            var hsl = ryControls.ColorHelper.RgbToHsl(new ryControls.ColorRGB(StickyBackColor));
            hsl.L = 255 - hsl.L;
            // Color img_color = Color.FromArgb(255 - StickyBackColor.R, 255 - StickyBackColor.G, 255 - StickyBackColor.B);
            return ryControls.ColorHelper.HslToRgb(hsl).GetColor();
        }
        #region 界面按钮设置
        private void LblClose_Click(object sender, EventArgs e)
        {
            DeskShow = 0;
            if (txtContent.Text == "")
            {
                DataProvider mydb = new DataProvider();
                IDbInterface db = TimeClock.Itrycn_Db.CreateDataProvider(TimeClock.Itrycn_Db.dataType);
                if (db.ConnDb(TimeClock.Itrycn_Db.SQLConnStr) == 1)
                {
                    db.DelById("Sticky",Id.ToString());
                }
                db.Free();
            }
            else
            {
                SaveSticky();
            }
            this.Close();
        }
        public bool ProcUse = false;
        private void LblAdd_Click(object sender, EventArgs e)
        {
            FrmSticky frm = new FrmSticky();
            frm.ProcUse = true;
            frm.Id = -1;
            frm.IsAdd = true;
            frm.StickyBackColor = StickyBackColor;
            frm.Location = new Point(Screen.PrimaryScreen.WorkingArea.Width - frm.Width, 20);
            frm.Show();
            frm.ProcUse = false;
        }
        private void SetFontStyle(FontStyle style, bool IsRemove)
        {
            var font = txtContent.SelectionFont ?? this.Font;
            if (IsRemove)
            { txtContent.SelectionFont = new Font(font ?? this.Font, font.Style ^ style); }
            else { txtContent.SelectionFont = new Font(font, font.Style | style); }
        }
        private void LblBold_Click(object sender, EventArgs e)
        {
            SetFontStyle(FontStyle.Bold, txtContent.SelectionFont == null ? false : txtContent.SelectionFont.Bold);          
        }

        private void LblItalic_Click(object sender, EventArgs e)
        {
            SetFontStyle(FontStyle.Italic, txtContent.SelectionFont == null?false: txtContent.SelectionFont.Italic) ;
        }

        private void LblUnderline_Click(object sender, EventArgs e)
        {
            SetFontStyle(FontStyle.Underline, txtContent.SelectionFont == null ? false : txtContent.SelectionFont.Underline);
            
        }

        private void LblStrikeout_Click(object sender, EventArgs e)
        {
            SetFontStyle(FontStyle.Strikeout, txtContent.SelectionFont == null ? false : txtContent.SelectionFont.Strikeout);     
        }
        #endregion
        #region 菜单设置
        private void 撤销ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.Undo();
        }

        private void 重做ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.Redo();
        }

        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.Cut();
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.Copy();
        }

        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.Paste();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.SelectedText = "";
        }

        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.SelectAll();
        }

        private void MenuNote_Opening(object sender, CancelEventArgs e)
        {
            撤销ToolStripMenuItem.Enabled = txtContent.CanUndo;
            重做ToolStripMenuItem.Enabled = txtContent.CanRedo;
            剪切ToolStripMenuItem.Enabled = txtContent.SelectedText != "";
            复制ToolStripMenuItem.Enabled = txtContent.SelectedText != "";
            粘贴ToolStripMenuItem.Enabled = Clipboard.GetText() != "";
            删除ToolStripMenuItem.Enabled = txtContent.SelectedText != "";
            字体ToolStripMenuItem.Enabled = txtContent.SelectedText != "";
            字体颜色ToolStripMenuItem.Enabled = txtContent.SelectedText != "";
            不透明ToolStripMenuItem.Checked = this.Opacity == 1;
            for (int i = 2; i < 透明度ToolStripMenuItem.DropDownItems.Count; i++)
            {
                var item = (ToolStripMenuItem)透明度ToolStripMenuItem.DropDownItems[i];
                item.Checked = this.Opacity.ToString("0%") == item.Text;
            }
        }

        private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            fontDialog1.Font = txtContent.SelectionFont;
            if (fontDialog1.ShowDialog() == DialogResult.OK)
            {
                txtContent.SelectionFont = fontDialog1.Font;
                SaveSticky();
            }
        }

        private void 字体颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            colorDialog1.Color = txtContent.SelectionColor;
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                txtContent.SelectionColor = colorDialog1.Color;
                SaveSticky();
            }
        }
        private void 背景颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            colorDialog1.Color = StickyBackColor;
            if (colorDialog1.ShowDialog() == DialogResult.OK)
            {
                StickyBackColor = colorDialog1.Color;
                SaveSticky();
            }
        }
        #endregion
        private void FrmSticky_Load(object sender, EventArgs e)
        {
        }
        private int DeskShow = 1;
        /// <summary>
        /// 保存便笺
        /// </summary>
        private void SaveSticky()
        {
            if (ProcUse) { return; }
            RyQuickSQL mySQL = new RyQuickSQL("Sticky");
            mySQL.AddField("RichContent", txtContent.Rtf);
            mySQL.AddField("Content", txtContent.Text);
            mySQL.AddField("DeskShow", DeskShow);
            ryCommon.Storage mStor = new ryCommon.Storage();
            mStor.SelectNodeBySet();
            mStor.SetAttrValue("StickyBackColor", ColorTranslator.ToHtml(StickyBackColor));
            mStor.SetAttrValue("Left", this.Left);
            mStor.SetAttrValue("Top", this.Top);
            mStor.SetAttrValue("Width", this.Width);
            mStor.SetAttrValue("Height", this. Height);
            mStor.SetAttrValue("TopMost", this.TopMost);
            mStor.SetAttrValue("Opacity", this.Opacity);
            mySQL.AddField("Setting", mStor.XMLText);
            mySQL.AddField("editTime", DateTime.Now);
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.SQLConnStr) == 1)
            {
                if (IsAdd && Id == -1)
                {
                    mySQL.AddField("addTime", DateTime.Now);
                    var ds = db.ReadData(mySQL.GetInsertSQL() + ";select last_insert_rowid();", mySQL);
                    if (mydb.HaveData(ds))
                    {
                        var row = mydb.GetData(ds);
                        Id = row[0].ToInt();
                    }
                }
                else
                { db.ExecuteNonQuery(mySQL.GetUpdateSQL() + " where id=" + Id, mySQL); }
            }
            db.Free();
        }
        /// <summary>
        /// 加载便笺信息
        /// </summary>
        public void LoadSticky(bool _isAdd,int _Id)
        {
            IsAdd = _isAdd;
            Id = _Id;
            LoadSticky();
        }
        /// <summary>
            /// 加载便笺信息
            /// </summary>
        public void LoadSticky()
        {
            ProcUse = true;
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.SQLConnStr) == 1)
            {
                var ds = db.ReadData("select * from Sticky where id="+Id);
                if(mydb.HaveData(ds))
                {
                    var row = mydb.GetData(ds);
                    #region 读取便笺信息
                    try
                    {
                        txtContent.Rtf = row["RichContent"].ToString();
                    }
                    catch { }
                    ryCommon.Storage mStor = new ryCommon.Storage(row["Setting"].ToString());
                    mStor.SelectNodeBySet();
                    this.Location = new Point(mStor.GetAttrValue("Left", 0), mStor.GetAttrValue("Top", 0));
                    this.Size = new Size(mStor.GetAttrValue("Width", 0), mStor.GetAttrValue("Height", 0));
                    this.TopMost = mStor.GetAttrValue("TopMost", false);
                    this.Opacity = mStor.GetAttrValue("Opacity", 0d);
                    try
                    {
                        StickyBackColor = ColorTranslator.FromHtml(mStor.GetAttrValue("StickyBackColor"));
                    }
                    catch { } 
                    #endregion
                }
            }
            db.Free();
            ProcUse = false;
        }

        private void txtContent_TextChanged(object sender, EventArgs e)
        {
            dt_change = DateTime.Now;
            isChange = true;
        }

        private void LblTopMost_Click(object sender, EventArgs e)
        {
            this.TopMost = !this.TopMost;
            SaveSticky();
        }
        /// <summary>
        /// 便笺状态是否发生改变
        /// </summary>
        bool isChange = false;
        /// <summary>
        /// 经过多少毫秒延迟后来检测状态
        /// </summary>
        int delayTime = 2000;
        DateTime dt_change = DateTime.Now;
        /// <summary>
        /// 便笺状态发生改变时
        /// </summary>
        private void OnChange()
        {
            SaveSticky();
        }
        private void FrmSticky_ResizeEnd(object sender, EventArgs e)
        {
            SaveSticky();
        }

        private void FrmSticky_LocationChanged(object sender, EventArgs e)
        {
            dt_change = DateTime.Now;
            isChange = true;
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            if(isChange && dt_change.AddMilliseconds(delayTime)<DateTime.Now)
            {
                isChange = false;
                SaveSticky();
            }
            if (RyForm.GetActiveWindow() == Handle)
            {
                if (!PnlTop.Visible) PnlTop.Visible = true;
                if (!PnlBottom.Visible) PnlBottom.Visible = true;
            }
            else
            {
                if (PnlTop.Visible) PnlTop.Visible = false;
                if (PnlBottom.Visible) PnlBottom.Visible = false;
            }

        }

        private void 插入时间ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtContent.SelectedText = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        private void 不透明ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Opacity = 1; SaveSticky();
        }

        private void toolStripMenuItem7_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.6; SaveSticky();
        }

        private void toolStripMenuItem8_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.7; SaveSticky();
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.75; SaveSticky();
        }

        private void toolStripMenuItem10_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.8; SaveSticky();
        }

        private void toolStripMenuItem11_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.85; SaveSticky();
        }

        private void toolStripMenuItem12_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.9; SaveSticky();
        }

        private void toolStripMenuItem13_Click(object sender, EventArgs e)
        {
            this.Opacity = 0.95; SaveSticky();
        }

        private void FrmSticky_FormClosed(object sender, FormClosedEventArgs e)
        {
            Itrycn_Info.StickyList.Remove(this);
        }

        private void FrmSticky_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)      //如果窗口大小发生改变后变成最小化，则将窗口重新设置为正常大小
            {
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void LblBullet_Click(object sender, EventArgs e)
        {
            txtContent.SelectionBullet = !txtContent.SelectionBullet;
            //Image img = Image.FromFile(@"C:\Users\fengxin\Desktop\order_714.56449553001px_1229794_easyicon.net.png");
            //API.RTB_InsertImg.InsertImage(this.txtContent, img);
        }

        private void LblImage_Click(object sender, EventArgs e)
        {
            if(openFileDialog1.ShowDialog()==DialogResult.OK)
            {
                Image img =RyFiles.LoadPicFromFile(openFileDialog1.FileName);
                if (img != null)
                { API.RTB_InsertImg.InsertImage(this.txtContent, img); }
                else
                {
                    MessageBox.Show("图片无效。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
