
using PageAdmin.BLL;
using PageAdmin.Common;
using PageAdmin.Utils.ORM;
using PageAdmin.Utils;
using PageAdmin.Web.Filter;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.Admin.Controllers
{

    /// <summary>
    /// 数据库增，删，改，查的基类
    /// </summary>
    public class DefaultBaseController : BaseController
    {
        //实例化一个上下文类
        protected MvcControllerContext MvcContext;


        public string CheckExixtsWhere = "";

        protected string EditViewName = "Add";

        protected IListBLL IListBll;
        protected IPageListBLL IPageListBll;
        protected IAddBLL IAddBll;
        protected IEditBLL IEditBll;
        protected IUpdateBLL IUpdateBll;
        protected IDetailBLL IDetailBll;
        protected IDeleteBLL IDeleteBll;
        protected ITransferBLL ITransferBll;
        protected ICheckExistsBLL ICheckExistsBll;

        /// <summary>
        /// 添加编辑数据时候要检测重复的字段字典，格式：字段，字段名
        /// </summary>
        protected Dictionary<string, string> CheckRepeatFieldDic = new Dictionary<string, string>();

        /// <summary>
        /// 列表的更新字典，字段，字段值
        /// </summary>
        protected DbKeyValueList UpdateDbKeyValues = new DbKeyValueList();

        ///// <summary>
        ///// 删除是否检测guid
        ///// </summary>
        //protected bool CheckDeleteGuid = false;
        ///// <summary>
        /////是否内页面获取数据检测guid
        ///// </summary>
        //protected bool CheckDetailGuid = false;

        /// <summary>
        /// 首页的委托
        /// </summary>
        protected Action IndexViewExecuting;

        /// <summary>
        /// 添加前的委托
        /// </summary>
        protected Action AddViewExecuting;

        /// <summary>
        /// 编辑页前的委托
        /// </summary>
        protected Action EditViewExecuting;

        /// <summary>
        /// 添加提交前的委托
        /// </summary>
        protected Action AddExecuting;

        /// <summary>
        /// 编辑提交前的委托
        /// </summary>
        protected Action EditExecuting;

        /// <summary>
        /// 添加提交成功后的委托
        /// </summary>
        protected Action AddExecuted;

        /// <summary>
        /// 编辑提交成功后的委托
        /// </summary>
        protected Action EditExecuted;

        /// <summary>
        /// 执行更新列表前的委托
        /// </summary>
        protected Action UpdateListExecuting;

        /// <summary>
        /// 删除前的委托
        /// </summary>
        protected Action DeleteExecuting;

        /// <summary>
        /// 删除成功后的委托
        /// </summary>
        protected Action DeleteExecuted;

        /// <summary>
        /// 获取列表页数据前的委托
        /// </summary>
        protected Action ListDataExecuting;

        /// <summary>
        /// 获取列表页数据后的委托
        /// </summary>
        protected Action ListDataExecuted;
        /// <summary>
        /// 获取内容页数据前的委托
        /// </summary>
        protected Action DetailDataExecuting;

        /// <summary>
        /// 设置字段前的委托
        /// </summary>
        protected Action SetFieldExecuting;

        protected dynamic EditDetailData;

        /// <param name="table">表名</param>
        /// <param name="directory">分类目录</param>
        protected DefaultBaseController(string table, string directory = "") : base(directory)
        {
            MvcContext = new MvcControllerContext();
            if (string.IsNullOrEmpty(table))
            {
                table = System.Web.HttpContext.Current.Request.QueryString["table"];
            }
            MvcContext.Table = table;
            MvcContext.From = FromEnum.Admin;
        }


        //在这里设置上下文数据,不放在构造函数中应为过滤器中ViewBag在构造函数阶段还未赋值！
        protected override void OnActionExecuting(ActionExecutingContext context)
        {
            base.CurrentUser = ViewBag.CurrentUser;
            ViewBag.Uid = base.CurrentUser.Uid;
            ViewBag.Table = MvcContext.Table;
            MvcContext.CurrentUser = base.CurrentUser;
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 执行完毕后清理缓存
        /// </summary>
        /// <param name="context"></param>
        protected override void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.RequestContext.HttpContext.Request.HttpMethod == "POST")
            {
                if (!string.IsNullOrEmpty(MvcContext.Table))
                {
                    CacheHelper.RemoveDbCache(MvcContext.Table);
                }
            }
            base.OnActionExecuted(context);
        }


        [HttpGet]
        public virtual ActionResult Index()
        {
            MvcContext.Data = Request.QueryString;
            IndexViewExecuting?.Invoke();
            //ActionExtendBLL.OnExecuting(MvcContext);//扩展点
            return View();
        }


        ///// <summary>
        ///// 内容页面ajax数据
        ///// </summary>
        ///// <returns></returns>
        //[AjaxOnly]
        //[HttpGet]
        //public virtual JsonResult DetailData()
        //{
        //    var form = Request.QueryString;
        //    MvcContext.Data = form;
        //    int Id = StringHelper.Format<int>(form["id"]);
        //    if (CheckDetailGuid)
        //    {
        //        bool isOkGuid = CheckGuid(form);
        //        if (!isOkGuid)
        //        {
        //            return null;
        //        }
        //    }
        //    DetailDataExecuting?.Invoke();
        //    if (IDetailBll == null)
        //    {
        //        IDetailBll = new DetailBLL();
        //    }
        //    return Json(IDetailBll.Detail(MvcContext));
        //}


        /// <summary>
        /// 获取列表数ajax数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        [NotCheckMenuItemPermissions]
        public virtual JsonResult ListData()
        {
            NameValueCollection form = new NameValueCollection();
            form.Add(Request.QueryString);
            MvcContext.Data = form;
            ListDataExecuting?.Invoke();
            //ActionExtendBLL.OnExecuting(MvcContext);//扩展点
            if (MvcContext.TipsInfo.State == 0)
            {
                return null;
            }
            if (IListBll == null)
            {
                IListBll = new ListBLL();
            }
            IEnumerable<dynamic> dataList = IListBll.List(MvcContext);
            ListDataExecuted?.Invoke();
            //ActionExtendBLL.OnExecuted(MvcContext);//扩展点
            return Json(dataList);
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        [NotCheckMenuItemPermissions]
        public virtual JsonResult PageListData()
        {
            NameValueCollection form = new NameValueCollection();
            form.Add(Request.QueryString);
            MvcContext.Data = form;
            PageInfo pageInfo = MvcContext.PageInfo;
            ListDataExecuting?.Invoke();

            if (MvcContext.TipsInfo.State == 0)
            {
                return null;
            }
            if (IPageListBll == null)
            {
                IPageListBll = new ListBLL();
            }
            IEnumerable<dynamic> dataList = IPageListBll.PageList(MvcContext);
            ListDataExecuted?.Invoke();

            return Json(dataList, pageInfo);
        }

        /// <summary>
        /// 列表页的更新,每条记录更新值不一样
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public virtual JsonResult UpdateList(FormCollection form)
        {
            MvcContext.Data = form;
            UpdateListExecuting?.Invoke();

            //ActionExtendBLL.OnExecuting(MvcContext); //扩展点

            TipsInfo tipsInfo = MvcContext.TipsInfo;
            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }
            if (IUpdateBll == null)
            {
                IUpdateBll = new UpdateBLL();
            }
            if (UpdateDbKeyValues.Count==0)
            {
                UpdateDbKeyValues.Add("xuhao", StringHelper.Format<int>(MvcContext.Data["xuhao"]));
            }
            tipsInfo = IUpdateBll.Update(MvcContext, UpdateDbKeyValues);

            //ActionExtendBLL.OnExecuted(MvcContext); //扩展点

            return Json(tipsInfo);
        }


        /// <summary>
        /// 根据id获取对应字段,多个id用半角逗号隔开
        /// </summary>
        /// <returns></returns>
        [AjaxOnly]
        [NotCheckMenuItemPermissions]
        [HttpGet]
        public virtual JsonResult GetFieldByIds()
        {
            MvcContext.Data = Request.QueryString;
            GetFieldByIdsBLL bll = new GetFieldByIdsBLL();
            IEnumerable<dynamic> data = bll.Get(MvcContext);
            return Json(data);
        }


        /// <summary>
        /// 根据id等参数获取数据,应用场景获取数据并填充到select
        /// </summary>
        /// <returns></returns>

        [HttpGet]
        [NotCheckMenuItemPermissions]
        [AjaxOnly]
        public virtual JsonResult LoadListByIds()
        {
            MvcContext.Data = Request.QueryString;
            LoadListByIdsBLL bll = new LoadListByIdsBLL();
            IEnumerable<dynamic> data = bll.LoadListByIds(MvcContext);
            return base.Json(data);
        }

        ///// <summary>
        ///// 载入列表,主要用于填充select或select界面
        ///// </summary>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAllUser]
        //[AjaxOnly]
        //public virtual JsonResult LoadList()
        //{
        //    MvcContext.Data = Request.QueryString;
        //    LoadListByIdsBLL bll = new LoadListByIdsBLL();
        //    IEnumerable<dynamic> data = bll.LoadList(MvcContext);
        //    return base.Json(data);
        //}

        /// <summary>
        /// 主要用于列表页设置字段值，主要用于多条或一条记录设置同一个字段值
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [AjaxOnly]
        [HttpPost]
        public virtual JsonResult SetField(FormCollection form)
        {
            MvcContext.Data = form;
            MvcContext.SqlCondition = null;
            SetFieldExecuting?.Invoke();
            TipsInfo tipsInfo = MvcContext.TipsInfo;
            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }

            SetFieldBLL bll = new SetFieldBLL();
            tipsInfo = bll.SetField(MvcContext);

            //ActionExtendBLL.OnExecuted(MvcContext); //扩展点

            return Json(tipsInfo);
        }


        [HttpGet]
        public virtual ActionResult Add()
        {
            MvcContext.Data = Request.QueryString;
            AddViewExecuting?.Invoke();
            //ActionExtendBLL.OnExecuting(MvcContext); //扩展点
            return View();
        }

        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [HttpPost]
        [AjaxOnly]
        public virtual JsonResult Add(FormCollection form)
        {
            MvcContext.Data = form;
            AddExecuting?.Invoke();//提交前的委托
            //ActionExtendBLL.OnExecuting(MvcContext); //扩展点

            TipsInfo tipsInfo = MvcContext.TipsInfo;
            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }
            if (IAddBll == null)
            {
                IAddBll = new AddBLL();
            }
            if (ICheckExistsBll == null)
            {
                ICheckExistsBll = new CheckExistsBLL();
            }
            tipsInfo = ICheckExistsBll.CheckExists(MvcContext, CheckRepeatFieldDic, 0, MvcContext.Data, CheckExixtsWhere, tipsInfo);
            if (tipsInfo.State == 1)
            {
                tipsInfo = IAddBll.Add(MvcContext);
            }
            if (tipsInfo.State == 1)
            {
                AddExecuted?.Invoke();//提交成功后的委托
            }
            //ActionExtendBLL.OnExecuted(MvcContext); //扩展点
            return Json(tipsInfo);
        }

        [NonAction]
        protected dynamic DetailData()
        {
            NameValueCollection form = Request.QueryString;
            MvcContext.Data = form;
            if (IDetailBll == null)
            {
                IDetailBll = new DetailBLL();
            }
            return IDetailBll.Detail(MvcContext);
        }

        
        [HttpGet]
        public virtual ActionResult Edit()
        {
            NameValueCollection form = Request.QueryString;
            MvcContext.Data = form;
            TipsInfo tipsInfo = MvcContext.TipsInfo;
            if (IDetailBll == null)
            {
                IDetailBll = new DetailBLL();
            }
            EditDetailData = IDetailBll.Detail(MvcContext);
            EditViewExecuting?.Invoke();
            return View(EditViewName,(object)JsonHelper.JsonParse(EditDetailData));
        }


        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        [HttpPost]
        [AjaxOnly]
        public virtual JsonResult Edit(FormCollection form)
        {
            MvcContext.Data = form;
            TipsInfo tipsInfo = MvcContext.TipsInfo;
            EditExecuting?.Invoke();//提交前的委托

            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }
            if (IEditBll == null)
            {
                IEditBll = new EditBLL();
            }
            int id = StringHelper.Format<int>(MvcContext.Data["id"]);
            if (ICheckExistsBll == null)
            {
                ICheckExistsBll = new CheckExistsBLL();
            }
            tipsInfo = ICheckExistsBll.CheckExists(MvcContext, CheckRepeatFieldDic, id, MvcContext.Data, CheckExixtsWhere, tipsInfo);
            if (tipsInfo.State == 1)
            {
                tipsInfo = IEditBll.Edit(MvcContext);
            }
            if (tipsInfo.State == 1)
            {
                EditExecuted?.Invoke();//提交成功后的委托
            }
            return Json(tipsInfo);
        }


        [HttpPost]
        [AjaxOnly]
        public virtual JsonResult Delete(FormCollection form)
        {
            MvcContext.Data = form;
            TipsInfo tipsInfo = MvcContext.TipsInfo;

            DeleteExecuting?.Invoke();//删除前的委托
            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }

            if (tipsInfo.State == 0)
            {
                return Json(tipsInfo);
            }
            if (IDeleteBll == null)
            {
                IDeleteBll = new DeleteBLL();
            }
            tipsInfo = IDeleteBll.Delete(MvcContext);
            if (tipsInfo.State == 1)
            {
                DeleteExecuted?.Invoke();//删除成功后的委托
            }
            //ActionExtendBLL.OnExecuted(MvcContext); //扩展点
            return Json(tipsInfo);
        }


        /// <summary>
        /// 转移分类
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Transfer()
        {
            return View();
        }

        /// <summary>
        /// 分类转移
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public JsonResult Transfer(FormCollection form)
        {
            MvcContext.Data = form;
            //ActionExtendBLL.OnExecuting(MvcContext); //扩展点
            TipsInfo tipsInfo = MvcContext.TipsInfo;
            if (tipsInfo.State == 0)
            {
                Json(tipsInfo);
            }
            if (ITransferBll == null)
            {
                ITransferBll = new TransferBLL();
            }
            tipsInfo = ITransferBll.Transfer(MvcContext);
            //ActionExtendBLL.OnExecuted(MvcContext); //扩展点
            return Json(tipsInfo);
        }


        //field不存在会报错,只能后台使用,此功能用于表单的checkUrl调用进行重复性检测
        [HttpPost]
        [AjaxOnly]
        public JsonResult CheckExists(FormCollection form)
        {
            MvcContext.Data = form;
            if (ICheckExistsBll == null)
            {
                ICheckExistsBll = new CheckExistsBLL();
            }
            string fieldName = Request.QueryString["fieldName"];
            int id = StringHelper.Format<int>(Request.QueryString["id"]);
            string validateName = StringHelper.Format<string>(MvcContext.Data["_validateName"]);
            string fieldValue = StringHelper.Format<string>(MvcContext.Data[validateName]);
            var tipsInfo = ICheckExistsBll.CheckExists(MvcContext,id, fieldName, validateName, fieldValue, CheckExixtsWhere);
            return Json(tipsInfo);
        }


    }
}