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.Manage
{
    public partial class DBManage : System.Web.UI.Page
    {
        public string UserArea = "Manage";
        public string act = eParameters.Request("act");
        public string ModelID = eParameters.Request("ModelID");
        public string AppItem = eParameters.Request("AppItem");
        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 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["restore"] = 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(".bak.zip");
        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 = eRunTime.dbbackupPath;
            if (!Directory.Exists(basePath)) Directory.CreateDirectory(basePath);


          

            #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 ext = "";
            DataTable tb;
            string reurl = "";
            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 "ddbc":
                    //2005:DUMP TRANSACTION EKEFrameV9 WITH NO_LOG;BACKUP LOG EKEFrameV9 WITH NO_LOG;DBCC SHRINKDATABASE (EKEFrameV9);
                    string sql = "ALTER DATABASE " + eBase.DataBase.DataBase + " SET RECOVERY SIMPLE;DBCC SHRINKDATABASE(" + eBase.DataBase.DataBase + " , 0);ALTER DATABASE " + eBase.DataBase.DataBase + " SET RECOVERY FULL;";
                    eBase.DataBase.Execute(sql);
                    //Response.Redirect("DBManage.aspx", true);
                    Response.Write("<script>alert('收缩成功!');document.location.href='DBManage.aspx';</script>");
                    Response.End();
                    break;
                case "backup"://OK
                    #region 备份数据库
                    if (!Power["backup"]) eResult.Error("没有权限!");
                    name = name.Split(".".ToCharArray())[0] + ".bak";
                    if (File.Exists(basePath + name)) eResult.Error("文件已经存在,备份失败!");
                    Backup(basePath + name);
                    eResult.Success("备份成功!");
                    #endregion
                    break;
                case "restore"://OK
                    #region 还原数据库
                    if (!Power["restore"]) eResult.Error("没有权限!");
                    name = name.Split(".".ToCharArray())[0] + ".bak";
                    if (!File.Exists(basePath + name)) eResult.Error("文件不存在,备份失败!");
                    Restore(basePath + name);
                    eResult.Success("数据库还原成功!");
                    #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);
                        #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")//文件
                    {
                        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 = "../upload/" +  (path.Length > 0 ?  path + "/" : "")  + name;
            //FileInfo info = new FileInfo(Server.MapPath( _path));

            string _path = basePath + name;
            FileInfo info = new FileInfo(_path);
            eFileInfo fi = new eFileInfo(name);
            string file = _path.toVirtualUrl();

            sb.Append("<a ext=\"" + fi.fileExtension + "\" href=\"javascript:;\" 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.fileExtension + ".") > -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=\"../" + 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();
            //DirectoryInfo dinfo = new DirectoryInfo(basePath);
            eDirectoryInfo dinfo = new eDirectoryInfo(basePath);
            foreach (DirectoryInfo folder in dinfo.getDirectories())
            {
                sb.Append("<a ext=\"\" href=\"" + aspxFile + "?" + (ModelID.Length > 0 ? "ModelID=" + ModelID + "&" : "") + "path=" + (path.Length > 0 ? path + "/" : path) + folder.Name.ToString() + "\" onmousedown=\"contextmenu(event,this,1,'" + folder.Name + "');\" title=\"" + folder.Name + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", folder.CreationTime) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", folder.LastWriteTime) + "&#10;大小：" + folder.Size() + "\">\r\n");
                sb.Append("<dl>\r\n");
                sb.Append("<dt class=\"folder\"></dt>\r\n");
                sb.Append("<dd>" + folder.Name + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
            }
            foreach (FileInfo file in dinfo.getFiles())
            {
                getFileHTML(sb, file.Name);
            }
            sb.Append("<div class=\"clear\"></div>\r\n");
            return sb.ToString();
        }
        private string List()
        {
            StringBuilder sb = new StringBuilder();


            string sql = "SELECT DB_NAME(database_id) AS [Database Name],[Name] AS [Logical Name],[Physical_Name] AS [Physical Name],((size * 8) / 1024) AS [Size(MB)],[differential_base_time] AS [Differential Base Time]";
            sql = "SELECT Name,((size * 8) / 1024) AS Size";
            sql += " FROM sys.master_files";
            sql += " WHERE DB_NAME(database_id) IN ('" + eBase.DataBase.DataBase + "') order by type";
            DataTable tb = eBase.DataBase.getDataTable(sql);
            foreach (DataRow dr in tb.Rows)
            {
                sb.Append("<div>" + dr["name"].ToString() + "：" + dr["size"].ToString() + " MB</div>");
            }
            sb.Append("<hr>");

            #region 当前位置
            //sb.Append("<div>当前位置：");
            sb.Append("<div class=\"filemanage_tool\" style=\"margin-tottom:8px;\">");
            if (path.Length > 0)
            {
                litNav.Text = "<a href=\"" + aspxFile + (ModelID.Length > 0 ? "?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>";
                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
            {

                litNav.Text = "根目录";
                //sb.Append("根目录");
                //litNav.Text = "<a href=\"" + aspxFile + (ModelID.Length > 0 ? "?ModelID=" + ModelID : "") + "\">" + (model.ModelInfo.Table.Columns.Contains("mc") ? model.ModelInfo["MC"].ToString() : modelName) + "</a>";

            }
            //if (model.Power.Table.Columns.Contains("new") && model.Power["new"].ToString().ToLower() == "true")
            //{
            sb.Append("<a href=\"javascript:;\" class=\"ico dbbackup\" onclick=\"backup();\" title=\"备份数据库\"></a>");
            //}

            //if (model.Power.Table.Columns.Contains("upload") && model.Power["upload"].ToString().ToLower() == "true")
            // {
            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>");
            //}

            sb.Append("</div>");
            #endregion

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


        private void Backup(string bakpath)
        {
            string dbname = eBase.DataBase.DataBase;
            string sql = "BACKUP DATABASE [" + dbname + "] TO DISK = '" + bakpath + "' With format,init";
            eBase.DataBase.Execute(sql);
        }
        private void Restore(string bakpath)
        {
            string dbname = eBase.DataBase.DataBase;
            string sql = "select spid from  master..sysprocesses  where db_name(dbid)= '" + dbname + "'";
            DataTable tb = eBase.DataBase.getDataTable(sql);
            foreach (DataRow dr in tb.Rows)
            {
                eBase.DataBase.Execute("exec('kill " + dr["spid"].ToString() + "')");
            }
            eBase.DataBase.Execute("use master ");
            sql = "RESTORE DATABASE " + dbname + " FROM DISK='" + bakpath + "' WITH REPLACE,RECOVERY";
            eBase.DataBase.Execute(sql);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            if (Master == null) return;
            Literal lit = (Literal)Master.FindControl("LitTitle");
            if (lit != null)
            {
                lit.Text = modelName + " - " + eConfig.manageName();
            }
        }
    }
}