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 eFiles : 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 eModel model;



        public string pid = eParameters.QueryString("pid");
        public string id = eParameters.QueryString("id");
        string aspxFile = eBase.getAspxFileName();
        string type = eParameters.QueryString("type");
        public string ajax = eParameters.QueryString("ajax");

        protected void Page_Load(object sender, EventArgs e)
        {
            user = new eUser(eBase.getUserArea(UserArea));
            user.Check();
            eModelInfo customModel = new eModelInfo(user);
            model = customModel.Model;
            #region 安全性
            if (act.Length > 0 && (Request.UrlReferrer == null || Request.Url.Host.ToLower() != Request.UrlReferrer.Host.ToLower()))
            {
                Response.Write("访问未被许可!");
                Response.End();
            }
            #endregion
            #region 操作
            eTable etb;
            string basePath = "";
            string filepath = "";
            string oldname = "";
            string newname = "";
            string reurl = "";
            string sql = "";
            DataTable tb;
            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 "save"://OK
                    #region 保存

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

                    etb = new eTable("eFiles", user);
                    etb.Fields.Add("Body", value);
                    etb.Where.Add("FileID='" + id + "'");
                    etb.Update();

                    eResult.Success("保存成功!");
                    #endregion
                    break;
                case "edit"://OK
                    #region 读取

                    string content = eBase.DataBase.getValue("select Body from eFiles where FileID='" + id + "'");
                    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 新建文件
                    etb = new eTable("eFiles", user);
                    etb.Fields.Add("Name", name);
                    if (pid.Length > 0) etb.Fields.Add("FolderID", pid);
                    etb.Add();
                    if (ajax == "true")
                    {
                        if (etb.ID.Length == 0)
                        {
                            eResult.Error("文件创建失败,可能原因：eFiles表不存在!");
                        }
                        else
                        {
                            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 添加文件夹
                    etb = new eTable("eFolders", user);
                    etb.Fields.Add("Name", name);
                    if (pid.Length > 0) etb.Fields.Add("ParentID", pid);
                    etb.Add();

                    if (ajax == "true")
                    {
                        if (etb.ID.Length == 0)
                        {
                            eResult.Error("文件夹创建失败,可能原因：eFolders表不存在!");
                        }
                        else
                        {
                            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 重命名文件、文件夹
                    newname = eParameters.QueryString("newname");
                    if (type == "1")//文件夹
                    {
                        etb = new eTable("eFolders", user);
                        etb.Fields.Add("Name", newname);
                        etb.Where.Add("FolderID='" + id + "'");
                        etb.Update();
                        
                    }
                    if (type == "2")//文件
                    {
                        etb = new eTable("eFiles", user);
                        etb.Fields.Add("Name", newname);
                        etb.Where.Add("FileID='" + id + "'");
                        etb.Update();
                    }
                    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 "del"://OK
                    #region 删除文件、文件夹
                    string tmpPath = basePath + name;
                    if (type == "1")//文件夹
                    {
                        etb = new eTable("eFolders", user);
                        etb.Where.Add("FolderID='" + id + "'");
                        etb.Delete();
                    }
                    if (type == "2")//文件
                    {
                        etb = new eTable("eFiles", user);
                        etb.Where.Add("FileID='" + id + "'");
                        etb.Delete();

                    }
                    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 "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 "getjson": //OK
                    #region 读取数据
                    json = new JsonData();
                    json["success"] = "1";

                    sql = "SELECT DataViewID as value,MC as text FROM a_eke_sysDataViews where delTag=0 order by addTime desc";
                    tb = eBase.DataBase.getDataTable(sql);
                    json["viewJson"] = tb.toJSONData();
 

                    sql = "SELECT DataContentID as value,MC as text FROM a_eke_sysDataContents where delTag=0 order by addTime desc";
                    tb = eBase.DataBase.getDataTable(sql);
                    json["contentJson"] = tb.toJSONData();



                    //1fa0dde6-decf-466b-8dec-12ba8ae0bd7a 网站信息模块
                    sql = "select code as value,mc as text from a_eke_sysModelItems where ModelID='1fa0dde6-decf-466b-8dec-12ba8ae0bd7a' and delTag=0 AND Custom = 0 AND SYS = 0 AND showAdd = 1 order by AddOrder,px,addTime";
                    tb = eBase.DataBase.getDataTable(sql);
                    json["siteJson"] = tb.toJSONData();
                    json["message"] = "加载成功!";
                    eResult.WriteJson(json);
                    #endregion
                    break;
                case "": //OK
                    #region 列表
                    litBody.Text = List();
                    #endregion
                    break;
            }
            #endregion
        }      

        private string getFiles()
        {
            string sql = "select * from eFolders where deltag=0";
            sql += pid.Length == 0 ? " and ParentID is null" : " and ParentID='" + pid + "'";
            DataTable tb = eBase.DataBase.getDataTable(sql);

            StringBuilder sb = new StringBuilder();
            foreach (DataRow dr in tb.Rows)
            {
                sb.Append("<a ext=\"\" href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "&pid=" + dr["FolderID"].ToString() + "\" onmousedown=\"contextmenu(event,this,1,'" + dr["Name"].ToString() + "','" + dr["FolderID"].ToString() + "');\" title=\"" + dr["Name"].ToString() + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["addTime"]) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["editTime"]) + "\">\r\n");
                sb.Append("<dl>\r\n");
                sb.Append("<dt class=\"folder\"></dt>\r\n");
                sb.Append("<dd>" + dr["Name"].ToString() + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");
            }

            sql = "select * from eFiles where deltag=0";
            sql += pid.Length == 0 ? " and FolderID is null" : " and FolderID='" + pid + "'";
            tb = eBase.DataBase.getDataTable(sql);
            foreach (DataRow dr in tb.Rows)
            {
                sb.Append("<a href=\"javascript:;\" onclick=\"file_view('" + dr["Name"].ToString() + "','" + dr["FileID"].ToString() + "');\" onmousedown=\"contextmenu(event,this,2,'" + dr["Name"].ToString() + "','" + dr["FileID"].ToString() + "');\" title=\"" + dr["Name"].ToString() + "&#10;创建时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["addTime"]) + "&#10;修改时间：" + string.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["editTime"]) + "&#10;" + "\">\r\n");
                sb.Append("<dl>\r\n");
                sb.Append("<dt class=\"text\"></dt>\r\n");

                sb.Append("<dd>" + dr["Name"].ToString() + "</dd>\r\n");
                sb.Append("</dl>\r\n");
                sb.Append("</a>\r\n");

            }   
            sb.Append("<div class=\"clear\"></div>\r\n");
            return sb.ToString();
        }

        private string getParName(string _pid)
        {
            string temp = "";
            dynamic obj = eBase.DataBase.getValues("select FolderID,ParentID,Name from eFolders where FolderID='" + _pid + "'");
            if (obj.success)
            {
                temp = "&nbsp;<span class=\"pag\">-&gt;</span>&nbsp;<a href=\"?AppItem=" + AppItem + "&pid=" + _pid + "\">" + obj["Name"] + "</a>";
                if (obj["ParentID"].ToString().Length > 0) temp = getParName(obj["ParentID"]) + temp;
               // obj["success"]

            }
            return temp;
        }
        private string List()
        {
            StringBuilder sb = new StringBuilder();
            #region 当前位置
            //sb.Append("<div>当前位置：");
            sb.Append("<div class=\"filemanage_tool\" style=\"margin-tottom:8px;\">");
            litNav.Text = "<a href=\"" + aspxFile + "?" + (AppItem.Length > 0 ? "AppItem=" + AppItem : "ModelID=" + ModelID) + "\">" + model.ModelInfo["MC"].ToString() + "</a>";
            if (pid.Length > 0)
            {
                //litNav.Text += "&nbsp;->&nbsp;a";
                litNav.Text += getParName(pid);
            }


            if ( model.Power["add"])
            {
                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>");
            }            
            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();
        }
    }
}