using System;
using System.Linq;
using System.Web.Mvc;
using PageAdmin.Common;using PageAdmin.ORM;using PageAdmin.Utils;
using PageAdmin.BLL;

namespace PageAdmin.Web.Areas.E.Views.AttachmentData.Filter
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
    public class CheckParamAttribute : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request.QueryString;
            int fieldId = StringHelper.Format<int>(request["field_id"]);
            if (fieldId == 0)
            {
                Error(filterContext,"无效的field_id参数！");
                return;
            }
            FieldBLL fieldBll = new FieldBLL();
            dynamic fieldData = fieldBll.GetData(fieldId);
            if (fieldData == null)
            {
                Error(filterContext, "field_id参数不正确！");
                return;
            }
            string fieldType = fieldData.field_type;
            string[] arrFieldType = new string[] { "images", "fiels" };
            if (!arrFieldType.Contains(fieldType))
            {
                Error(filterContext, "field_id对应的field_type类型不匹配！");
                return;
            }
            AttachmentTableBLL attachmentTableBLL = new AttachmentTableBLL();
            string attachmentTable = attachmentTableBLL.GetName(fieldData.table_name, fieldData.name);
            if(string.IsNullOrEmpty(attachmentTable))
            {
                Error(filterContext, "找不到附件表！");
                return;
            }
            filterContext.Controller.ViewBag.FieldData = fieldData;
            filterContext.Controller.ViewBag.AttachmentTable = attachmentTable;
        }

        public void Error(ActionExecutingContext filterContext, string content)
        {
            filterContext.Result = new ContentResult
            {
                ContentType = "text/html",
                Content = content
            };
        }
    }
}