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;
using SixGroup_Knowledge.Class;
using System.Data.SqlClient;
using SixGroup_Knowledge.PopView;
using System.IO;

namespace SixGroup_Knowledge.View
{
    public partial class EditForm : Model.Model
    {
        /*
         * 待解决的问题：
         */
        public List<FileTabItem> fileTabItemList = new List<FileTabItem>();
        public static List<EditForm> editFormList = new List<EditForm>();
        private static int limitTabCount = 4;

        protected static SQLHelper db = new SQLHelper();
        protected static string fileSavePath = Application.StartupPath + "\\DataBase\\files\\";
        protected static int onAlterSaveType = 0;

        private int tarX = 0;
        private int tarY = 0;
        public static int ALTERSAVE
        {
            get { return onAlterSaveType; }
        }
        public static string FILESAVEPATH
        {
            get { return fileSavePath; }
        }
        public static int LIMITTABCOUNT
        {
            get { return limitTabCount; }
        }
        public static EditForm getInstance(FileListItem fileListItem)
        {
            if (fileListItem == null)
                return null;
            if (editFormList.Count < 1)
            {
                EditForm editForm = new EditForm(fileListItem);
                editFormList.Add(editForm);
            }
            else
            {
                //如果文件选项卡以满则自动切换文件到新的窗口显示
                if (editFormList[0].getTabCount() >= LIMITTABCOUNT)
                {
                    return autoFindNewForm(fileListItem, 0);
                }
                else
                {
                    editFormList[0].addFileTab(fileListItem);
                }
            }
            return editFormList[0];
        }
        public static EditForm getInstance(FileListItem fileListItem, Boolean isNew)
        {
            if (fileListItem == null)
                return null;
            if (isNew)
            {
                EditForm editForm = new EditForm(fileListItem);
                editFormList.Add(editForm);
                return editForm;
            }
            else
            {
                return getInstance(fileListItem);
            }
        }
        //递归查找获得可用的窗口
        protected static EditForm autoFindNewForm(FileListItem fileListItem, int level)
        {
            //当窗口不存在时创建
            if (level >= editFormList.Count)
            {
                EditForm editForm = new EditForm(fileListItem);
                editFormList.Add(editForm);
                return editForm;
            }
            //当选项卡以满时继续寻找
            if (editFormList[level].getTabCount() >= LIMITTABCOUNT)
            {
                return autoFindNewForm(fileListItem, level + 1);
            }
            //选项卡未满 直接添加文件
            //editFormList[level].addFileTab(editFormList[level], fileListItem);
            editFormList[level].addFileTab(fileListItem);
            return editFormList[level];
        }
        protected EditForm(FileListItem fileListItem)
        {
            InitializeComponent();
            addFileTab(fileListItem);
            //addFileTabLoadData(this.tabLayout, fileListItem);
            setGroupImage(fileListItem.gimage);
            this.l_cur_filename.Text = fileListItem.name;
            this.l_cur_filename.Tag = fileListItem;
            this.timer1.Enabled = true;
        }
        protected void setGroupImage(string gid)
        {
            switch(gid)
            {
                case "0":
                    this.p_groupImage.Image = Properties.Resources.group3;
                    break;
                case "1":
                    this.p_groupImage.Image = Properties.Resources.group4;
                    break;
                case "2":
                    this.p_groupImage.Image = Properties.Resources.group2;
                    break;
                case "3":
                    this.p_groupImage.Image = Properties.Resources.group1;
                    break;
                case "4":
                    this.p_groupImage.Image = Properties.Resources.group5;
                    break;
            }
        }
        public int getTabCount()
        {
            return this.tabLayout.Controls.Count;
        }
        protected void addFileTab(FileListItem fileListItem)
        {
            /*
            addFileTabLoadData(editFormList[0].tabLayout, fileListItem);
            loadFileContent(editFormList[0], fileListItem);
             */
            saveFileButClick(null, null);
            addFileTabLoadData(this.tabLayout, fileListItem);
            loadFileContent(this, fileListItem);
            loadContentLenght();
        }

