using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SixGroup_Knowledge.PopView;
using System.Data.SqlClient;
using SixGroup_Knowledge.Class;
using SixGroup_Knowledge.Model;
using SixGroup_Knowledge.View;
using System.IO;

namespace SixGroup_Knowledge
{
    public partial class MainForm : Model.Model,ConfirmCallBack
    {

        public static String selectedItemText = "";
        public static MainForm self = null;

        public MainForm()
        {
            InitializeComponent();
        }

        private void backButMouseHover(object sender, EventArgs e)
        {
            PictureBox picBut = sender as PictureBox;
            picBut.Image = Properties.Resources.back_but_hover;
            this.l_pro_text.Text = "返回上层目录";
            this.l_pro_text.Visible = true;
        }

        private void backButMouseLeave(object sender, EventArgs e)
        {
            PictureBox picBut = sender as PictureBox;
            picBut.Image = Properties.Resources.back_but_def;
            this.l_pro_text.Text = "";
            this.l_pro_text.Visible = false;
        }

        private void addDirButMouseHover(object sender, EventArgs e)
        {
            PictureBox picBut = sender as PictureBox;
            picBut.Image = Properties.Resources.add_dir_hover;
            this.l_pro_text.Text = "创建";
            this.l_pro_text.Visible = true;
        }

        private void addDirButMouseLeave(object sender, EventArgs e)
        {
            PictureBox picBut = sender as PictureBox;
            picBut.Image = Properties.Resources.add_dir_def;
            this.l_pro_text.Text = "";
            this.l_pro_text.Visible = false;
        }


