using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;


namespace eFrameWork.Manage
{
    public partial class fileManage : System.Web.UI.Page
    {
        public string UserArea = "Manage";
        public string act = eParameters.Request("act");
        public string ModelID = eParameters.Request("ModelID");
        public eUser user;

        private string basePath = "";//当前目录
        public string path = eParameters.QueryString("path");
        string aspxFile = eBase.getAspxFileName();
        string type = eParameters.QueryString("type");
        public eModel model;
        public string modelName = "文件库";
        private DataRow _power;
        private DataRow Power
        {
            get 
            {
                if (_power == null)
                {
                    _power = new DataTable().NewRow();
                    _power.Table.Columns.Add(new DataColumn("list", typeof(string)));
                    _power["list"] = "true";
                    _power.Table.Columns.Add(new DataColumn("new", typeof(string)));
                    _power["new"] = "true";
                    _power.Table.Columns.Add(new DataColumn("rename", typeof(string)));
                    _power["rename"] = "true";
                    _power.Table.Columns.Add(new DataColumn("edit", typeof(string)));
                    _power["edit"] = "true";
                    _power.Table.Columns.Add(new DataColumn("del", typeof(string)));
                    _power["del"] = "true";
                    _power.Table.Columns.Add(new DataColumn("backup", typeof(string)));
                    _power["backup"] = "true";
                    _power.Table.Columns.Add(new DataColumn("upload", typeof(string)));
                    _power["upload"] = "true";
                    _power.Table.Columns.Add(new DataColumn("download", typeof(string)));
                    _power["download"] = "true";
                    _power.Table.Columns.Add(new DataColumn("zip", typeof(string)));
                    _power["zip"] = "true";
                    _power.Table.Columns.Add(new DataColumn("unzip", typeof(string)));
                    _power["unzip"] = "true";
                }
                return _power;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser(eBase.getUserArea(UserArea));
            user.Check();


            eModelInfo customModel = new eModelInfo(user);
            model = customModel.Model;
            if(!model.ModelInfo.Table.Columns.Contains("mc")) model.Power = Power;


            basePath = Server.MapPath("~/")  + "upload\\filemanage\\";
            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);

            if (path.Length > 0) basePath += path.Replace("/", "\\") + "\\";
            #region 安全性
            if (act.Length > 0 && (Request.UrlReferrer == null || Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower()))
            {
                //Response.Write("访问未被许可!");
                //Response.End();
            }
            #endregion
            #region 操作
            string filepath = "";
            string oldname = "";
            string newname = "";
            string sql = "";
            eJson json;
            DataTable tb;
            string reurl = "";
            switch (act)
            {
                case "upload":
                    #region 上传文件
                    StringBuilder sb = new StringBuilder();
                    try
                    {
                        for (int i = 0; i < Request.Files.Count; i++)
                        {
                            HttpPostedFile f = Request.Files[i];
                            filepath = basePath + f.FileName;
                            f.SaveAs(filepath);
                            getFileHTML(sb, f.FileName);
                        }
                    }
                    catch (Exception ex)
                    {
                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    Response.Write(sb.ToString());
                    Response.End();
                    #endregion
                    break;
                case "save":
                    #region 保存编辑
                    filepath = basePath + eParameters.QueryString("name");
                    if (File.Exists(filepath))
                    {

                        string value = eParameters.Form("value");
                        value = value.Replace("0x\\r\\n", "\r\n");

                        json = new eJson();

                        try
                        {
                            StreamWriter sw = new StreamWriter(filepath, false, Encoding.GetEncoding("UTF-8"));
                            sw.Write(value);
                            sw.Flush();
                            sw.Close();
                            json.Add("success", "1");
                            json.Add("message", "保存成功!");
                        }
                        catch (Exception ex)
                        {
                            json.Add("success", "0");
                            json.Add("message", "没有权限!");
                        }

                        eBase.WriteJson(json);
                    }
                    #endregion
                    break;
               
                case "edit":
                    #region 读取编辑文件数据
                    filepath = basePath + eParameters.QueryString("name");
                    if (File.Exists(filepath))
                    {
                        json = new eJson();
                        try
                        {
                            Encoding enc = eBase.GetEncoding(filepath);
                            StreamReader sr = new StreamReader(filepath, enc);
                            string content = sr.ReadToEnd();
                            sr.Close();
                            content = System.Web.HttpUtility.HtmlEncode(content);

                            json.Add("success", "1");
                            json.Add("value", eBase.encode(content));
                        }
                        catch (Exception ex)
                        {
                            json.Add("success", "0");
                            json.Add("message", "没有权限!");
                        }
                        eBase.WriteJson(json);
                    }
                    #endregion
                    break;
                case "addfile":
                    #region 添加文件
                    filepath = basePath + eParameters.QueryString("name");
                    if (!File.Exists(filepath))
                    {
                        try
                        {
                            StreamWriter sw = new System.IO.StreamWriter(filepath, false, Encoding.GetEncoding("UTF-8"));
                            sw.Close();
                        }
                        catch (Exception ex)
                        {

                            Response.Write(ex.Message);
                            Response.End();
                        }
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "addfolder":
                    #region 添加文件夹
                    try
                    {
                        Directory.CreateDirectory(basePath + eParameters.QueryString("name"));
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "rename":
                    #region 重命名文件、文件夹
                    oldname = basePath + eParameters.QueryString("oldname");
                    newname = basePath + eParameters.QueryString("newname");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            Directory.Move(oldname, newname);
                        }
                        if (type == "2")//文件
                        {
                            File.Move(oldname, newname);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "oldname");
                    reurl = eParameters.removeQuery(reurl, "newname");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "bak":
                    #region 备份文件、文件夹
                    oldname = basePath + eParameters.QueryString("name");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            newname = oldname + "_bak";
                            if (!Directory.Exists(newname)) eBase.CopyFolder(oldname, newname);
                        }
                        if (type == "2")//文件
                        {
                            newname = oldname + ".bak";
                            if (!File.Exists(newname)) File.Copy(oldname, newname);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "del":
                    #region 删除文件、文件夹

                    string tmpPath = basePath + eParameters.QueryString("name");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            if (Directory.Exists(tmpPath)) eBase.DeleteFolder(tmpPath);
                        }
                        if (type == "2")//文件
                        {
                            if (File.Exists(tmpPath)) File.Delete(tmpPath);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");

                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "zip":
                    #region 压缩
                    oldname = basePath + eParameters.QueryString("name");
                    try
                    {
                        if (type == "1")//文件夹
                        {
                            newname = oldname + ".zip";
                            FolderToZip(oldname, newname);
                        }
                        if (type == "2")//文件
                        {
                            eFileInfo fi = new eFileInfo(oldname);
                            newname = fi.Path + fi.Name + ".zip";
                            FileToZip(oldname, newname);
                        }
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "unzip":
                    #region 解压
                    oldname = basePath + eParameters.QueryString("name");
                    try
                    {
                        new FastZip().ExtractZip(oldname, basePath, "");//覆盖
                    }
                    catch (Exception ex)
                    {

                        Response.Write(ex.Message);
                        Response.End();
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "type");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "download":
                    #region 下载
                    if (Request.Path != Request.CurrentExecutionFilePath) Response.Redirect(Request.CurrentExecutionFilePath + Request.Url.Query, true);

                    oldname = basePath + eParameters.QueryString("name");
                    FileInfo fileInfo = new FileInfo(oldname);

                   // eBase.Writeln(oldname);
                    //eBase.End();
                    /*System.Web.HttpUtility.UrlDecode(str);
                   Response.Clear();
                   Response.ClearContent();
                   Response.ClearHeaders();
                   //HttpUtility.UrlEncode(fileInfo.Name, System.Text.Encoding.UTF8)
                   Response.Charset = "utf-8";
                   Response.ContentEncoding = System.Text.Encoding.UTF8;
                   Response.AddHeader("Content-Disposition", "attachment;filename=" + (Request.UserAgent.ToLower().IndexOf("msie") > -1 ? Server.UrlPathEncode(fileInfo.Name) : fileInfo.Name));
                   Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                   Response.AddHeader("Content-Transfer-Encoding", "binary");
                   Response.ContentType = "application/octet-stream";
                   Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                   Response.WriteFile(fileInfo.FullName);
                   Response.Flush();
                   Response.End();
                     */
                   
 
                   //Response.ContentType = "application/octet-stream";
                   //Response.AddHeader("Content-Disposition", "attachment;filename=" + (Request.UserAgent.ToLower().IndexOf("msie") > -1 ? Server.UrlPathEncode(fileInfo.Name) : fileInfo.Name));
                   //Response.TransmitFile(oldname);
                   //Response.End();

                   
                    Response.Clear();
                    Response.Expires = 0;   
                    Response.Buffer = true;
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + (Request.UserAgent.ToLower().IndexOf("msie") > -1 ? Server.UrlPathEncode(fileInfo.Name) : fileInfo.Name));
                    //Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                    Response.TransmitFile(oldname);                    
                    Response.End();
                  
                    return;
                    #endregion
                    break;
                case "":
                    List();      

                    break;
            }
            #endregion
        }
        public long GetDirectoryLength(string dirPath)
        {
            long len = 0;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            foreach (FileInfo fi in di.GetFiles())
            {
                len += fi.Length;
            }
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectoryLength(dis[i].FullName);
                }
            }
            return len;
        }
        private void getFileHTML(StringBuilder sb, string name)
        {
            string _path = "../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name;
            FileInfo info = new FileInfo(Server.MapPath( _path));


            eFileInfo fi = new eFileInfo(name);
            sb.Append("<a ext=\"." + fi.Extension.ToLower() + "\" href=\"javascript:;\" class=\"copypath\" data-clipboard-action=\"copy\" data-clipboard-text=\"upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "\" onmousedown=\"contextmenu(event,this,2,'" + name + "');\" title=\"" + name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", info.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", info.LastWriteTime) + "&#10;大小：" + eBase.getFileSize(info.Length) + "\">\r\n");
            sb.Append("<dl>\r\n");
            //if (".jpg.jpeg.gif.bmp.png.tif".IndexOf("." + fi.Extension.ToLower()) > -1) sb.Append("<dt><img class=\"copy\" data-clipboard-action=\"copy\" data-clipboard-text=\"upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "\" src=\"../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "\" border=\"0\" /></dt>\r\n");
            //else  sb.Append("<dt><img class=\"copy\" data-clipboard-action=\"copy\" data-clipboard-text=\"upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "\" src=\"images/none.gif\" style=\"background:transparent url('images/Unknown.gif') no-repeat center center; backg4round-size:100% 100%;object-fit: cover;\" border=\"0\" /></dt>\r\n");
            //background-size:container; 
            //cover            
            //contain
            
