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 LitJson;


namespace eFrameWork.Customs
{
    public partial class eFileManage : System.Web.UI.Page
    {
        public string UserArea = "Application";
        public string act = eParameters.Request("act");
        public string ModelID = eParameters.Request("ModelID");
        public string AppItem = eParameters.Request("AppItem");
        public eUser user;
        public string siteid = "";
        public string sitefolder = "";
        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 dynamic _power;
        public dynamic Power
        {
            get
            {
                if (_power == null)
                {
                    _power = new ePower();
                    _power["list"] = true;
                    _power["new"] = true;
                    _power["rename"] = true;
                    _power["edit"] = true;
                    _power["del"] = true;
                    _power["backup"] = true;
                    _power["upload"] = true;
                    _power["download"] = true;
                    _power["zip"] = true;
                    _power["unzip"] = true;
                }
                return _power;
            }
        }
        public string ajax = eParameters.QueryString("ajax");
        public eExtensionsList allowExts = new eExtensionsList();
        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;

            string path = model.Propertys.basePath.ToString();
            if (path.Length < 2)
            {
                path = "files";
            }
            else
            {
                path = path.Replace("/", "\\");
                path = path.TrimStart('\\');
                path = path.TrimEnd('\\');
            }
            basePath = eRunTime.sitePath + path + "\\";// eRunTime.fileManagePath;

            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);
            if (path.IndexOf("..") > -1) path = "";//禁止越权上级目录
            if (path.Length > 0) path = path.toUrlFormat();
            if (path.EndsWith("/")) path = path.Substring(0, path.Length - 1);

