using Newtonsoft.Json;
using PageAdmin.Utils;
using System;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.E.Controllers.UEditor.Filter
{
    public class EditorUploadFilter : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            CheckParams(filterContext);
        }

        protected void CheckParams(ActionExecutingContext filterContext)
        {
            var result = new
            {
                state = "检测自定义参数tableName，fieldName和guid参数是否正确",
                url = "",
                title = "",
                original = "",
                error = "参数错误"
            };
            var Request = filterContext.RequestContext.HttpContext.Request;
            var Response = filterContext.HttpContext.Response;
            string jsonpCallback = Request["callback"],
                tableName = Request["tableName"],
                fieldName = Request["fieldName"],
                guid = Request["guid"],
                json = JsonConvert.SerializeObject(result);

            //检测参数
            if (!StringHelper.IsStr(tableName) || !StringHelper.IsStr(fieldName) || !StringHelper.IsStr(guid))
            {
                if (String.IsNullOrWhiteSpace(jsonpCallback))
                {
                    //filterContext.HttpContext.Response.AddHeader("Content-Type", "");
                    //Response.Write(json);
                    filterContext.Result = new ContentResult()
                    {
                        Content = json,
                        ContentType = "text/plain"
                    };
                }
                else
                {
                    //Response.AddHeader("Content-Type", "application/javascript");
                    //Response.Write(String.Format("{0}({1});", jsonpCallback, json));
                    filterContext.Result = new JavaScriptResult()
                    {
                        Script = String.Format("{0}({1});", jsonpCallback, json)
                    };
                }
            }
            //Response.End();
        }

    }
}