        private void loadDirListViewData(String []data)
        {
            for (int i = 0; i < data.Length; i++)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                if (i % 2 == 0)
                    listViewItem.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(95)))), ((int)(((byte)(95)))), ((int)(((byte)(95)))));
                else
                    listViewItem.ForeColor = System.Drawing.Color.FromArgb(60,60,60);
                listViewItem.Text = data[i];
                dir_list_view.Items.Add(listViewItem);
            }
        }
        private void loadDirListViewData(List<String> idList,List<String> nameList,List<String> pidList)
        {
            if (idList.Count < 1)
                return;
            this.dir_list_view.Items.Clear();
            for (int i = 0; i < idList.Count; i++)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Font = new System.Drawing.Font("微软雅黑", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                if (i % 2 == 0)
                    listViewItem.ForeColor = System.Drawing.Color.FromArgb(70, 70, 70);
                else
                    listViewItem.ForeColor = System.Drawing.Color.FromArgb(110, 110, 110);
                listViewItem.Text = nameList[i];
                listViewItem.Tag = new DirListItem(idList[i],pidList[i],nameList[i]);
                dir_list_view.Items.Add(listViewItem);
            }
        }
        private void loadFileListViewData(List<string> idList,List<string> nameList,List<string> didList,List<string> gImageList,List<string> content)
        {
            if (idList.Count < 1)
                this.l_no_file_text.Visible = true;
            else
                this.l_no_file_text.Visible = false;
            this.file_list_view.Items.Clear();
            for (int i = 0; i < idList.Count; i++)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Font = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                if (i % 2 == 0)
                    listViewItem.ForeColor = System.Drawing.Color.FromArgb(70,70,70);
                else
                    listViewItem.ForeColor = System.Drawing.Color.FromArgb(110, 110, 110);
                listViewItem.Text = nameList[i];
                listViewItem.Tag = new FileListItem(idList[i], nameList[i], gImageList[i], didList[i], content[i]);
                listViewItem.ImageIndex=Convert.ToInt32(gImageList[i]);
                file_list_view.Items.Add(listViewItem);
            }
        }
        public void queryAllDirViewData()
        {
            queryAllDirViewData("");
        }
        public void queryAllDirViewData(String pid)
        {
            //存在的Bug： 当删除最后一个目录之后 目录列表不会更行
            string sqlstr = "";
            if (pid == "")
            {
                //如果listview中数据为空时则直接查询根目录
                if (this.dir_list_view.Items.Count < 1)
                    sqlstr = String.Format("select * from dir where pid={0}", "0");
                else
                {
                    //否则查询当前目录
                    pid = (this.dir_list_view.Items[0].Tag as DirListItem).pid;
                    sqlstr = String.Format("select * from dir where pid={0}", pid);
                }
            }
            else
            {
                sqlstr = String.Format("select * from dir where pid={0}",pid);
            }
            SqlDataReader read = null;
            List<String> idList = new List<string>();
            List<String> nameList = new List<string>();
            List<String> pidList = new List<string>();
            try
            {
                read = db.ExecuteReader(sqlstr, null, null);
                while (read.Read())
                {
                    idList.Add(read["id"].ToString());
                    nameList.Add(read["name"].ToString());
                    pidList.Add(read["pid"].ToString());
                }
                loadDirListViewData(idList, nameList, pidList);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (read != null)
                    read.Close();
            }


        }
        public void queryAllFileViewData()
        {
            queryAllFileViewData("");
        }
        public void queryAllFileViewData(string did)
        {
            //存在的Bug： 当删除最后一个目录之后 目录列表不会更行
            string sqlstr = "";
            if (did == "")
            {
                //如果listview中数据为空时则直接查询根目录
                if (this.dir_list_view.Items.Count < 1)
                    sqlstr = String.Format("select * from [file] where did={0}", "0");
                else
                {
                    //否则查询当前目录
                    did = (this.dir_list_view.Items[0].Tag as DirListItem).pid;
                    sqlstr = String.Format("select * from [file] where did={0}", did);
                }
            }
            else
            {
                sqlstr = String.Format("select * from [file] where did={0}", did);
            }
            SqlDataReader read = null;
            try
            {
                read = db.ExecuteReader(sqlstr, null, null);
                fillFileListData(read);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        //填充数据并加载到窗体中
        private void fillFileListData(SqlDataReader read)
        {

            if (read == null)
                return;

            List<string> idList = new List<string>();
            List<string> nameList = new List<string>();
            List<string> didList = new List<string>();
            List<string> gImageList = new List<string>();
            List<string> contentList = new List<string>();
            while (read.Read())
            {
                idList.Add(read["id"].ToString());
                nameList.Add(read["name"].ToString());
                didList.Add(read["did"].ToString());
                gImageList.Add(read["gimage"].ToString());
                contentList.Add(read["content"].ToString());
            }
            read.Close();
            loadFileListViewData(idList, nameList, didList, gImageList, contentList);

        }
        private void pic_add_dir_Click(object sender, EventArgs e)
        {
            CreateDirForm newDirForm = CreateDirForm.getInstance();
            newDirForm.ShowDialog();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            self = this;
            queryAllDirViewData();
            queryAllFileViewData();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            CreateDirForm newDirForm = CreateDirForm.getInstance();
            if (dirListIsSelect())
            {
                ListViewItem selectItem = dir_list_view.Items[this.dir_list_view.SelectedIndices[0]];
                newDirForm.dirListItem = selectItem.Tag as DirListItem;
            }
            newDirForm.ShowDialog();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (this.dir_list_view.SelectedItems.Count < 1)
            {
                MessageForm.show("请先选中文件夹!");
                return;
            }
            ConfirmForm confirm = ConfirmForm.getInstance();
            confirm.callBack = this;
            confirm.setTitle("删除目录会导致该目录下所有文件被删除，确定操作么？");
            confirm.ShowDialog();

        }
        //删除文件夹
        public void ok()
        {
            if (!dirListIsSelect())
                return;

            ListViewItem selectItem = dir_list_view.Items[this.dir_list_view.SelectedIndices[0]];
            DirListItem dirListItem = selectItem.Tag as DirListItem;
            String sqlStr = String.Format("delete from dir where id={0}",dirListItem.id);
            if(db.ExecuteNoneQuery(sqlStr)>0)
            {
                MessageForm.show("文件夹删除成功");
                this.queryAllDirViewData();
            }
            else
            {
                MessageForm.show("文件夹删除失败",MessageForm.ERROR);
            }
        }
        public void cancel()
        {
            
        }

        //修改文件/重命名
        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            if (!dirListIsSelect())
                return;
            ListViewItem selectItem = dir_list_view.Items[this.dir_list_view.SelectedIndices[0]];
            DirListItem dirListItem = selectItem.Tag as DirListItem;

            AlterDirFormcs form = AlterDirFormcs.getInstance(dirListItem);
            if (form == null)
                return;
            form.ShowDialog();
        }


        private void dir_list_view_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (!dirListIsSelect())
                return;
            ListViewItem selectItem = dir_list_view.Items[this.dir_list_view.SelectedIndices[0]];
            DirListItem dirListItem = selectItem.Tag as DirListItem;
            this.L_select_filename.Text = dirListItem.name;
            queryAllDirViewData(dirListItem.id);
            queryAllFileViewData(dirListItem.id);
        }

        private void pic_back_but_Click(object sender, EventArgs e)
        {
            if(this.dir_list_view.Items.Count<1)
            {
                MessageForm.show("没有任何目录,无法返回。");
                return;
            }
            ListViewItem selectItem = dir_list_view.Items[0];
            DirListItem dirListItem = selectItem.Tag as DirListItem;
            if (dirListItem.pid == "0" || dirListItem.pid == "")
            {
                MessageForm.show("已经到了根目录了");
                queryAllFileViewData();
                return;
            }

            //先查询父级目录所属的目录 然后 显示父级目录所属的目录 实现后退功能
            String pid = "0";
            SqlDataReader read = db.ExecuteReader(String.Format("select top 1 pid from dir where id={0}",dirListItem.pid));
            if (read.Read())
            {
                pid = read["pid"].ToString();
            }
            read.Close();
            queryAllDirViewData(pid);
            queryAllFileViewData(pid);
        }

        //添加文件
        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            CreateFileForm form = new CreateFileForm();
            form.ShowDialog();
        }

        /// <summary>
        /// 获得当前目录的id 如果没有目录则返回0
        /// </summary>
        /// <returns></returns>
        public string getDirListId()
        {
            if (this.dir_list_view.Items.Count < 1)
                return "0";
            return (this.dir_list_view.Items[0].Tag as DirListItem).id;
        }

        private void addfileMenu_Click(object sender, EventArgs e)
        {
            if (!dirListIsSelect())
                return;
            CreateFileForm form = new CreateFileForm();
            //ListViewItem selectItem = dir_list_view.Items[this.dir_list_view.SelectedIndices[0]];
            //form.dirListItem = selectItem.Tag as DirListItem;
            form.dirListItem = getDirSelectItem();
            form.ShowDialog();
        }

        private void pic_add_file_Click_Click(object sender, EventArgs e)
        {
            CreateFileForm form = new CreateFileForm();
            form.ShowDialog();
        }

        //删除文件
        private void delfileMenuClick(object sender, EventArgs e)
        {
            if (!fileListIsSelect())
                return;
            
            ConfirmForm confirm = ConfirmForm.getInstance();
            confirm.callBack = new DeleteFileCallBack();
            confirm.setTitle("确定删除该文件么？");
            confirm.ShowDialog();

            
        }
        private class DeleteFileCallBack:ConfirmCallBack
        {
            public void ok()
            {
                FileListItem fileListItem = MainForm.self.getFileSelectItem();
                if (fileListItem == null)
                {
                    MessageForm.show("请先选中要删除的文件。", MessageForm.ERROR);
                    return;
                }
                SQLHelper db = new SQLHelper();
                string sqlstr = String.Format("delete from [file] where id={0}", fileListItem.id);
                if (db.ExecuteNoneQuery(sqlstr) > 0)
                {
                    MessageForm.show("文件删除成功");
                    if (File.Exists(EditForm.FILESAVEPATH + fileListItem.content + ".txt"))
                    {
                        try
                        {
                            File.Delete(EditForm.FILESAVEPATH + fileListItem.content + ".txt");
                        }
                        catch (Exception ex)
                        {
                            MessageForm.show(ex.Message, MessageForm.ERROR);
                        }
                    }
                    MainForm.self.queryAllFileViewData();
                }
                else
                {
                    MessageForm.show("文件删除失败", MessageForm.ERROR);
                }
            }
            public void cancel()
            {

            }
        }
        //判断是否有选中的dirList 选中返回true 
        public Boolean dirListIsSelect()
        {
            return (dir_list_view.SelectedIndices == null || dir_list_view.SelectedIndices.Count < 1) ? false : true;
        }
        public Boolean fileListIsSelect()
        {
            return (file_list_view.SelectedIndices == null || file_list_view.SelectedIndices.Count < 1) ? false : true;
        }
        //获得选中的dirListItem
        public DirListItem getDirSelectItem()
        {
            if (!dirListIsSelect())
                return null;
            return (dir_list_view.Items[this.dir_list_view.SelectedIndices[0]]).Tag as DirListItem;
        }
        public FileListItem getFileSelectItem()
        {
            if (!fileListIsSelect())
                return null;
            return (file_list_view.Items[this.file_list_view.SelectedIndices[0]]).Tag as FileListItem;
        }

        //修改文件
        private void toolStripMenuItem1_Click_1(object sender, EventArgs e)
        {
            AlterFileForm form = new AlterFileForm(getFileSelectItem());
            form.ShowDialog();
        }

        //打开文件
        private void openfileMenu_Click(object sender, EventArgs e)
        {
            if (!fileListIsSelect())
            {
                MessageForm.show("请先选中要打开的文件",MessageForm.ERROR);
                return;
            }
            EditForm form = EditForm.getInstance(getFileSelectItem());
            if (form == null)
                return;
            form.Show();
        }

        //在新窗口中打开文件
        private void openNewForm_Click(object sender, EventArgs e)
        {
            if (!fileListIsSelect())
            {
                MessageForm.show("请先选中要打开的文件", MessageForm.ERROR);
                return;
            }
            EditForm form = EditForm.getInstance(getFileSelectItem(), true);
            if (form == null)
                return;
            form.Show();
        }

        private void seekButClick(object sender, EventArgs e)
        {
            string sqlstr = "";
            //当搜索内容为空时显示当前目录下所有的文件
            if (t_seek.Text.Trim() == "")
            {
                if (dir_list_view.Items.Count < 1)
                {
                    sqlstr = String.Format("select * from [file] where did=0");
                }
                else
                {
                    sqlstr = String.Format("select * from [file] where did={0}", (dir_list_view.Items[0].Tag as DirListItem).pid);
                }
            }
            else
                sqlstr = String.Format("select * from [file] where name like '%{0}%'", t_seek.Text.Trim());
            SqlDataReader read = db.ExecuteReader(sqlstr);
            fillFileListData(read);
        }

        //按照文件类型来显示文件
        private void groupSeekButClick(object sender, EventArgs e)
        {
            if (this.file_list_view.Items.Count < 1)
            {
                MessageForm.show("搜索内容为空", MessageForm.ERROR);
                return;
            }
            PictureBox but = sender as PictureBox;
            string did = (this.file_list_view.Items[0].Tag as FileListItem).did;
            string sqlstr = String.Format("select * from [file] where did={0} and gimage={1}", did, but.Tag.ToString());
            SqlDataReader read = db.ExecuteReader(sqlstr);

            fillFileListData(read);
        }

        private void openDirMenu_Click(object sender, EventArgs e)
        {
            dir_list_view_MouseDoubleClick(null, null);
        }

        //通过双击打开文件
        private void file_list_view_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            openfileMenu_Click(null, null);
        }

        private void p_seek_but_MouseHover(object sender, EventArgs e)
        {
            this.l_pro_text.Text = "在所有目录中搜索文件";
            this.l_pro_text.Visible = true;
        }

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

        private void p_group0_but_MouseHover(object sender, EventArgs e)
        {
            this.l_pro_text.Text = "只显示当前目录下指定该分类的文件";
            this.l_pro_text.Visible = true;
        }

        private void p_group3_but_MouseLeave(object sender, EventArgs e)
        {
            this.l_pro_text.Text = "";
            this.l_pro_text.Visible = false;
        }
        /*
         * 
        private void dir_list_view_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dir_list_view.SelectedIndices != null && dir_list_view.SelectedIndices.Count > 0)
            {
                ListViewItem selectItem = dir_list_view.Items[this.dir_list_view.SelectedIndices[0]];
                selectedItemText = selectItem.Text;
                this.L_select_filename.Text = selectedItemText;
            }
        }
        */
    }
    
}
