using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Filter;
using System;
using System.Linq;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.Admin.Controllers
{

    /// <summary>
    /// 文件管理的基类
    /// </summary>
    public class FileManageBaseController : BaseController
    {
        protected string RootPath = "/";
        protected Func<dynamic,bool> FuncCondition=null;
        protected string ListOrder;
        FileManagerBLL fileManagerbll;
        protected Action IndexViewExecuting; //首页加载前的委托
        private string _PublicViewPath;

        public FileManageBaseController(string rootPath,string classifyDirectory) : base(classifyDirectory)
        {
            _PublicViewPath = "~/Areas/Admin/Views/Tool/FileManager/";
            ListOrder = "CreationTime desc";
            fileManagerbll = new FileManagerBLL();
            RootPath = rootPath;
        }


        [HttpGet]
        public ActionResult Index()
        {
            IndexViewExecuting?.Invoke();
            ViewBag.CurrentPath = StringHelper.Format<string>(Request.QueryString["path"]);
            return View();
        }

        public JsonResult ListData()
        {
            string currentPath = StringHelper.Format<string>(Request.QueryString["path"]);
            var dataList = fileManagerbll.List(RootPath,currentPath, ListOrder, FuncCondition);
            return Json(dataList);
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        public virtual JsonResult PageListData()
        {
            var form = Request.QueryString;
            PageInfo pageInfo = new PageInfo();
            string currentPath = StringHelper.Format<string>(form["path"]);
            var dataList = fileManagerbll.PageList(form, RootPath, currentPath,pageInfo, ListOrder, FuncCondition);
            return Json(dataList, pageInfo);
        }

        [HttpGet]
        public FilePathResult DownFile()
        {
            string filePath = RootPath+"/"+Request.QueryString["path"];
            string ext = System.IO.Path.GetExtension(Server.MapPath(filePath));
            string[] picExt = new string[] { ".jpg", ".gif", ".png", ".jpeg", ".bmp" };
            //string mineType = "application/zip-x-compressed";
            if (filePath != "")
            {
                string fileName = filePath.Split('/').Last();
                filePath = filePath.Replace("//", "/");
                if (picExt.Contains(ext))
                {
                    return File(filePath, @"image/" + ext.Replace(".", ""));
                }
                else
                {
                    return DownFile(filePath);
                }
            }
            else
            {
                return null;
            }
        }

        [HttpPost]
        public JsonResult Delete(FormCollection form)
        {
            bool isDirectory = false;
            if(form["type"] == "directory")
            {
                isDirectory = true;
            }
            string Path = form["path"];
            string DelName = form["name"];
            return Json(fileManagerbll.Delete(RootPath,Path,DelName,isDirectory));
        }


        [HttpGet]
        public ActionResult AddFolder()
        {
            string path = Request.QueryString["path"];
            if (!string.IsNullOrEmpty(path))
            {
                ViewBag.Path = path;
            }
            string viewName = _PublicViewPath + RouteData.Values["action"].ToString() + ".cshtml";
            return View(viewName);
        }

        [HttpGet]
        public ActionResult AddFile()
        {
            string path = Request.QueryString["path"];
            if (!string.IsNullOrEmpty(path))
            {
                ViewBag.Path = path;
            }
            string viewName = _PublicViewPath + RouteData.Values["action"].ToString() + ".cshtml";
            return View(viewName);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult AddFolder(FormCollection form)
        {
            string path = form["path"];
            string folderName = StringHelper.Format<string>(form["name"]);
            var tipsInfo = fileManagerbll.AddDirectory(RootPath, path, folderName);
            return Json(tipsInfo);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult AddFile(FormCollection form)
        {
            string path = form["path"];
            string folderName = StringHelper.Format<string>(form["name"]);
            var tipsInfo = fileManagerbll.AddFile(RootPath, path, folderName);
            return Json(tipsInfo);
        }

        [HttpGet]
        public ActionResult ReName()
        {
            string path = Request.QueryString["path"];
            string name = Request.QueryString["name"];
            ViewBag.Path = path;
            ViewBag.Name = name;
            string viewName = _PublicViewPath + RouteData.Values["action"].ToString() + ".cshtml";
            return View(viewName);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public JsonResult ReName(FormCollection form)
        {
            string path = form["path"];
            string name = form["name"];
            string newFileName = form["newFileName"];
            string newDirectoryName = form["newDirectoryName"];
            string type= form["type"];
            TipsInfo tipsInfo = null;
            if(type=="file")
            {
                tipsInfo=fileManagerbll.MoveFile(RootPath, path, name, newFileName);
            }
            else
            {
                tipsInfo = fileManagerbll.MoveDirectory(RootPath, path, name, newDirectoryName);
            }
            return Json(tipsInfo);
        }


        [HttpGet]
        public ActionResult Edit()
        {
            string path = Request.QueryString["path"];
            string name = Request.QueryString["name"];
            if (!string.IsNullOrEmpty(name))
            {
                ViewBag.Name = name;
                ViewBag.Path = path;
                string ext = name.Split('.').Last();
                string canReadExt = XmlHelper.NodeValue("Config/CanReadExt", "/Config/FileEdit.config");
                string[] arrCanReadExt = canReadExt.Split(',');
                if (!string.IsNullOrEmpty(path))
                {
                    path = path + "/";
                }
                path = RootPath + path+ name;
                if (arrCanReadExt.Contains(ext))
                {
                    ViewBag.Content = IOHelper.ReadFile(path);
                }
                else
                {
                    ViewBag.NotRead = "true";
                }
            }
            else
            {
                throw new Exception("无效的name参数!");
            }
            string viewName = _PublicViewPath + RouteData.Values["action"].ToString() + ".cshtml";
            return View(viewName);
            return View();
        }

        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [HttpPost]
        public JsonResult Edit(FormCollection form)
        {
            string path = form["path"];
            string name = form["name"];
            string content = form["content"];
            return Json(fileManagerbll.UpdateFile(RootPath, path, name,content));
        }


        /// <summary>
        /// 分片下载大文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        protected FilePathResult DownFile(string filePath)
        {
            filePath = IOHelper.MapPath(filePath);
            if (IOHelper.FileIsExists(filePath))
            {
                System.IO.FileStream fs = null;
                byte[] fileBuffer = new byte[1024];//每次读取1024字节大小的数据
                try
                {
                    using (fs = System.IO.File.OpenRead(filePath))
                    {
                        long totalLength = fs.Length;
                        Response.ContentType = "application/octet-stream";
                        string fileName = System.IO.Path.GetFileName(filePath);
                        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);// HttpUtility.UrlEncode(fileName,Encoding.UTF8));
                        while (totalLength > 0 && Response.IsClientConnected)//持续传输文件
                        {
                            int length = fs.Read(fileBuffer, 0, fileBuffer.Length);//每次读取1024个字节长度的内容
                            fs.Flush();
                            Response.OutputStream.Write(fileBuffer, 0, length);//写入到响应的输出流
                            Response.Flush();//刷新响应
                            totalLength = totalLength - length;
                        }
                        Response.Close();//文件传输完毕，关闭相应流
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                }
                finally
                {
                    if (fs != null)
                        fs.Close();//最后记得关闭文件流
                }
            }
            return null;
        }

    }
}