            if (!Directory.Exists(basePath + path.toLocalFormat())) path = "";
            if (path.Length > 0) basePath += path.toLocalFormat() + "\\";


 
            #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 reurl = "";
            string ext = "";
            eFileResult result;
            JsonData json;
            string name = eParameters.QueryString("name");//文件名，文件夹名
            if (name.Contains("..")) eRunTime.endError("文件名无效!");//禁止上级目录
            switch (act)
            {
                case "reload"://OK
                     #region 重新加载
                     JsonData jd = new JsonData();
                        jd.Add("success", "1");
                        jd.Add("body", getFiles());
                        //jd.Add("table", eBase.encode(eListControl.getControlHTML()));
                        Response.Write(jd.ToJson());
                        Response.End();
                    #endregion
                    break;
                case "upload"://OK
                    #region 上传文件
                    StringBuilder sb = new StringBuilder();
                    JsonData files = JsonMapper.ToObject("[]");
                    for (int i = 0; i < Request.Files.Count; i++)
                    {
                        HttpPostedFile file = Request.Files[i];
                        ext = file.FileName.fileExtension();
                        filepath = basePath + file.FileName.File();
                        result = file.safeSaveAs(filepath, allowExts);
                        if (!result.Success) eRunTime.endError(result.Message);
                        if (eConfig.saveSource())
                        {
                            string sourcePath = eRunTime.sourcePathCurrent;
                            if (!Directory.Exists(sourcePath)) Directory.CreateDirectory(sourcePath);
                            string _pathname = sourcePath + file.FileName.File();
                            file.safeSaveAs(_pathname);
                        }
                        #region 文件返回JSON
                        JsonData item = new JsonData();
                        item.Add("name", file.FileName);
                        item.Add("ext", ext);
                        item.Add("size", file.Size());
                        item.Add("time", string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now));
                        item.Add("url", filepath.toUrl());
                        files.Add(item);
                        #endregion
                        getFileHTML(sb, file.FileName);
                    }
                    if (ajax == "true")
                    {
                        //eResult.Success("文件上传成功!");
                        json = new JsonData();
                        json.Add("errcode", "0");
                        json.Add("message", "文件上传成功!");
                        json["files"] = files;
                        eResult.WriteJson(json);
                    }
                    //Response.Redirect(Request.UrlReferrer.PathAndQuery, true);
                    Response.Write(sb.ToString());
                    Response.End();
                    #endregion
                    break;
                case "save"://OK
                    #region 保存
                    filepath = basePath + name;
                    string value = eParameters.Form("value");
                    //value = value.Replace("0x\\r\\n", "\r\n");
                    value = eBase.decode(value);
                    value = value.Replace("\n", "\r\n");
                    result = eFileHelper.save(filepath, value);
                    if (!result.Success) eRunTime.endError(result.Message);
                    eResult.Success("保存成功!");
                    #endregion                   
                    break;
                case "edit"://OK
                    #region 读取
                    filepath = basePath + name;
                    result = eFileHelper.read(filepath);
                    if (!result.Success) eRunTime.endError(result.Message);
                    string content = result.Content;
                    content = HttpUtility.HtmlEncode(content);
                    JsonData obj = new JsonData();
                    obj["success"] = 1;
                    obj["errcode"] = "0";
                    obj["message"] = "读取成功!";
                    obj["value"] = content;
                    eResult.WriteJson(obj);
                    #endregion
                    break;
                case "newfile"://OK
                   #region 新建文件
                    filepath = basePath + name;
                    result = eFileHelper.create(filepath);
                    if (!result.Success) eRunTime.endError(result.Message);
                    if (ajax == "true") eResult.Success("文件创建成功!");
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "newfolder"://OK
                    #region 添加文件夹
                    result = eFolderHelper.create(basePath + name);
                    if (!result.Success) eRunTime.endError(result.Message);
                    if (ajax == "true") eResult.Success("文件夹创建成功!");   
                    reurl = Request.Url.PathAndQuery;
                    reurl = eParameters.removeQuery(reurl, "act");
                    reurl = eParameters.removeQuery(reurl, "name");
                    Response.Redirect(reurl, true);
                    #endregion
                    break;
                case "rename"://OK
                    #region 重命名文件、文件夹
                    oldname = basePath + eParameters.QueryString("oldname");
                    newname = basePath + eParameters.QueryString("newname");
                    if (type == "1")//文件夹
                    {
                        result = eFolderHelper.rename(oldname, newname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        //newname += oldname.fileExtension();
                        result = eFileHelper.rename(oldname, newname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件" + (type == "1" ? "夹" : "") + "重命名成功!");
                    }
                    //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"://OK
                    #region 备份文件、文件夹
                    oldname = basePath + name;
                    if (type == "1")//文件夹
                    {
                        result = eFolderHelper.backup(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        result = eFileHelper.backup(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true")
                    {
                        eResult.Success("文件" + (type == "1" ? "夹" : "") + "备份成功!");
                    }
                    //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"://OK
                    #region 删除文件、文件夹
                    string tmpPath = basePath + name;
                    if (type == "1")//文件夹
                    {
                        result = eFolderHelper.remove(tmpPath);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        result = eFileHelper.remove(tmpPath);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (ajax == "true") eResult.Success("文件" + (type == "1" ? "夹" : "") + "删除成功!");
                    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"://OK
                    #region 压缩
                    oldname = basePath + name;
                    if (type == "1")//文件夹
                    {
                        newname = oldname + ".zip";
                        //eZipHelper.folderToZip(oldname, newname);
                        result = eZipHelper.folderToZip(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }
                    if (type == "2")//文件
                    {
                        eFileInfo fi = new eFileInfo(oldname);
                        newname = fi.Path + fi.Name + ".zip";
                        //eZipHelper.fileToZip(oldname, newname);
                        result = eZipHelper.fileToZip(oldname);
                        if (!result.Success) eRunTime.endError(result.Message);
                    }                        
                    if (ajax == "true") eResult.Success("文件" + (type == "1" ? "夹" : "") + "压缩成功!");
                    //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"://OK
                    #region 解压
                    oldname = basePath + name;
                    //new FastZip().ExtractZip(oldname, basePath, "");//覆盖
                    //result = eZipHelper.extract(oldname, basePath);
                    result = eZipHelper.extract(oldname);
                    if (!result.Success) eRunTime.endError(result.Message);
                    if (ajax == "true") eResult.Success("文件解压成功!");
                    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"://OK
                    #region 下载
                    if (Request.Path != Request.CurrentExecutionFilePath) Response.Redirect(Request.CurrentExecutionFilePath + Request.Url.Query, true);
                    oldname = basePath + name;
                    result= eFileHelper.download(oldname);
                    if (!result.Success) eRunTime.endError(result.Message);
                    #endregion
                    break;
                case "":
                    litBody.Text = List();
                    break;
            }
            #endregion
        }        
        private void getFileHTML(StringBuilder sb, string name)
        {
            string _path = basePath + name;
            FileInfo info = new FileInfo(_path);

            eFileInfo fi = new eFileInfo(name);
            string file = _path.toVirtualUrl();
            //bool isImage = ".jpg.jpeg.gif.bmp.png.tif.".IndexOf(fi.fileExtension + ".") > -1;
            bool isImage = eConfig.imageExtensions.Contains(fi.fileExtension);


            sb.Append("<a ext=\"" + fi.fileExtension + "\" href=\"javascript:;\""+ ( isImage ? "" : " onclick=\"viewFile('" + file + "');\"") +" class=\"copypath\" data-clipboard-action=\"copy\" data-clipboard-text=\"" + file + "\" 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;大小：" + info.Size() + "\">\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; 


            if (isImage)
            {
                //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=\"../" + file + "\" /></dt>\r\n");
            }
            else
            {
                sb.Append("<dt class=\"" + eRunTime.getFileClass(fi.fileExtension) + "\"></dt>\r\n");
            }

            sb.Append("<dd>" + name + "</dd>\r\n");
            sb.Append("</dl>\r\n");
            sb.Append("</a>\r\n");
        }
        private string getFiles()
        {
            StringBuilder sb = new StringBuilder();
            eDirectoryInfo edinfo = new eDirectoryInfo(basePath);
            foreach (DirectoryInfo dir in edinfo.GetDirectories())
            {
                sb.Append("<a ext=\"\" href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&path=" + (path.Length > 0 ? path + "/" : path) + dir.Name.ToString() + "\" onmousedown=\"contextmenu(event,this,1,'" + dir.Name + "');\" title=\"" + dir.Name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dir.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dir.LastWriteTime) + "&#10;大小：" + dir.Size() + "\">\r\n");
                sb.Append("<dl>\r\n");
                sb.Append("<dt class=\"folder\"></dt>\r\n");
                sb.Append("<dd>" + dir.Name + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
            }
            foreach (FileInfo file in edinfo.GetFiles())
            {
                getFileHTML(sb, file.Name);
            }
            sb.Append("<div class=\"clear\"></div>\r\n");
            return sb.ToString();
        }
        private string List()
        {
            StringBuilder sb = new StringBuilder();
            #region 当前位置
            //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 + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">" + (model.ModelInfo.Table.Columns.Contains("mc") ? model.ModelInfo["MC"].ToString() : modelName) + "</a>";
                litNav.Text += "&nbsp;<span class=\"pag\">-&gt;</span>&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "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 + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "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;<span class=\"pag\">-&gt;</span>&nbsp;<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">根目录</a>";
            }
            #region 操作按钮
            if (model.Power["new"])
            {
                sb.Append("<a href=\"javascript:;\" class=\"ico addfolder\" onclick=\"file_newFolder();\" title=\"新建文件夹\"></a>");
                sb.Append("<a href=\"javascript:;\" class=\"ico addfile\" onclick=\"file_newFile();\" title=\"新建文件\"></a>");
            }
            if (model.Power["upload"])
            {
                sb.Append("<a href=\"javascript:;\" class=\"ico upload\" title=\"上传文件\">");
                //sb.Append("<input type=\"file\" title=\"上传文件\" class=\"file\" id=\"imgFile\" name=\"imgFile\" badexts=\"" + eConfig.getPreventExtensions() + "\" onchange=\"fileManage_upload(this);\" multiple />");
                sb.Append("<input type=\"file\" title=\"上传文件\" class=\"file\" id=\"imgFile\" name=\"imgFile\" posturl=\"auto\" allowexts=\"" + allowExts.ToString() + "\" preventexts=\"" + eConfig.PreventExtensions.ToString() + "\" accept=\"" + allowExts.ToString(",") + "\" callback=\"autoupload_callback\" onchange=\"autoupload_change(this);\" multiple=\"multiplt\" />");
                
                sb.Append("</a>");
            }
            #endregion
            sb.Append("</div>");
            #endregion

            sb.Append("<div id=\"filemanage_files\" class=\"filemanage_template_files eimages_view\" oncontextmenu=\"return false;\">");
            sb.Append(getFiles());
            sb.Append("</div>");
            return sb.ToString();
        }



    }
}