            if (".jpg.jpeg.gif.bmp.png.tif".IndexOf("." + fi.Extension.ToLower()) > -1)
            {
                //sb.Append("<dt style=\"background:transparent url('../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "') no-repeat center center;background-size:container;object-fit: cover; background: none\\9;filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale,src='../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "');\"></dt>\r\n");
                sb.Append("<dt><img src=\"../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + name + "\" /></dt>\r\n");
            }
            else
            {
               
                switch (fi.Extension.ToLower())
                {
                    case "zip":
                        sb.Append("<dt class=\"zip\"></dt>\r\n");
                        break;
                    default:
                        sb.Append("<dt class=\"file\"></dt>\r\n");
                        break;
                }
            }



            sb.Append("<dd>" + name + "</dd>\r\n");
            sb.Append("</dl>\r\n");
            sb.Append("</a>\r\n");
        }
        private void List()
        {
            StringBuilder sb = new StringBuilder();
            //sb.Append("<div>当前位置：");
            sb.Append("<div class=\"filemanage_tool\" style=\"margin-tottom:8px;\">");
            if (path.Length > 0)
            {
                //sb.Append("<a href=\"" + aspxFile + "?ModelID=" + ModelID + "\">根目录</a>");
                litNav.Text = "<a href=\"" + aspxFile + (ModelID.Length > 0 ? "?ModelID=" + ModelID : "") + "\">" + (model.ModelInfo.Table.Columns.Contains("mc") ? model.ModelInfo["MC"].ToString() : modelName) + "</a>";
                litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + (ModelID.Length > 0 ? "?ModelID=" + ModelID : "") + "\">根目录</a>";
                string[] arr = path.Split("/".ToCharArray());
                string tmp = "";
                for (int i = 0; i < arr.Length; i++)
                {
                    if (i > 0) tmp += "/";
                    tmp += arr[i];
                    if (i == arr.Length - 1)
                    {
                        //sb.Append(" / " + arr[i]);
                    }
                    else
                    {
                        //sb.Append(" / <a href=\"" + aspxFile + "?ModelID=" + ModelID + "&path=" + tmp + "\">" + arr[i] + "</a>");
                    }
                    litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + "?" + (ModelID.Length > 0 ? "ModelID=" + ModelID + "&" : "") + "path=" + tmp + "\">" + arr[i] + "</a>";
                }
            }
            else
            {
                //sb.Append("根目录");
                litNav.Text = "<a href=\"" + aspxFile + (ModelID.Length > 0 ? "?ModelID=" + ModelID : "") + "\">" + (model.ModelInfo.Table.Columns.Contains("mc") ? model.ModelInfo["MC"].ToString() : modelName) + "</a>";
                litNav.Text += "&nbsp;->&nbsp;<a href=\"" + aspxFile + (ModelID.Length > 0 ? "?ModelID=" + ModelID : "") + "\">根目录</a>";
            }
            if (model.Power.Table.Columns.Contains("new") && model.Power["new"].ToString().ToLower() == "true")
            {
                sb.Append("<a href=\"javascript:;\" class=\"ico addfolder\" onclick=\"addFolder();\" title=\"新建文件夹\"></a>");
                sb.Append("<a href=\"javascript:;\" class=\"ico addfile\" onclick=\"addFile();\" title=\"新建文件\"></a>");
            }

            if (model.Power.Table.Columns.Contains("upload") && model.Power["upload"].ToString().ToLower() == "true")
            {
                sb.Append("<a href=\"javascript:;\" class=\"ico upload\" title=\"上传文件\"><input type=\"file\" title=\"上传文件\" class=\"file\" id=\"imgFile\" name=\"imgFile\" onchange=\"fileManage_upload(this);\" multiple /></a>");
            }

            sb.Append("</div>");
            System.IO.DirectoryInfo dinfo = new DirectoryInfo(basePath);


            sb.Append("<div id=\"filemanage_files\" class=\"filemanage_files\" oncontextmenu=\"return false;\">");
            foreach (DirectoryInfo a in dinfo.GetDirectories())
            {
                sb.Append("<a ext=\"\" href=\"" + aspxFile + "?" + (ModelID.Length > 0 ? "ModelID=" + ModelID + "&" : "") + "path=" + (path.Length > 0 ? path + "/" : path) + a.Name.ToString() + "\" onmousedown=\"contextmenu(event,this,1,'" + a.Name + "');\" title=\"" + a.Name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", a.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", a.LastWriteTime) + "&#10;大小：" + eBase.getFileSize(GetDirectoryLength(a.FullName)) + "\">\r\n");
                sb.Append("<dl>\r\n");
                //sb.Append("<dt><img src=\"images/ts_folder.gif\" border=\"0\" /></dt>\r\n");

                //sb.Append("<dt><img src=\"images/none.gif\" style=\"background:transparent url('images/ts_folder.gif') no-repeat center center; object-fit: cover;\" border=\"0\" /></dt>\r\n");

                sb.Append("<dt class=\"folder\"></dt>\r\n");
                sb.Append("<dd>" + a.Name + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
            }

            foreach (FileInfo a in dinfo.GetFiles())
            {

                getFileHTML(sb, a.Name);
                /*
                sb.Append("<a href=\"javascript:;\" onmousedown=\"contextmenu(event,this,2,'" + a.Name + "');\" title=\"" + a.Name + "\">\r\n");
                sb.Append("<dl>\r\n");
                //sb.Append("<dt><img src=\"../upload/filemanage" + (path.Length > 0 ? "/" + path  : "") + "/" + a.Name + "\" border=\"0\" /></dt>\r\n");
                if (".jpg.jpeg.gif.bmp.png.tif".IndexOf(a.Extension.ToLower()) > -1)
                {
                    //sb.Append("<dt><img src=\"images/none.gif\" style=\"background:transparent url('../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + a.Name + "') no-repeat center center; background-size:auto auto; back5ground-size:100% 100%;object-fit: cover;\" border=\"0\" /></dt>\r\n");
                    sb.Append("<dt><img class=\"copy\" data-clipboard-action=\"copy\" data-clipboard-text=\"upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + a.Name + "\" src=\"../upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + a.Name + "\" border=\"0\" /></dt>\r\n");
                }
                else
                {
                    sb.Append("<dt><img class=\"copy\" data-clipboard-action=\"copy\" data-clipboard-text=\"upload/filemanage" + (path.Length > 0 ? "/" + path : "") + "/" + a.Name + "\" src=\"images/none.gif\" style=\"background:transparent url('images/Unknown.gif') no-repeat center center; backg4round-size:100% 100%;object-fit: cover;\" border=\"0\" /></dt>\r\n");
                }
                sb.Append("<dd>" + a.Name + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
                */
            }
            sb.Append("<div class=\"clear\"></div>\r\n");
            sb.Append("</div>");

            litBody.Text = sb.ToString();
        }
        public void FileToZip(string FromFile, string toZipFile)
        {
            using (ZipFile zip = ZipFile.Create(toZipFile))
            {
                zip.BeginUpdate();
                zip.Add(FromFile, System.IO.Path.GetFileName(FromFile));
                zip.CommitUpdate();
            }
        }
        public void FolderToZip(string folderPath, string toZipFile)
        {
            using (ZipFile zip = ZipFile.Create(toZipFile))
            {
                zip.NameTransform = new ZipNameTransform(basePath);
                zip.BeginUpdate();
                addFolder(folderPath, zip);
                zip.CommitUpdate();
            }
        }
        private void addFolder(string folderPath, ZipFile zip)
        {
            zip.AddDirectory(folderPath);
            DirectoryInfo di = new DirectoryInfo(folderPath);
            foreach (FileInfo item in di.GetFiles())
            {
                zip.Add(item.FullName);
            }
            foreach (DirectoryInfo item in di.GetDirectories())//遍历出所有目录
            {
                addFolder(item.FullName, zip);
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = modelName + " - " + eConfig.manageName();
            }
        }
    }
}