using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Utils.ORM;
using PageAdmin.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using PageAdmin.Web.Filter;

namespace PageAdmin.Web.Areas.E.Controllers
{
    public class UploadPanelController : BaseController
    {
        private string _SavePath = "/Upload/";
        private string name, userName, parentTable, parentField, fileType,guid,xuhao,_SaveFileName;
        private int uid;
        private bool _DeleteRepeat = false, _SaveToAttachmentData = true, _Rename = true, _SortByDate= true, _sortByFileType=true;

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public async Task<ActionResult>  Index(FormCollection form)
        {
            string rv = "";
            name = form["name"].ToString();//获取文件名
            xuhao = form["id"].Replace("WU_FILE_", "");
            fileType = form["fileType"];
            string[] canFieldType = new string[] { "image", "file", "images", "files" };
            if (!canFieldType.Contains(fileType))
            {
                rv = Result(0, "无效的文件类型参数！");
                return Content(rv);
            }
            CurrentUser user = ViewBag.CurrentUser;
            string reName = StringHelper.Format<string>(form["rename"]);
            if (!string.IsNullOrEmpty(reName))
            {
                _Rename = StringHelper.Format<bool>(reName);
            }

            string savePath= StringHelper.Format<string>(form["savePath"]);
            if(!string.IsNullOrEmpty(savePath))
            {
                _SavePath = savePath;
                if (user == null)
                {
                    rv = Result(0, "自定义路径需要管理员权限");
                    return Content(rv);
                }
                else if (user.RoleId==0)
                {
                    rv = Result(0, "自定义上传路径需要管理员权限");
                    return Content(rv);
                }
            }
            string fileName = StringHelper.Format<string>(form["saveFileName"]);
            if (!string.IsNullOrEmpty(fileName))
            {
                _SaveFileName = fileName;
            }
            string deleteRepeat = StringHelper.Format<string>(form["deleteRepeat"]);
            if (!string.IsNullOrEmpty(deleteRepeat))
            {
                _DeleteRepeat = StringHelper.Format<bool>(deleteRepeat);
            }
            string saveToAttachmentData = StringHelper.Format<string>(form["saveToAttachmentData"]);
            if (!string.IsNullOrEmpty(saveToAttachmentData))
            {
                _SaveToAttachmentData = StringHelper.Format<bool>(saveToAttachmentData);
            }
            string sortByDate = StringHelper.Format<string>(form["sortByDate"]);
            if (!string.IsNullOrEmpty(sortByDate))
            {
                _SortByDate = StringHelper.Format<bool>(sortByDate);
            }
            string sortByFileType = StringHelper.Format<string>(form["sortByFileType"]);
            if (!string.IsNullOrEmpty(sortByFileType))
            {
                _sortByFileType = StringHelper.Format<bool>(sortByFileType);
            }
           
            if (_SaveToAttachmentData)
            {
                parentTable = form["tableName"];
                parentField = form["fieldName"];
                if (!StringHelper.IsStr(parentTable))
                {
                    rv = Result(0, "无效的tableName");
                    return Content(rv);
                }
                if (!StringHelper.IsStr(parentField))
                {
                    rv = Result(0, "无效的parentField");
                    return Content(rv);
                }
                guid = StringHelper.Format<string>(form["guid"]);
                if (!StringHelper.IsStr(guid))
                {
                    rv = Result(0, "无效的guid参数");
                    return Content(rv);
                }
            }
            string fileSize = StringHelper.Format<string>(form["size"]); //webupload自带的尺寸大小
            uid = user.Uid;
            userName = user.UserName;
            if (StringHelper.IsNum(fileSize))
            {
                Action action=()=> rv=Save(form);
                await Task.Run(action);
            }
            return Content(rv);
        }


        private string Save(FormCollection form)
        {
            HttpPostedFileBase hpf = Request.Files["file"];
            int hpfLength = hpf.ContentLength;
            if (hpfLength == 0)
            {
                return Result(0, "emptyfile");
            }
            if(string.IsNullOrEmpty(_SaveFileName))
            {
                _SaveFileName=Path.GetFileNameWithoutExtension(hpf.FileName);
            }
            string fileExt = Path.GetExtension(hpf.FileName).ToLower();
            if (SysHelper.IsForbiddenFileExt(fileExt))
            {
                return Result(0, "禁止的文件格式！");
            }
            string saveDirectory = "";
            bool isImage = false;
            if (hpf.ContentType.Contains("image") && new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" }.Contains(fileExt))
            {
                saveDirectory = "Images";
                isImage = true;
            }
            else
            {
               saveDirectory = "Files";
            }
            //name = name.Replace(fileExt, "");
            if(!_SavePath.StartsWith("/"))
            {
                _SavePath = "/" + _SavePath;
            }
            if (!_SavePath.EndsWith("/"))
            {
                _SavePath =_SavePath+"/";
            }
            string savePath = _SavePath;
            if(_sortByFileType)
            {
                savePath = savePath + saveDirectory + "/";
            }
            DateTime nowdt = DateTime.Now;
            if(_SortByDate)
            {
                string dateDir = nowdt.ToString("yyyy") + "/" + nowdt.ToString("MM") + "/" + nowdt.ToString("dd");
                savePath = savePath + dateDir + "/";
            }
            string fileName;
            if (_Rename)
            {
                fileName = DateTime.Now.ToString("HHmmssfff")+ xuhao+fileExt;
            }
            else
            {
                fileName = _SaveFileName + fileExt;
            }
            savePath = IOHelper.UploadFile(hpf, savePath, fileName, _DeleteRepeat);
            if (this.fileType == "images" || this.fileType == "image")
            {
            }
            else
            {
                isImage = false;
            }
            string watermarkBuild = form["watermark"];
            string thumbnailBuild = form["thumbnail"];
            int thumbnailWidth =StringHelper.Format<int>(form["thumbnailWidth"]);
            int thumbnailHeight = StringHelper.Format<int>(form["thumbnailHeight"]);

            string thumbnail = "";
            if (isImage)
            {
                if (watermarkBuild == "1")
                {
                    savePath = Common.ImageHelper.BuildWaterMark(savePath);
                }
                if (thumbnailBuild == "1")
                {
                    if (this.fileType == "images")
                    {
                        thumbnail = Utils.ImageHelper.BuildThumbnail(savePath, thumbnailWidth, thumbnailHeight,false,"th-");
                    }
                    else if (this.fileType == "image")
                    {
                        savePath= Utils.ImageHelper.BuildThumbnail(savePath, thumbnailWidth, thumbnailHeight,true, "th-");
                    }
                }
                else
                {
                    if (this.fileType == "images")
                    {
                        thumbnail = savePath;
                    }
                }
            }

            int id = InsertData(form, savePath, thumbnail); //插件到附件数据表进行记录和管理
            return Result(1,"success", savePath, thumbnail);
        }

        private int InsertData(FormCollection form, string url, string thumbnail)
        {
            if (_SaveToAttachmentData)
            {
                AttachmentsBLL attachmentDataBLL = new AttachmentsBLL();
                return attachmentDataBLL.Add(parentTable, parentField, guid, userName, url, thumbnail);
            }
            return 0;
        }

        private string Result(int state, string info)
        {
            return Result(state, info, "", "");
        }

        private string Result(int state, string info, string path,string thumbnail)
        {
            string result = "{\"state\" : " + state + ", \"msg\" :\"" + info + "\", \"path\" : \"" + path + "\",\"thumbnail\" : \"" + thumbnail + "\",\"name\" : \"" + name + "\"}";
            return result;
        }

    }
}