        /*
        protected void addFileTab(EditForm editForm, FileListItem fileListItem)
        {
            if (editForm == null || fileListItem == null)
                return;
            addFileTabLoadData(editForm.tabLayout, fileListItem);
            loadFileContent(editForm, fileListItem);
        }
         */

        protected void addFileTabLoadData(FlowLayoutPanel pLayout,FileListItem fileListItem)
        {
            if (pLayout == null || fileListItem == null)
                return;
            FlowLayoutPanel layout = new FlowLayoutPanel();
            Label label = new Label();
            PictureBox pic = new PictureBox();
            //设置layout属性和添加layout子控件
            layout.AutoSize = true;
            layout.Controls.Add(label);
            layout.Controls.Add(pic);
            //讲layout加入到显示列表中
            pLayout.Controls.Add(layout);

            //设置label属性
            if (fileListItem.name.Length > 10)
                label.Text = fileListItem.name.Substring(0, 10)+"...";
            else
                label.Text = fileListItem.name;

            label.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            label.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(0)))), ((int)(((byte)(64)))));
            label.Padding = new System.Windows.Forms.Padding(5, 5, 0, 0);
            label.AutoSize = true;
            label.MouseLeave += new System.EventHandler(this.labelFileNameMouseLeave);
            label.MouseHover += new System.EventHandler(this.labelFileNameMouseHover);
            label.Click += new System.EventHandler(this.fileNameClick);

            //设置关闭按钮属性
            pic.Image = Properties.Resources.file_close_but;
            pic.Size = new System.Drawing.Size(25, 25);
            pic.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            pic.Visible = false;
            pic.MouseLeave += new System.EventHandler(this.file_close_but_MouseLeave);
            pic.MouseHover += new System.EventHandler(this.file_close_but_MouseHover);
            pic.Click += new System.EventHandler(this.file_close_but_Click);

            //创建FileTabItem对象保存文件选项卡属性
            FileTabItem fileTabItem = new FileTabItem(fileListItem, layout, label, pic);
            fileTabItemList.Add(fileTabItem);
            //在label和pic中保存文件属性
            pic.Tag = fileListItem;
            label.Tag = fileTabItem;
        }

        protected static void loadFileContent(EditForm editForm,FileListItem fileListItem)
        {
            if (editForm == null || fileListItem == null)
                return;
            /*string sqlstr = String.Format("select top 1 content from [file] where id={0}", fileListItem.id);
            SqlDataReader read = db.ExecuteReader(sqlstr);

            if (read.Read())
            {
                editForm.rich_edit_content.Text = read[0].ToString();
            }
            read.Close();
             * */
            string filePath = fileSavePath + fileListItem.content.Trim() + ".txt";
            if (File.Exists(filePath))
                editForm.rich_edit_content.LoadFile(filePath);
            else
                editForm.rich_edit_content.Text = "";
            //保存当前打开文件的属性
            editForm.l_cur_filename.Tag = fileListItem;
            editForm.l_cur_filename.Text = fileListItem.name;
            editForm.rich_edit_content.SelectionStart = editForm.rich_edit_content.TextLength;
        }

        private void saveFileButClick(object sender, EventArgs e)
        {
            FileListItem fileListItem = this.l_cur_filename.Tag as FileListItem;
            if (!this.rich_edit_content.Modified)
                return;
            if (fileListItem == null)
            {
                MessageForm.show("没有要保存的文件", MessageForm.ERROR);
                return;
            }
            string filePath = existsFile(fileSavePath + fileListItem.content + ".txt");
            this.rich_edit_content.SaveFile(filePath);
            MessageForm.show("文件保存成功");
            /*
            string sqlstr = String.Format("update [file] set content='{0}' where id={1}",
                this.rich_edit_content.Rtf, fileListItem.id);

            if (db.ExecuteNoneQuery(sqlstr) > 0)
                MessageForm.show("文件保存成功");
            else
                MessageForm.show("文件保存失败");
             */
        }
        
        private void file_close_but_MouseHover(object sender, EventArgs e)
        {
            PictureBox but = sender as PictureBox;
            but.Image = Properties.Resources.file_close_but_hover;
        }

        private void file_close_but_MouseLeave(object sender, EventArgs e)
        {
            PictureBox but = sender as PictureBox;
            but.Image = Properties.Resources.file_close_but;
        }

        private void labelFileNameMouseHover(object sender, EventArgs e)
        {
            FileTabItem fileTabItem = (sender as Label).Tag as FileTabItem;
            fileTabItem.closeBut.Image = Properties.Resources.file_close_but_hover;
            fileTabItem.closeBut.Visible = true;
            if (fileTabItem.closeBut.Tag as FileTabItem == null)
                fileTabItem.closeBut.Tag = fileTabItem;
        }

        private void labelFileNameMouseLeave(object sender, EventArgs e)
        {
            FileTabItem fileTabItem = (sender as Label).Tag as FileTabItem;
            fileTabItem.closeBut.Image = Properties.Resources.file_close_but;
        }

        private void file_close_but_Click(object sender, EventArgs e)
        {
            //关闭文件选项卡时根据当前文件和关闭文件选项卡相对比 并判断是否修改
            FileListItem fileListItem = this.l_cur_filename.Tag as FileListItem;
            FileTabItem fileTabItem = (sender as PictureBox).Tag as FileTabItem;

            if (fileListItem.id == fileTabItem.fileListItem.id && this.rich_edit_content.Modified)
            {
                //创建回调对象
                ConfirmInterface callBack = new ConfirmInterface(new CloseFormNeedItem(fileTabItem, this), ALTERSAVE);

                ConfirmForm confirm = ConfirmForm.getInstance();
                confirm.callBack = callBack;
                confirm.Show();
            }
            else
            {
                this.tabLayout.Controls.Remove(fileTabItem.layout);
                this.fileTabItemList.Remove(fileTabItem);
                onCloseFile();
            }
            
        }

        protected void onCloseFile()
        {
            if (getTabCount() == 0)
            {
                this.Close();
                return;
            }
            this.l_cur_filename.Text = fileTabItemList[0].fileListItem.name;
            this.l_cur_filename.Tag = fileTabItemList[0].fileListItem;
            setGroupImage(fileTabItemList[0].fileListItem.gimage);
            loadFileContent(this, fileTabItemList[0].fileListItem);

        }
        private void EditForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            editFormList.Remove(this);
        }

        private void fileNameClick(object sender, EventArgs e)
        {
            saveFileButClick(null, null);
            FileTabItem fileTabItem = (sender as Label).Tag as FileTabItem;
            this.l_cur_filename.Text = fileTabItem.fileListItem.name;
            this.l_cur_filename.Tag = fileTabItem.fileListItem;
            setGroupImage(fileTabItem.fileListItem.gimage);
            loadFileContent(this, fileTabItem.fileListItem);
        }

        private class ConfirmInterface:ConfirmCallBack
        {
            public object tag = null;
            public int type = 0;

            public ConfirmInterface(object tag, int type)
            {
                this.tag = tag;
                this.type = type;
            }
            public void ok()
            {
                switch (type)
                {
                    //修改关闭
                    case 0:
                        CloseFormNeedItem item = tag as CloseFormNeedItem;
                        item.editForm.saveFileButClick(null, null);
                        item.editForm.tabLayout.Controls.Remove(item.fileTabItem.layout);
                        item.editForm.fileTabItemList.Remove(item.fileTabItem);
                        item.editForm.onCloseFile();
                        break;
                }
            }
            public void cancel()
            {
                CloseFormNeedItem item = tag as CloseFormNeedItem;
                item.editForm.tabLayout.Controls.Remove(item.fileTabItem.layout);
                item.editForm.fileTabItemList.Remove(item.fileTabItem);
                item.editForm.onCloseFile();
            }
        }

        private class CloseFormNeedItem
        {
            public FileTabItem fileTabItem = null;
            public EditForm editForm = null;
            public CloseFormNeedItem(FileTabItem fileTabItem,EditForm editForm)
            {
                this.editForm = editForm;
                this.fileTabItem = fileTabItem;
            }
        }

        private void rich_edit_content_TextChanged(object sender, EventArgs e)
        {
            loadContentLenght();
        }
        public void loadContentLenght()
        {
            int index = this.rich_edit_content.GetFirstCharIndexOfCurrentLine();
            int line = this.rich_edit_content.GetLineFromCharIndex(index) + 1;
            int column = this.rich_edit_content.SelectionStart - index + 1;
            this.l_textLength.Text = "当前字数：" + this.rich_edit_content.TextLength
                + "   行数：" + this.rich_edit_content.Lines.Length
                + "      L：" + line + " C：" + column;
        }
        private void rich_edit_content_SelectionChanged(object sender, EventArgs e)
        {
            loadContentLenght();
        }
        private void p_redo_but_Click(object sender, EventArgs e)
        {
            this.rich_edit_content.Redo();
        }

        private void p_undo_but_Click(object sender, EventArgs e)
        {
            this.rich_edit_content.Undo();
        }

        private void p_font_but_Click(object sender, EventArgs e)
        {
            this.fontDialog1.Font = this.rich_edit_content.SelectionFont;
            if (this.fontDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                this.rich_edit_content.SelectionFont = this.fontDialog1.Font;
        }
        
        private void p_color_but_Click(object sender, EventArgs e)
        {
            this.colorDialog1.Color = this.rich_edit_content.SelectionColor;
            if (this.colorDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                this.rich_edit_content.SelectionColor = this.colorDialog1.Color;
        }

        private void p_image_but_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Filter = "图片(*.bmp;*.jpg;*.png;)|*.bmp;*.jpg;*.png;";
            if (this.openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Image image = Image.FromFile(this.openFileDialog1.FileName);
                Clipboard.SetDataObject(image);
                rich_edit_content.Paste();
            }
        }

        private static string existsFile(string path)
        {
            if (!Directory.Exists(fileSavePath))
            {
                Directory.CreateDirectory(fileSavePath);
            }
            if (!File.Exists(path))
            {
                FileStream myFs = new FileStream(path, FileMode.Create);
                myFs.Close();
            }
            return path;
        }


        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Location.X >= tarX)
                timer1.Enabled = false;
            else
                this.Location = new Point(this.Location.X + 5, this.Location.Y + 5);
        }

        private void EditForm_Load(object sender, EventArgs e)
        {
            tarX = this.Location.X + 30;
            tarY = this.Location.Y + 30;
        }

        private void p_font_but_MouseHover(object sender, EventArgs e)
        {
            PictureBox but = sender as PictureBox;
            this.label2.Visible = true;
            switch (but.Name)
            {
                case "p_image_but":
                    this.label2.Text = "插入图片";
                    break;
                case "p_color_but":
                    this.label2.Text = "设置字体颜色";
                    break;
                case "p_font_but":
                    this.label2.Text = "设置字体";
                    break;
                case "p_undo_but":
                    this.label2.Text = "撤销";
                    break;
                case "p_redo_but":
                    this.label2.Text = "返回";
                    break;
                case "p_save_file_but":
                    this.label2.Text = "保存";
                    break;
            }
        }

        private void p_undo_but_MouseLeave(object sender, EventArgs e)
        {
            this.label2.Visible = false;
            this.label2.Text = "";
        }

        private void saveMenu_Click(object sender, EventArgs e)
        {
            saveFileButClick(null, null);
        }

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

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.p_undo_but_Click(null,null);
        }

        private void 返回ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.p_redo_but_Click(null, null);
        }

        private void 颜色ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.p_color_but_Click(null, null);
        }

        private void 字体ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.p_font_but_Click(null, null);
        }

        private void insertImage_Click(object sender, EventArgs e)
        {
            this.p_image_but_Click(null, null);
        }



        /*
             * private void fileNameBlockMouseHover(object sender, EventArgs e)
            {
                /*FlowLayoutPanel layout = sender as FlowLayoutPanel;
                Control[] controls = layout.Controls.Find("file_close_but", true);
                PictureBox pic = controls[0] as PictureBox;
                pic.Visible = true;
            }

            private void fileNameBlockMouseLeave(object sender, EventArgs e)
            {
                /*FlowLayoutPanel layout = sender as FlowLayoutPanel;
                Control[] controls = layout.Controls.Find("file_close_but", true);
                PictureBox pic = controls[0] as PictureBox;
                pic.Visible = false;

            }
        */

    }
}
