using System;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using TopWinCMS.BLL;
using TopWinCMS.Common;
using System.Threading;

namespace TopWinCMS.WebUI.Admin.Explorer
{
    public partial class ServerExplorer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RightsCheck.CheckWorkPower("P_2");

                TB_Dir.Text = Server.MapPath("~/");

                GV_List.EmptyDataTemplate = TopWinCMS.WebFactory.PageBase.GetTemplate(this);
                GV_Directory.EmptyDataTemplate = TopWinCMS.WebFactory.PageBase.GetTemplate(this);

                BindList();
            }
        }



        /// <summary>
        /// 当前的物理路径
        /// </summary>
        private string Path
        {
            set
            {
                ViewState["Path"] = value;
                TB_Dir.Text = value;
            }
            get
            {
                if (ViewState["Path"] == null)
                {
                    return Server.MapPath("~/");
                }
                else
                {
                    return ViewState["Path"].ToString();
                }
            }
        }

        #region  绑定
        private void BindList()
        {
            DataTable dt_Files = new DataTable();
            DataTable dt_Directorys = new DataTable();
            DataRow dr_Files;
            DataRow dr_Directorys;

            dt_Files.Columns.Add(new DataColumn("ICO", typeof(string)));
            dt_Files.Columns.Add(new DataColumn("FileName", typeof(string)));
            dt_Files.Columns.Add(new DataColumn("FullName", typeof(string)));
            dt_Files.Columns.Add(new DataColumn("FileSize", typeof(string)));
            dt_Files.Columns.Add(new DataColumn("DownLoad", typeof(string)));
            dt_Files.Columns.Add(new DataColumn("Move", typeof(string)));
            dt_Files.Columns.Add(new DataColumn("LastWriteTime", typeof(DateTime)));

            dt_Directorys.Columns.Add(new DataColumn("DirectoryName", typeof(string)));
            dt_Directorys.Columns.Add(new DataColumn("FullName", typeof(string)));

            //针对当前目录建立目录引用对象
            string strDir = Path;

            DirectoryInfo dirInfo = new DirectoryInfo(strDir);
            //循环判断当前目录下的文件和目录
            FileInfo fi;
            DirectoryInfo di;

            dr_Directorys = dt_Directorys.NewRow();
            dr_Directorys["DirectoryName"] = "向上";

            string subdir = strDir.Substring(0, strDir.LastIndexOf("\\"));  //取出上一层目录

            dr_Directorys["FullName"] = subdir;

            dt_Directorys.Rows.Add(dr_Directorys);

            foreach (FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
            {
                //如果是文件
                if (fsi is FileInfo)
                {
                    dr_Files = dt_Files.NewRow();
                    fi = fsi as FileInfo;

                    dr_Files["ICO"] = fi.Extension.TrimStart('.');
                    dr_Files["FileName"] = string.Concat("<a href=\"FileEditor.aspx?dir=", fi.FullName, "\" target=_blank>", fi.Name, "</a>");
                    dr_Files["FullName"] = fi.FullName;

                    //取得文件的大小
                    dr_Files["FileSize"] = FileIO.FileSize(fi.Length);
                    dr_Files["DownLoad"] = string.Concat("<a href=\"DownloadFile.aspx?dir=", fi.FullName, "\" target=_blank><img src=\"../Images/FileICO/download.png\" /></a>");

                    dr_Files["Move"] = "Move";
                    //取得文件的创建时间
                    dr_Files["LastWriteTime"] = fi.LastWriteTime;

                    dt_Files.Rows.Add(dr_Files);
                }
                else
                {
                    dr_Directorys = dt_Directorys.NewRow();

                    di = fsi as DirectoryInfo;

                    dr_Directorys["DirectoryName"] = di.Name;
                    dr_Directorys["FullName"] = di.FullName;

                    dt_Directorys.Rows.Add(dr_Directorys);
                }
            }


            PageNavigation1.RecordCount = dt_Files.Rows.Count;

            GV_List.DataSource = dt_Files;
            GV_List.DataBind();

            GV_Directory.DataSource = dt_Directorys;
            GV_Directory.DataBind();

            MyJavascript.RegJS(UpdatePanel1, "attachMouseEvent('" + GV_List.ClientID + "');");
            MyJavascript.RegJS(UpdatePanel1, "attachMouseEvent('" + GV_Directory.ClientID + "');");
            //Label1.Text = "没有文件！";
        }
        #endregion

        protected bool CFile(object FullName)
        {
            FileInfo fi = new FileInfo(FullName.ToString());
            switch (fi.Extension.ToLower())
            {
                case ".rar":
                    return true;

                case ".zip":
                    return true;
                case ".7z":
                    return true;

            }

            return false;
        }

        protected void GV_List_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                File.Delete(GV_List.DataKeys[e.RowIndex].Value.ToString());

                MsgBox.Alert("删除成功！", UpdatePanel1);

                BindList();
            }
            catch (Exception ex)
            {
                MsgBox.Alert("删除失败，错误信息：" + ex.Message, UpdatePanel1);
            }
        }


        protected void PageNavigation1_PageChanging(object src, TopWinCMS.WebControls.PageChangingEventArgs e)
        {
            GV_List.PageIndex = e.NewPageIndex - 1;
            BindList();//要重新绑定数据

        }

        protected void BT_OK_Click(object sender, EventArgs e)
        {
            Directory.Move(TB_OldFilePath.Text, TB_FilePath.Text.Trim());

            Panel1.Visible = false;
            TopWinCMS.Common.MsgBox.Alert("操作成功！", UpdatePanel1);
            BindList();
        }
        protected void BT_Cancel_Click(object sender, EventArgs e)
        {
            GV_List.Visible = true;
            Panel1.Visible = false;
        }
        protected void GV_List_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strPath = null;


            if (e.CommandName == "Move")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                strPath = GV_List.DataKeys[index].Value.ToString();
                Panel1.Visible = true;
                TB_OldFilePath.Text = strPath;
                TB_FilePath.Text = strPath;
            }
            if (e.CommandName == "CFile")
            {
                if (TopWinCMS.Common.Winrar.Exists() == true)
                {

                    //Thread th = new Thread(new ParameterizedThreadStart(JieYa));
                    //th.IsBackground = true;
                    //th.Start(e.CommandArgument);

                    string err = JieYa(e.CommandArgument);
                    if (string.IsNullOrEmpty(err))
                    {
                        MsgBox.Alert("解压已执行完成.", this.UpdatePanel1);
                    }
                    else
                    {
                        MsgBox.Alert(err, this.UpdatePanel1);
                    }
                }
            }
        }


        private string JieYa(object FullName)
        {
            Winrar winrar = new Winrar();
            FileInfo fi = new FileInfo(FullName.ToString());
            return winrar.unCompressRAR(fi.DirectoryName, fi.DirectoryName, fi.Name);

        }

        protected void GV_Directory_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strPath = null;
            if (e.CommandName == "GoTo")
            {
                strPath = e.CommandArgument.ToString();

                //MsgBox.Alert(strPath, UpdatePanel1);
                Path = strPath;
                PageNavigation1.PageNo = 1;
                GV_List.PageIndex = 0;
                BindList();

            }
        }

        protected void BT_GoTo_Click(object sender, EventArgs e)
        {
            if (Directory.Exists(TB_Dir.Text.Trim()))
            {
                Path = TB_Dir.Text.Trim();
                PageNavigation1.PageNo = 1;
                GV_List.PageIndex = 0;
                BindList();
            }
            else
            {
                MsgBox.Alert("目录不存在！", UpdatePanel1);
            }
        }

        protected void GV_List_Sorting(object sender, GridViewSortEventArgs e)
        {

        }

        protected void GV_List_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                TableCell myTableCell = e.Row.Cells[4];

                ImageButton btnDel = myTableCell.Controls[0] as ImageButton;

                btnDel.OnClientClick = "if(confirm('您确定要删除？')==false){ return;}";
            }
        }


    }
}